From stephan.diehlNOSPAM at gmx.net Tue Dec 30 09:44:38 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Tue, 30 Dec 2003 15:44:38 +0100 Subject: Some optimization tale References: <0gf0vv4o95ql695fkgemodebdlgvvsh7u7@4ax.com> <3fr2vvo7ubmgkuo7u5s7cf90fh8ge34l12@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Mon, 29 Dec 2003 17:08:39 +0100, rumours say that Stephan Diehl > might have written: > >>> You might also want to read: >>> >>> http://www.python.org/sf/681780 >> >>Terry's solution is much faster (at least on my test set) and, as an >>additional benefit, is the easiest to understand. > > Yep, I believe clarity is essential in the library (and that is why my > patch was obviously not accepted :) Actually IIRC (it's been a long > since) that code never compares more than once prefixes that have been > found equal and does not create slices (used buffer() and then switched > to startswith() for future compatibility), that is why it's a little > complicated. The main loop runs math.ceil(math.log(N,2)) times, where N > is min([len(x) for x in argument_list]). > > Anyway, perhaps Terry or you should update the SF patch so that > os.path.commonprefix becomes faster... the point is to benefit the whole > Python community, right? :) In principle, yes :-) I'm not too sure if commonprefix is used that often and in a way that would really be worth the effort to patch the existing code. (I guess, if there had been a real need, it would have been done already a long time ago). Another thing is that the speed improvement would be largely due to using C implemented functions instead of pure Python code (o.k., the lines are blury here). In order to understand what's going on, one needs to know what kind of functions are C implemented and why, in that particular case, it is a good idea, to use them. From daniel.dittmar at sap.com Tue Dec 30 08:56:43 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 30 Dec 2003 14:56:43 +0100 Subject: C++ and Python: how can I make it stop? References: Message-ID: Heikki Salo wrote: > I have decided to embedd Python into my C++ application and I have one > question about it. Everything works perfectly, but I haven?t figured > any way to stop the interpreter when it is executing (using > PyRun_SimpleFile) a python script. I expose a callback-function (so > scripts can call it) in my programs API which should stop the > processing, but as I said, I have no idea how to do that. I tried to > use sys.exit, but it kills the whole application. Raise an exception in your callback (see http://www.python.org/doc/current/api/exceptionHandling.html on how to do this in C++). Daniel From paul_rudin at scientia.com Wed Dec 10 04:37:42 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 10 Dec 2003 09:37:42 +0000 Subject: mod_python and caching DB objects References: Message-ID: >>>>> "fowlertrainer" == fowlertrainer writes: > Hello ! I want to create a site with mod_py. I am beginner. > Can I create an persistent database connection/objects in mod_py There is an entry in the mod_python FAQ addressing this question IIRC. From jjl at pobox.com Wed Dec 31 09:51:01 2003 From: jjl at pobox.com (John J. Lee) Date: 31 Dec 2003 14:51:01 +0000 Subject: canonical file access pattern? References: Message-ID: <874qvhkpm2.fsf@pobox.com> Hans-Joachim Widmaier writes: > Am Tue, 30 Dec 2003 12:00:52 +0100 schrieb Rene Pijlman: [...] > > Then this would need to be the algorithm: > > > > try: > > f = file("spam.txt", "w") > > except IOError, e: > > # Handle open() error > > pass > > else: > > try: > > try: > > # read/write to the file > > pass > > except IOError, e: > > # Handle read/write errors > > pass > > finally: > > try: > > f.close() > > except IOError, e: > > # Handle close error > > pass > > While my first thought was: Why is the finally needed here? The close() > might just as well be the end of the else-suit. But it slowly dawns on me: > If there is another exception than IOError in the read/write suite, > closing of the file wouldn't take place. > > > Not very pretty, but I can't think of a simplification that does not > > violate one of the assumptions. > > Yes, I would second that. Alas, this means that the wonderful pattern > > for line in file(filename, "r"): > process_line(line) > > is unusable for any "production quality" program. ;-( [...] If that were true, why did exceptions get invented? If you don't need to do something different in all those except: clauses, then don't put them in. As you know, the nice thing about exceptions is that you're allowed to handle them in sensible places, so typical usage is like this: def frob(filename): f = file(filename, "w") try: # read/write to the file finally: f.close() def blah(): try: frob(filename) except IOError, e: # try something else, or print e.strerror or, even better: def blah(): frob(filename) Shock, horror, where's the except IOError:, you ask?! It's in the calling function, of course. Also, if you want to catch both OSError and IOError, note that EnvironmentError is their common base class. John From dman at dman13.dyndns.org Tue Dec 9 13:24:07 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Tue, 09 Dec 2003 18:24:07 GMT Subject: Delete common entries between two dictionaries References: <4Guwb.7197$9O5.6638@fed1read06> <97ba91-169.ln1@dman13.dyndns.org> Message-ID: On Mon, 24 Nov 2003 14:20:30 -0800, David Eppstein wrote: > In article <97ba91-169.ln1 at dman13.dyndns.org>, > Derrick 'dman' Hudson wrote: > >> This would be great for sets, if a set adequately models your data. >> (with two sets, this would simply be (s1-(s1&s2))) > > You mean s1 - s2, no need for that extra &. Ah, of course -- if an item is in s2 but not in s1, the subtraction is a no-op. -- Love is not affectionate feeling, but a steady wish for the loved person's ultimate good as far as it can be obtained. --C.S. Lewis www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From john.abel at pa.press.net Tue Dec 16 06:37:10 2003 From: john.abel at pa.press.net (John Abel) Date: Tue, 16 Dec 2003 11:37:10 +0000 Subject: downloading long files In-Reply-To: <95aa1afa.0312160310.7e629fd6@posting.google.com> References: <95aa1afa.0312152351.7b6143be@posting.google.com> <95aa1afa.0312160310.7e629fd6@posting.google.com> Message-ID: <3FDEEE66.2050509@pa.press.net> If I remember rightly, there is python code for a resumable HTTP downloader in the Python Cookbook. I don't think it would take much work for it to handle FTP, too. Regards John Michele Simionato wrote: >garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) wrote in message news:... > > >>Michele Simionato wrote: >> >> >>>I have a connection which is not 100% rock solid, so if I try >>>to download a large file (i.e. a Linux ISO image) chances are >>>that the connection will break. Is there a way to check periodically >>>if the connection is open, reopen it if needed, and continue the >>>download without restarting from the beginning? >>> >>> >>yes, use wget http://www.gnu.org/directory/wget.html >>or are you looking for a pure python solution? >> >> > >A pure Python solution would be preferable, indeed. > > Michele > > From python at rcn.com Thu Dec 18 11:10:16 2003 From: python at rcn.com (Raymond Hettinger) Date: 18 Dec 2003 08:10:16 -0800 Subject: filter and map / deprecated? References: Message-ID: <5d83790c.0312180810.56077fcc@posting.google.com> > I read in PEP 279 the following comment by GvR: > > "filter and map should die and be subsumed into list > comprehensions, not grow more variants." > > Actually, I am using 'filter' and 'map' a lot in my scripts > (not really because they are necessary, but more because I > like them). Should I avoid the usage of 'filter' and 'map' > in the future? The above comment by GvR makes me a little > bit afraid that they will become deprecated one day and that > I will have to change many of my scripts then. Until Py3.0, we are shying away from deprecating things. apply(), buffer(), coerce(), and intern() were moved to a separate page in the docs for obsolete or non-essential stuff but there are no deprecations. The itertools variants of filter and map are proving to be popular and will likely be around for a long time. I suggest using them instead of the builtins since they are memory friendly and scale-up nicely. Raymond Hettinger From Mike at DeleteThis.Geary.com Wed Dec 24 22:05:38 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 24 Dec 2003 19:05:38 -0800 Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: > Thanks MIke. > I forgot to add another note, by the way, that I received an > email from ActiveState correcting me on this. > I will add your positive mention to my ultimate decision. Glad to help. But my real advice is to do like I did: Download all the IDEs that you are considering and try them out yourself. You'll quickly know which one suits your needs and taste the best. For me, it was a no-brainer: I spend most of my work day in Microsoft Visual Studio, and unlike the others I tried, Komodo is designed to be familiar and comfortable for a Visual Studio user. But what matters to me may not be important to someone else. So try them all and have fun exploring! -Mike From peter at engcorp.com Wed Dec 10 08:57:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Dec 2003 08:57:18 -0500 Subject: Python & Expect References: Message-ID: <3FD7263E.110F9CC4@engcorp.com> Jeff Wagner wrote: > > Is there an Expect-like module for Python that is cross platform and, for the most part, does what > Expect does? A number of years ago, I wrote some Tcl scripts using Expect for automation. I am > trying to convince my good friend who I worked with at the time to try Python. He said, "what about > Expect?" > > I have heard of a Pexpect but was told that it didn't run on win32 and he needs win32 and Linux > support both. Hmmm... let's see what Google brings up... (typing) http://www.google.com/search?q=python+expect Wow! Look at that! Pexpect is the first hit. Let's try accessing that page and see what it says. (click) Ah, there's a "Requirements" link: (click) -------------------------------------------- Python Pexpect was written and tested with Python 2.1. It should work on earlier versions that have the pty module. ... pty module Any POSIX system (UNIX) with a working pty module should be able to run Pexpect. The pty module is part of the Standard Python Library, so if you are running on a POSIX system you should have it. The pty module does not run as well on all platforms. I have taken effort to try to smooth the wrinkles out the different platforms. To learn more about the wrinkles see Bugs and Testing. Pexpect does not currently work on the standard Windows Python(see the pty requirement); however, it seems to work fine using Cygwin. ... -------------------------------------------- Okay, Jeff, consider your wrist slapped for not even trying... :-) -Peter From andrew-pythonlist at puzzling.org Fri Dec 19 01:42:55 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 19 Dec 2003 17:42:55 +1100 Subject: Default attribute in base class precludes delegation In-Reply-To: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> References: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> Message-ID: <20031219064255.GC7524@frobozz> On Fri, Dec 19, 2003 at 12:44:28AM -0300, Gabriel Genellina wrote: > Hi > > In the following code sample, I have: > - a Worker class, which could have a lot of methods and attributes. In > particular, it has a 'bar' attribute. This class can be modified as needed. > - a Base class (old-style) which defines a default class attribute 'bar' > too. I can't modify the source code of this class. Note that Workes does > not inherit from Base. > - a Derived class which must inherit from Base and is a wrapper around > Worker: it contains a Worker instance and delegates almost anything to it. > This class can be modified as needed too. > > For most attributes, as they are not found in the Derived instance's dict, > __getattr__ is called and the attribute is retrieved from the Worker > instance. > But for the 'bar' attribute, it is found in the Base class and just the > default value is returned. __getattr__ is never called. Inherit Derived from object as well as Base, to make it new-style, then you could use either __getattribute__ or descriptors (e.g. property) to get the behaviour you want. -Andrew. From reply.in.the.newsgroup at my.address.is.invalid Thu Dec 25 12:08:24 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 25 Dec 2003 18:08:24 +0100 Subject: How does "delegation" work as per the FAQ? Message-ID: Section 6.5 "What is delegation?" of the FAQ says: "Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase: class UpperOut: def __init__(self, outfile): self.__outfile = outfile def write(self, s): self.__outfile.write(s.upper()) def __getattr__(self, name): return getattr(self.__outfile, name) [...] All other methods are delegated to the underlying self.__outfile object. The delegation is accomplished via the __getattr__ method; consult the language reference for more information about controlling attribute access." http://www.python.org/doc/faq/programming.html#what-is-delegation I don't understand how __getattr__ accomplishes delegation of other methods. I'd expect __getattr__ to be called for attribute access, not for method calls. And how would the arguments of a method call be passed on? The link to the language reference doesn't help much. It says about __getattr__: "Called when an attribute lookup has not found the attribute in the usual places". There is no mention of method calls. -- Ren? Pijlman From anthony at ekit-inc.com Mon Dec 8 19:15:02 2003 From: anthony at ekit-inc.com (Anthony Baxter) Date: Tue, 09 Dec 2003 11:15:02 +1100 Subject: Python 2.2.3 memory leaks? In-Reply-To: Message from genjox@yahoo.com (Robert) of "08 Dec 2003 16:04:57 -0800." Message-ID: <200312090015.hB90F3dt023580@maxim.off.ekorp.com> >>> Robert wrote > I'm having to use 2.2.3 to port to other platforms. I started porting > a few months ago, and only recently had time to finish it. I just > noticed there seems to be some memory leaks, and not only in some > static function variables they use. There's been a number of memory leaks fixed in 2.3. If you can, please try 2.3.3rc1 (announced a few days ago). In the absence of someone willing to take up the job of backporting these fixes to the 2.2 line, these fixes won't be going into 2.2, nor will there be a future release in the 2.2 line. I have no plans or interest in 2.2 - the changes between 2.2 and 2.3 are so slight (from a code point of view) that I'm skipping straight past the 2.2 series for my production systems. Anthony From __peter__ at web.de Fri Dec 19 06:01:53 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 12:01:53 +0100 Subject: Sorting coordinates array References: Message-ID: Maarten van Reeuwijk wrote: > I'm a newbie to Python, so sorry for this maybe trivial question. I have a > numpy array with coordinates, which I want to sort, for example first on > z-coordinate, then x and lastly y-coordinate. So an array like: > > [[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]] > > should look after sorting like > > [[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]] > > I tried the sort command, but that command mangles my coordinate pairs. > Also converting the array to a list doesn't seem to improve the results. > How should I tackle this problem? >>> import Numeric >>> a = Numeric.array([[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]]) >>> lst = a.tolist() >>> lst.sort(lambda x, y: cmp(x[::-1], y[::-1])) >>> lst [[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]] >>> You can pass an arbitrary comparison function to list.sort(), I just compare reversed copies of the inner lists. This is a highly unoptimized version, but at least seems to do the job. Peter From newsgroups at jhrothjr.com Mon Dec 22 16:18:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Dec 2003 16:18:10 -0500 Subject: How do I test if an object is a sequence? References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: "Aahz" wrote in message news:bs79nr$k7j$1 at panix1.panix.com... > In article , > John Roth wrote: > >"Max M" wrote in message > >news:3fe6fbb1$0$69983$edfadb0f at dread12.news.tele.dk... > >> > >> Is there a common idiom for testing if an object is a sequence? > >> > >> Both list, tuple and non-standard objects etc. I have Googled, but > >> didn't find a usable answer. > > > >The best way I know of is to check for the existance of either __iter__ > >or __getitem__. This gets you roughly the same results as either the > >for statement or the iter() built-in function. > > Not quite. Try using ``for`` on a dict in Python 2.1 or earlier. Well, yes, but dicts aren't the only problem. The notion of 'sequence' is sufficiently ill-defined that you almost need to know what the OP wants to do with it to give a usable answer. For example, do you want to accept infinite sequences? Some generators will do that to you, on the other hand, testing for __len__ isn't going to let you accept files, which are neither infinite nor do they have a usable __len__ or __getitem__. And, as you point out, everything that has a __getitem__ and a __len__ won't accept numeric subscripts. Like dicts. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Weinberg's Second Law: If builders built buildings the way programmers wrote > programs, then the first woodpecker that came along would destroy civilization. From g2h5dqi002 at sneakemail.com Thu Dec 18 00:25:27 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 18 Dec 2003 18:25:27 +1300 Subject: Default parameters In-Reply-To: References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: Stian S?iland wrote: > When is this issue going to be resolved? Enough newbie-pythoners have > made this mistake now. Changes are rarely if ever made to Python for the sole reason of reducing newbie mistakes. There needs to be a payoff for long-term use of the language as well. In this case, evaluating the default args at call time would have a negative payoff, since it would slow down every call to the function in cases where the default value doesn't need to be evaluated more than once. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ville.vainio at spamster_tut_remove.fi Mon Dec 29 08:35:56 2003 From: ville.vainio at spamster_tut_remove.fi (Ville Vainio) Date: 29 Dec 2003 15:35:56 +0200 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: Thomas Dorn writes: > In your situation (i.e. trying to build a Windows application which > is "standard in every conceivable way"), I would not use Python. Doesn't using the mfc library (like PythonWin does) enable creating applications that are "standard in every conceivable way"? -- Ville Vainio http://www.students.tut.fi/~vainio24 From yan at NsOeSiPnAeMr.com Sun Dec 7 06:49:47 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sun, 07 Dec 2003 06:49:47 -0500 Subject: how to determine if files are on same or different file systems In-Reply-To: References: Message-ID: Peter Otten wrote: > No need to determine it beforehand, just try (untested): > > def movefile(src, dst): > try: > os.rename(src, dst) > except OSError: > shutil.copy2(src, dst) > os.remove(src) > > > Of course, if you are using Python 2.3 you should use shutil.move() as > pointed out by Serge Orlov; the above was mostly posted to illustrate the > popular concept "It's easier to ask forgiveness than permission", i. e. > with Python's powerful exception handling mechanism you need not fear the > failure of a particular code snippet, as long as you provide the > appropriate error handling. Peter: I am copying 600mb - 1.2gb files over slow wireless to an NFS mount - not exactly the model of reliability. It takes 40 minutes to an hour to copy one of these. I am paranoid of failures - I don't want to lose movies. So, I don't want to rely on innate error handling, because the failure could come from wireless failure, and the copy could fail as well. That's why I'm looking for a way to tell if a particular partition is network mounted. The basic idea is that movies get moved on the same partition, but copied (and not deleted) when moving between network mounted partitions and local partitions. Deletes will be subject to manual review until I get a comfort factor. > > Random remarks: > - You might take a look at os.path.join() > - Ok, this is paranoia, but I would ensure that ".avi" is only at the end of > the string ".avi$" ? I still haven't figured out Python's string handling really well. Or use the length of the string and count backwards? I admit, I got lazy on this one. > - Use methods of the str object rather than functions in the string module, > e. g. "abc".replace("a", "d") rather than string.replace("abc", "a", "d") OK, I'll try that. -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From cartermark46 at ukmail.com Thu Dec 25 06:17:10 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 25 Dec 2003 03:17:10 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: > - FWIW I'm a proponent of MIT / BSD style "do whatever you want with it" > open source licenses, not GPL. I believe if you're going to give something Microsoft have always complained that GPL-ish licences "infect" everything they touch (yes, yes, I'm perfectly aware of the irony). I was thinking that, if more stuff was released into the Public Domain - then that would be a good thing. It might actually be a benefit for Microsoft to rip off good quality PD work. If they got it for free, then they might be less inclined to roll there own "feature rich" solutions, and instead opt for a more conventional approach. There might be a chance - and of course I emphasis the word "might" - that they would contribute, in some small way, to ongoing PD efforts. After all, if they though that they could get someone to effectively work on their product for free, then they might be a bit more forthcoming. Just an opinion. From oren at hishome.net Wed Dec 17 21:13:56 2003 From: oren at hishome.net (Oren Tirosh) Date: Wed, 17 Dec 2003 21:13:56 -0500 Subject: SWT and Python (was: Re: What GUI toolkit looks the best?) In-Reply-To: <7k0whmxp.fsf@python.net> References: <20031211190954.GA54939@hishome.net> <05f701c3c026$5eb9c8f0$7401a8c0@voidmk9> <7k0whmxp.fsf@python.net> Message-ID: <20031218021356.GB42162@hishome.net> On Tue, Dec 16, 2003 at 03:11:46PM +0100, Thomas Heller wrote: > Markus Wankus writes: > > I believe that's what he means...and I have been wondering about this > > for awhile. SWT is very wxWindows-ish in it's parent-child > > relationships - and I think it just looks and feels really cool. > > > > You can easily do it all in Python/Jython - provided you use the .dll > > and .jar file. A pure Python wrapping of the .dll (i.e. replacing the > > .jar file) would be seriously cool. > > Hm, it seems the .dll (which is 270 kB) is a thin wrapper over the > windows api, and the .jar file, which is (although probably compressed) > has 1MB, containing windows specific code. Yes, that's the SWT architecture. > Sounds more like a total rewrite of SWT in python than a simple wrapper > to me. Most of this work was done manually in a few weeks for the C# port. But there is no need to do it manually. I think that mechanical translation of Java to clean and even idiomatic Python would not be too hard. I've looked at the code and SWT uses a pretty small subset of the Java libraries (some basic I/O and containers) and a small number of language constructs over and over again. Oren From piir at earthlink.net Mon Dec 8 20:00:23 2003 From: piir at earthlink.net (Todd Gardner) Date: 8 Dec 2003 17:00:23 -0800 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> <3FD4C763.488579C1@engcorp.com> Message-ID: <9b849915.0312081700.7e7b1d21@posting.google.com> Peter Hansen wrote in message news:<3FD4C763.488579C1 at engcorp.com>... > Todd Gardner wrote: > > > > Peter Hansen wrote in message news:<3FD3E423.B53D23DE at engcorp.com>... > > > Todd Gardner wrote: > > > > > > > > I would like to graph two columns of x,y numbers? I would greatly > > > > appreciate any pointers or suggestions. > > > > > > Yes, include more detail about what you want to do. Specifically, > > > what platform, do you care if it's wxPython, or Tkinter, or something > > > else, etc. There are about a zillion possible answers to your > > > question as it stands, and "python graphing" or something on Google > > > would likely get you a lot of mileage right now. Maybe after you > > > do a little research there you can come back with a more detailed > > > question? > > > > There are LOTS of plotting choices on google. I guess I would like to > > narrow them down by tapping into some expertise. > > > > I would like to do 2D and possibly 3D plotting with python. I am > > tending toward wxpython because of it's ease of use. > > You still haven't really given any information about your goals. Is > this program just for visualization of static data? Yes. > Anything dynamic? At this point no. I would like to say something like plot(x,y) for 25,000 points. > Who's the audience? Engineers and scientists. > Do you need to do printing of the same output? Yes, I would like to print, save and possibly load the graph. > How precisely does the printed version need to match the screen? WYSIWYG > Is this part of a program that you will be giving to others, or > is it just for personal use? I would like to compile this program and bundle it with my application and sell it on a single user basis. It is to be bundled with a larger electrical engineering consulting job. > Do you have any limitations with respect > to the platform used? Linux only? Windows only? Both? Neither? Mandrake Linux and Windows 2000/XP. > And you can probably add another dozen questions to the mix. > If you have any more questions feel free to ask. Thanks for making me get the specs down a bit more precise. Todd > Yes, I understand that you hope someone can say something like > "Use X or Y, but skip Z because it sucks", but you really can't > expect to get a to-the-point answer if nobody knows what you want > this for. > > -Peter From max at alcyone.com Thu Dec 25 06:12:15 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 25 Dec 2003 03:12:15 -0800 Subject: 2.3 list reverse() bug? References: Message-ID: <3FEAC60F.1130F5D6@alcyone.com> Mark Carter wrote: > I did this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > > >>> d1 = [1,2] > >>> d2 = d1 > >>> d2.reverse() > >>> print d1 #note: d1, not d2 > [2, 1] > >>> > > Surely that can't be right: d1 should still be [1,2]. If it is > "right", then I expect that many people are in for a suprise. It's been that way since the very early versions of Python. The .reverse method modifies the list object in place, and "assignment" merely creates another name for the same object. In fact, .reverse's return value of None is intended to signal exactly this to you. After all, does this surprise you: >>> a = [1, 2] >>> b = a >>> b.append(3) >>> a [1, 2, 3] >>> b [1, 2, 3] If it does, then you need to read the Python tutorial on how Python deals with mutable objects. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Nothing spoils a confession like repentence. -- Anatole France From m.dufour at student.tudelft.nl Tue Dec 16 10:29:50 2003 From: m.dufour at student.tudelft.nl (Mark Dufour) Date: Tue, 16 Dec 2003 16:29:50 +0100 Subject: Converting integer to binary representation Message-ID: <200312161629.50069.m.dufour@student.tudelft.nl> On Tuesday 16 December 2003 15:48, Fredrik Lundh wrote: > "Mark Dufour" wrote: > > I need to convert an integer into some binary representation. I found the > > following code in the online cookbook (adapted to return a list): > > > > binary = lambda n: n>0 and [n&1]+binary(n>>1) or [] > > > > This is sure nice, but I'm wondering why something like this doesn't seem > > to be in the standard library, for example by formatting with '%b' % > > number. I can't think of a any reason for not doing it this way, as > > working with binary representations is quite common in programming, > > really? what kind of programs are you writing? I want to loop over the binary representation of numbers, for use in some algorithm dealing with prime numbers. Of course, there are multiple ways of doing this, but I like the clean: 'for power, bit in enumerate(binary(number))', possible with the above code. > (in my experience, binary numbers only appear in programming text > books. humans tend to use decimal numbers, and programmers use > octal or hexadecimal numbers when they need to "access the bits"). I've seen several attempts on the web for implementing this functionality in Python, so I guess I'm not the only one needing or wanting it.. ;-) Some programmers actually do work a lot with bits and prefer binary representation sometimes, so why not add a simple provision to the language? Like, int() takes a base argument, why not have str() take one as well?? If only just for consistency :-) Mark Dufour. -- "The employment agency has selected an immature and unproven software package and its functionality is at the best close to Office 97," said Microsoft representatives. From luc.saffre at gmx.net Fri Dec 12 03:38:27 2003 From: luc.saffre at gmx.net (Luc Saffre) Date: Fri, 12 Dec 2003 10:38:27 +0200 Subject: "Bad file descriptor" after py2exe or Installer In-Reply-To: References: <3FD8B25A.7080103@gmx.net> Message-ID: <3FD97E83.2000703@gmx.net> On 11/12/2003 23:11, Thomas Heller wrote: > It seems I cannot reproduce this with py2exe 0.5. > Can you? Yes: I use py2exe 0.5.0a5. Here is in more detailed, how I reproduce the problem: I used the following installers: Python-2.3.3c1.exe PIL-1.1.4.win32-py2.3.exe py2exe-0.5.0a5.win32-py2.3.exe I installed these three to a clean installation (except for my windows registry where I don't know how to verify cleaness) I place the test.py as described into a separate directory, together with a file setup.py: from distutils.core import setup import py2exe setup( console=["test.py"] ) and then I type "setup py2exe" at the command line. Here is the output of that command: running py2exe *** searching for required modules *** *** parsing results *** creating python loader for extension '_sre' creating python loader for extension 'PIL._imaging' creating python loader for extension '_tkinter' creating python loader for extension 'PIL._imagingtk' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\PaletteFile.py to PIL\PaletteFile.pyc skipping byte-compilation of C:\PYTHON23\lib\lib-tk\FixTk.py to FixTk.pyc skipping byte-compilation of C:\PYTHON23\lib\copy_reg.py to copy_reg.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_compile.py to sre_compile.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImageChops.py to PIL\ImageChops.pyc skipping byte-compilation of C:\PYTHON23\lib\StringIO.py to StringIO.pyc byte-compiling T:\data\luc\release\lino\tests\py2exe\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc skipping byte-compilation of C:\PYTHON23\lib\macpath.py to macpath.pyc skipping byte-compilation of C:\PYTHON23\lib\popen2.py to popen2.pyc skipping byte-compilation of C:\PYTHON23\lib\atexit.py to atexit.pyc skipping byte-compilation of C:\PYTHON23\lib\dummy_thread.py to dummy_thread.pyc byte-compiling T:\data\luc\release\lino\tests\py2exe\build\bdist.win32\winexe\temp\PIL._imaging.py to PIL\_imaging.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImageFilter.py to PIL\ImageFilter.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\GimpGradientFile.py to PIL\GimpGradientFile.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\__init__.py to PIL\__init__.pyc skipping byte-compilation of C:\PYTHON23\lib\posixpath.py to posixpath.pyc byte-compiling T:\data\luc\release\lino\tests\py2exe\build\bdist.win32\winexe\temp\_tkinter.py to _tkinter.pyc skipping byte-compilation of C:\PYTHON23\lib\linecache.py to linecache.pyc skipping byte-compilation of C:\PYTHON23\lib\tempfile.py to tempfile.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\GimpPaletteFile.py to PIL\GimpPaletteFile.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_constants.py to sre_constants.pyc skipping byte-compilation of C:\PYTHON23\lib\re.py to re.pyc skipping byte-compilation of C:\PYTHON23\lib\ntpath.py to ntpath.pyc skipping byte-compilation of C:\PYTHON23\lib\stat.py to stat.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImagePalette.py to PIL\ImagePalette.pyc skipping byte-compilation of C:\PYTHON23\lib\lib-tk\Tkinter.py to Tkinter.pyc skipping byte-compilation of C:\PYTHON23\lib\string.py to string.pyc skipping byte-compilation of C:\PYTHON23\lib\warnings.py to warnings.pyc skipping byte-compilation of C:\PYTHON23\lib\UserDict.py to UserDict.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\Image.py to PIL\Image.pyc skipping byte-compilation of C:\PYTHON23\lib\repr.py to repr.pyc byte-compiling T:\data\luc\release\lino\tests\py2exe\build\bdist.win32\winexe\temp\PIL._imagingtk.py to PIL\_imagingtk.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImageTk.py to PIL\ImageTk.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImageTransform.py to PIL\ImageTransform.pyc skipping byte-compilation of C:\PYTHON23\lib\copy.py to copy.pyc skipping byte-compilation of C:\PYTHON23\lib\site-packages\PIL\ImageColor.py to PIL\ImageColor.pyc skipping byte-compilation of C:\PYTHON23\lib\types.py to types.pyc skipping byte-compilation of C:\PYTHON23\lib\sre.py to sre.pyc skipping byte-compilation of C:\PYTHON23\lib\traceback.py to traceback.pyc skipping byte-compilation of C:\PYTHON23\lib\lib-tk\Tkconstants.py to Tkconstants.pyc skipping byte-compilation of C:\PYTHON23\lib\random.py to random.pyc skipping byte-compilation of C:\PYTHON23\lib\os2emxpath.py to os2emxpath.pyc skipping byte-compilation of C:\PYTHON23\lib\colorsys.py to colorsys.pyc skipping byte-compilation of C:\PYTHON23\lib\sre_parse.py to sre_parse.pyc skipping byte-compilation of C:\PYTHON23\lib\os.py to os.pyc *** copy extensions *** copying C:\PYTHON23\DLLs\_sre.pyd -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\PYTHON23\lib\site-packages\PIL\_imaging.pyd -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\PYTHON23\DLLs\_tkinter.pyd -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\PYTHON23\lib\site-packages\PIL\_imagingtk.pyd -> T:\data\luc\release\lino\tests\py2exe\dist *** copy dlls *** copying u:\CYGWIN\BIN\cygwin1.dll -> T:\data\luc\release\lino\tests\py2exe\dist copying u:\CYGWIN\BIN\tk84.dll -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\WINNT\System32\python23.dll -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\PYTHON23\DLLs\tcl84.dll -> T:\data\luc\release\lino\tests\py2exe\dist copying u:\CYGWIN\BIN\tcl84.dll -> T:\data\luc\release\lino\tests\py2exe\dist copying C:\PYTHON23\lib\site-packages\py2exe\run.exe -> T:\data\luc\release\lino\tests\py2exe\dist\test.exe copying C:\PYTHON23\lib\site-packages\py2exe\run_w.exe -> T:\data\luc\release\lino\tests\py2exe\dist\tkhello.exe Afterwards the dist\test.exe shows the described behavious. I hope that you (or somebody else) can now reproduce the problem. TIA, Luc From skip at pobox.com Thu Dec 18 16:08:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 15:08:13 -0600 Subject: Broken python-model.el In-Reply-To: <274A369893F5FB4099345F006439D987013876DB@bella.corp.resmed.org> References: <274A369893F5FB4099345F006439D987013876DB@bella.corp.resmed.org> Message-ID: <16354.5949.20593.712706@montanaro.dyndns.org> Peter> Well, I downloaded the python-mode.el just this morning as I was Peter> reading the news group. So it was about 1 - 1.5 hours ago (it's Peter> now 7:50am in Sydney, so I would have tried it probably about Peter> 6:30am) now that I downloaded python-mode.el (4.40) and had that Peter> exact problem. Peter> Do you mean you have changed the code since then? The revision Peter> number in the file doesn't seem to have changed (looking at Peter> sourceforge again now). So I don't think it is fixed :-) Ack! Fixed locally. Didn't check it in... :-( Try 4.41 (just checked in). Skip From http Fri Dec 5 17:59:24 2003 From: http (Paul Rubin) Date: 05 Dec 2003 14:59:24 -0800 Subject: min and max id numbers References: Message-ID: <7xsmjyx44z.fsf@ruckus.brouhaha.com> "r.e.s." writes: > On a given machine, is it possible to create objects LO and HI, > such that for all objects x, id(LO) <= id(x) <= id(HI) ? It may be possible under narrow circumstances but you really can't ever rely on it. You're better off writing a C extension that tells you the endpoints of heap memory. From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 12:27:10 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 18:27:10 +0100 Subject: inline References: Message-ID: km: >Does python support inline assembly ? (like C ) Thusly: http://www.python.org/doc/current/ext/ext.html -- Ren? Pijlman From rainerd at eldwood.com Sat Dec 20 01:03:06 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 20 Dec 2003 06:03:06 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Carl Banks wrote: > Well, personally, I don't see much use for non-constant default > arguments, as we have them now, wheras they would be useful if you > could get a fresh copy. I disagree completely. If a function modifies one of its arguments, this is a fundamental property of that function. If using a default value for that argument causes the function to swallow the changes it performs, the function no longer has consistent behavior. On the other hand, the following function has consistent, if silly, behavior: default_list = [] def append_5_to_a_list(which_list = default_list): which_list.append(5) -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From kraus at hagen-partner.de Fri Dec 5 10:09:20 2003 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 05 Dec 2003 16:09:20 +0100 Subject: How to tell the difference between string and list In-Reply-To: References: Message-ID: Heyho! Jan Kokoska wrote: [...] > > But unfortunately in Zope PythonScripts, where I need to use this, one > is not supposed to use underscore-prefixed methods as I just found out. In Zope you can use same_type(): same_type(a, '') same_type(a, []) (See Zope Book -> Advanced Zope Scripting -> Built-in Functions) > I figure this is a question general enough to post here (and not on the > Zope list), any clues? > > TIA > > Jan Kokoska > HTH, Wolfram From bokr at oz.net Sun Dec 7 22:21:46 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Dec 2003 03:21:46 GMT Subject: Efficient MD5 (or similar) hashes References: Message-ID: On Sun, 07 Dec 2003 19:49:58 -0500, Kamus of Kadizhar wrote: >ANother newbie question: > >I have large files I'm dealing with. Some 600MB -1.2 GB in size, over a >slow network. Transfer of one of these files can take 40 minutes or an >hour. > >I want to check the integrity of the files after transfer. I can check >the obvious - date, file size - quickly, but what if I want an MD5 hash? > > From reading the python docs, md5 reads the entire file as a string. I don't know what docs you're reading, but if your read the docs on the md5 module, you'll see you don't have to do that. also you could interactively type help('md5') or import md5 followed by help(md5) >That's not practical on a 1 GB file that's network mounted. Well, whatever calculates the md5 will have to read all the bytes from the source you want to check. If you have downloaded a file to another machine, then the fastest will be to run the md5 calculation there, but if you have a gigabit lan connection and things aren't busy, IWT it wouldn't make much difference if you read it that way. If you have a c/c++ excutable utility that will calculate md5, it will probably be fastest to run that on the file. You can run it from python via popen, if that's the context you want to control it from. I think there's ways to RPC to accomplish the same remotely, but I haven't played with that. > >The only thing I can think of is to set up an inetd daemon on the server >that will spit out the md5 hash if given the file path/name. > >Any other ideas? Describe your setup in a little more detail. Someone has probably done it before. Regards, Bengt Richter From hans at zephyrfalcon.org Fri Dec 12 22:08:59 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 12 Dec 2003 22:08:59 -0500 Subject: porting python script from linux to windows In-Reply-To: References: Message-ID: <3FDA82CB.90704@zephyrfalcon.org> hokieghal99 wrote: > What are the specific steps that one should take to make a python script > that works on a Linux x86 machine also work on a Windows x86 machine? Run it, and see what happens. ;-) Seriously, in theory there is no reason why it shouldn't work right out of the box, unless you have platform-specific code. So I'd say, just run it and see if you encounter any problems. > I am using os, re and string in the script. How do paths differ between > the two OSes? I am use to a unix-like path /blah/blah/blah. Would I need > to change this to x:\blah\blah\blah where x = drive letter? Maybe. Paths with slashes can be used on Windows as well. > What about > creating fs objects? file works the same on both? os.walk works the same? Files should work the same, except that on Windows opening files in 'binary mode' is different from 'text mode'. os.walk should work just fine. HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From peter at engcorp.com Fri Dec 12 14:05:04 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Dec 2003 14:05:04 -0500 Subject: Very slow opening of client connections to localhost with httplib References: <8ce71920.0312120951.4c49b061@posting.google.com> Message-ID: <3FDA1160.2450EE88@engcorp.com> Martin Fuzzey wrote: > > To test this I did : > > import socket > socket.getaddrinfo("localhost", 10000, 0, socket.SOCK_STREAM) > > and sure enough it blocked for several seconds before finally > returning 127.0.0.1 > > However > socket.gethostbyname("localhost") > returns immediately Any chance your /etc/host.conf, /etc/resolv.conf or /etc/hosts files are buggering this up somehow? (It doesn't explain gethostbyname() returning immediately, unless perhaps that function internally handles localhost "magically".) Just a thought. In my experience, delays like this generally result from host.conf having "order bind,hosts" instead of the other way around, plus perhaps an inappropriate "options timeout:xxx" value in resolv.conf. I haven't ever seen an issue with localhost, however, but I've never been on a machine that didn't have the right entry in /etc/hosts. -Peter From simonb at webone.com.au Mon Dec 22 21:33:42 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 23 Dec 2003 13:33:42 +1100 Subject: linux wine py2exe ?? References: Message-ID: On Sun, 21 Dec 2003 21:45:03 +0100, duikboot wrote: > Hi > > > A friend of mine runs windows, and asked me to write a little script. He > has no Python installed though, and istalling it, is no option. So I > really wanted to make an executable for windows. So I Installed wine: > Yeah! I think this is a great idea. Please let us know how you go. Simon Burton. From deets_noospaam at web.de Mon Dec 15 14:00:58 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 15 Dec 2003 20:00:58 +0100 Subject: Dynamically create classes for spark-parser-framework Message-ID: Hi, I've got to create some spark-based parsers during runtime. For people not familiar with spark, a parser looks like this: class MixFixParser(spark.GenericParser): def __init__(self, start='p_start'): spark.GenericParser.__init__(self, start) def p_rules(_, args): """ p_start ::= p_op p_start p_start ::= p_op ::= p_start lbracket p_start rbracket """ return args The framework looks for methods beginning with p_ and inspects its docstring for grammar rules. I hope that the body of my p_rules will be uniform, so until now I'd like to have one paser baseclass like MixFixParser above, and then modify the docstring accordingly - only for one specified instance! My first attempts failed due to AttributeError: 'instancemethod' object attribute '__doc__' is read-only Of course I could create one big string, with placeholders for class-name, doc-string contents and maybe even methodbody and evaluate it, but somehow this strikes me as unelegant - first of all, I lose emacs indention support for the code I write, and secondly I'd like the idea of manipulating only as few as possible - I don't _need_ distinct classes, only instances with differing parser-rules. I'll also have to check if spark allows for second-time or delayed calling of __init__, so that my altered rules get recognized - however, I think that could be done, come hell or highwater. Thanks for any suggestions, Diez From buzzard at urubu.freeserve.co.uk Fri Dec 5 19:06:16 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 6 Dec 2003 00:06:16 -0000 Subject: Newbie question: Any way to improve this code? References: Message-ID: "Gustavo Campanelli" wrote in message news:bqqvnl$kbo$1 at taurus.webcorp.pl... > I'm begining to work in a program that cicles through a list of phrases > (basically, a changing signature file). I started yesterday, and I only > have abput 8 full hours of real Python experience. > > So far I produced a code that succesfully reads an process the file, > separating the phrases. Is there any way to optimize this code, so that > I don't have to use the if for the first list member? > > Now for the data. > The file is firmas.txt, it contains the following three example phrases > > Frase 1 > Frase 2 > Frase 3 > > Note that this phrases are separated by newline characters. Upon reading > the full file (it won't be long) I get this: > > 'Frase 1\nFrase 2\nFrase 3\n' > > so, as you can see, the newlines are there. > > My code is this (I know I should close the file, but so far the runtime > is so small it doesn't really matter, that'll change) > > import string the string module doesn't seem to be used > f = open("firmas.txt",'r') # open the file > texto = f.read () no need for the space before the parentheses (see http://www.python.org/peps/pep-0008.html) > n = range (len (texto)) > frases = [0] why not initialise an empty list and append to it? > frase ="" > cant = 0 > for a in n: > if texto [a] != "\n": > frase = frase + (texto [a]) > else: > if cant == 0: > frases [0] = frase > else: > frases.append (1) > frases [cant] = frase then you can replace the above 5 lines with the following line and remove all references to 'cant', frases.append(frase) > cant +=1 > frase = "" > Or you could replace the whole thing with, try: f = open("firmas.txt",'r') texto = f.read() frases = texto.split('\n')[:-1] finally: f.close() Duncan From bowwnz at telstra.com Sat Dec 20 04:03:35 2003 From: bowwnz at telstra.com (Simon B) Date: Sat, 20 Dec 2003 09:03:35 GMT Subject: Is anyone using Python for .NET? In-Reply-To: References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: I know everyone has probably heard what I'm about to say a couple of hundred times, but because it's true, it should be stated. Brandon J. Van Every wrote: > "Richard Brodie" wrote in message > news:brpop1$1636 at newton.cc.rl.ac.uk... > >>That said, Brandon's claim was fairly contentious and likely to get >>someone to bite. It's a well worn debate though, and c.l.py probably >>isn't the best place to renew it. > > > It was a comment made in passing, and it takes quite a Trollhunter to make > it otherwise. My motives for posting were quite explicit, and I could care > less whether anyone wants to call .NET "a clone" or not. You can call it a > sheep or a dog or a rock for all I care. You can debate it until the cows > come home for all I care, I just want to know if people are using Python for > .NET. > > Again in passing: the concept of .NET was of course based on Java and a > number of other higher level languages. Every book on the subject I've read > says so (which by now is a small handful), and the goal (aside from > Microsoft dominating the world as usual) was to improve upon the basic > premise of a virtual machine. They have been successful and the truth > stands: the Unix world is cloning .NET because it is a superior technology > for a certain class of language interop problem. It remains to be seen > whether the *Windows Forms* part of .NET will be cloned successfully, or is > desired by the Unix crowd. I'm referring mainly to the IL. .NET is a platform, not a language. What you probably meant to say was: "C# is of course based on Java and a number of other higher level langauges". Completely true... Just as Java is based on Smalltalk and C++ along with a number of other higher level langauges. .NET the platform is, to programmers, a common set of types and libraries across multiple languages, whereas the JVM was sold along with the language Java, which in my opinion the only difference in marketing... Sun associated the JVM with Java so that to use the JVM they expected you to program in Java. Weird, because they could just have easily sold it as a platform on which other languages ran, and then we'd all be impressed about the vision of having multiple languages use common types... But it's happening anyway (http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html). There are far more languages running on the JVM than languages running on .NET. UNIX is cloning .NET not because it is superior technology (although it migth be, but that is arguable) but because it creates a situation where UNIX can run all of the software being churned out by .NET programmers. The barrier to moving platforms becomes Null and Void... Very JVM-esque eh? My opinion on why MS did take the .NET path is based on the premise that they are only really interested in Operating Systems, which isn't too bigger a stretch. They want to sell operating systems, and part of the reason corporations don't upgrade to the lastest version until they absolutely have to (and even then, they often don't!) is because they have invested big money in software that will require considerable testing and/or modification and/or risk if the underlying OS changes. .NET solves that problem for Microsoft. > Why bother to make another comment in passing? Because it's the truth, and > I find it annoying to be labeled as trying to get people to "bite" on some > advocacy debate when it's not my motive. If you want to debate the > relevance or morality of it all, go talk to the Mono people. Right now, I > don't care. I'm going to wait 4 years and then run .NET on Unix, picking up > a residual and unimportant market of Linux gamers for very little effort. > Sooner if things develop quicker. > From fnord at u.washington.edu Mon Dec 15 15:27:59 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 15 Dec 2003 12:27:59 -0800 Subject: ouput redirection..a newbie question References: <1008670585.21577.4.camel@gautam> Message-ID: You can also use os.popen() to capture the output of a shell command: import os p = os.popen('ls -al') output = p.read() # read output of command print output (a variation on this, os.popen3, can be used if you need to capture stdout and stderr separately...) Jp Calderone wrote in message news:... > On Tue, Dec 18, 2001 at 03:46:26PM +0530, Gautam Pagedar wrote: > > Hello, > > > > i am new to python and need a basic answer. Hope someone would help me > > solve this. > > > > I want to execute a command ls -l and sore its result in a file. > > > > >>import sys > > >>import os > > >>os.system("ls -al") > > > > executes the command how can i redirect the to a file like we do in > > shell script using a redirection operator. > > > > This works: > > os.system("ls -al > foo") > > Perhaps more usefully, though, the "commands" module allows you to get the > output of a program as a string: > > foo = commands.getoutput("ls -al") > > And it might be helpful to know that Python itself has functions for > listing files: > > fileList = os.listdir(".") > > As well as for getting information about them: > > fileMTimes = [os.path.getmtime(f) for f in os.listdir(".")] > filePermissions = [os.stat(f).st_mode for f in os.listdir(".")] > > For more information, see http://www.python.org/doc/lib/ > > Jp From olivasa at colorado.edu Mon Dec 15 18:04:55 2003 From: olivasa at colorado.edu (Alex Olivas) Date: Mon, 15 Dec 2003 16:04:55 -0700 Subject: compiling python-bibtex Message-ID: <3FDE3E17.8010005@colorado.edu> i'm not sure whether this is the correct list for this question, but i'm trying to build python-bibtex-1.1.93.1 with gcc 3.3.2 and am getting the following error messages... gcc -DNDEBUG -O2 -g -pipe -march=i386 -mcpu=i686 -D_GNU_SOURCE -fPIC -fPIC -DG_LOG_DOMAIN="BibTeX" -I$(top_builddir)//root/Installs/glib-2.2.3 -I$(top_builddir)//root/Installs/glib-2.2.3/. -I$(top_builddir)//root/Installs/glib-2.2.3/./glib -I/usr/include/python2.2 -c accents.c -o build/temp.linux-i686-2.2/accents.o In file included from accents.c:31: bibtex.h:35:18: glib.h: No such file or directory In file included from bibtex.h:36, from accents.c:31: logging.h:57: error: syntax error before '*' token In file included from accents.c:31: bibtex.h:76: error: syntax error before "GList" bibtex.h:76: warning: no semicolon at end of struct or union bibtex.h:76: warning: no semicolon at end of struct or union bibtex.h:77: warning: data definition has no type or storage class bibtex.h:78: error: syntax error before '*' token bibtex.h:78: warning: data definition has no type or storage class bibtex.h:79: error: syntax error before '*' token bibtex.h:79: warning: data definition has no type or storage class bibtex.h:81: error: syntax error before "unbreakable" ... and the list goes on. for one glib.h is in $(top_builddir)//root/Installs/glib-2.2.3/./glib the rest seems like an incompatibility with gcc 3.3.2, doesn't it? has anyone tried to build with this version of gcc? or if someone can point me to the correct mailing list i would appreciate it. thanks, alex. From fnord at u.washington.edu Mon Dec 15 15:42:43 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 15 Dec 2003 12:42:43 -0800 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: <3FDDC8FE.AED055CB@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3FDDC8FE.AED055CB at engcorp.com>... > ... > Perhaps Photoshop "transparently" (no pun intended) saves the alpha data > to some other location, but magically restores it when you reload the .jpg? > That pun was _clearly_ intentional. From nav+posts at bandersnatch.org Tue Dec 16 10:22:02 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 16 Dec 2003 10:22:02 -0500 Subject: Python in a spreadsheet References: <3064b51d.0312151318.277c8c06@posting.google.com> Message-ID: beliavsky at aol.com writes: > Is it possible to call a Python function from Calc (the Open Office > spreadsheet) or Microsoft Excel? Are their web sites or books > describing how to do this? You could check out the latest version of StarOffice from Sun (version 7, I believe) -- apparently it has Python scripting support built-in. I found that pretty interesting... Isn't Sun committed to something called Joe or Java or something like that? Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From aahz at pythoncraft.com Tue Dec 9 09:34:44 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Dec 2003 09:34:44 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: In article , Jacek Generowicz wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> Jacek Generowicz wrote: >>> >>>I have a program in which I make very good use of a memoizer: >>> >>> def memoize(callable): >>> cache = {} >>> def proxy(*args): >>> try: return cache[args] >>> except KeyError: return cache.setdefault(args, callable(*args)) >>> return proxy >>> >>>I've got to the stage where my program is still not fast enough, and >>>calls to the memoizer proxy are topping profiler output table. So I >>>thought I'd try to see whether I can speed it up by recoding it in C. >> >> I'm wondering whether you're tackling something the wrong way > >There _is_ always that possibility, but I don't think that's what my >problem is here (it may well be elsewhere in my program). > >> or perhaps you need to throw hardware at the problem. > >The definition of "not fast enough" in this case, is "much slower than >a competing C++ implementation", so throwing hardware at it advances >me not one bit, I'm afraid. > >> Dicts are one of the most highly optimized parts of Python, > >Which is exactly why I'm using them extensively. > >> and if your cache hit rate is higher than 90%, you'll be dealing >> with exceptions only rarely, > >My cache hit rate is well over 90%. All your comments taken as a set make no sense. There's just no way that a bunch of dict accesses in Python can be much slower than a C++ program. (C program, *maybe* -- not C++) >> so the speed of cache.setdefault() isn't where your time is going. >> I'm wondering whether you're hitting some kind of memory issue or >> something, or possibly you're having cache effects (in CPU/memory), >> or maybe even your key is poorly constructed so that you're getting >> hash duplicates. > >No, I think that my memoizer works just fine. The "problem" is that >I've memoized a lot of functions, and quite a few of them are being >called in my inner loops. If I want to compete on speed with C++, I'm >simply going have to eliminate Python bytecode from my inner loops[*]. > >[*] Unless my overall algorithm is completely wrong, of course. Waitasec .... okay, I see what your problem is, assuming you're describing it correctly. The problem is that you're calling Python functions in an inner loop. I think you're going to need to write a solution that doesn't call functions (function unrolling, so to speak). Instead of returning a memoizer function, just use a dict of dicts. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From n.favrefelix at _free.fr Sat Dec 27 05:44:04 2003 From: n.favrefelix at _free.fr (Nicolas =?ISO-8859-15?Q?Favre=2DF=E9lix?=) Date: Sat, 27 Dec 2003 11:44:04 +0100 Subject: Identifying File type by reading files References: <93f5c5e9.0312261056.22365aa7@posting.google.com> Message-ID: <3fed6489$0$29088$636a55ce@news.free.fr> Try to get the source code of the GNU program 'file'. I give you some examples : $ file sqlite.bin sqlite.bin: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.2.5, statically linked, stripped $ file doc.pdf doc.pdf: PDF document, version 1.4 $ file archive.tar.gz archive.tar.gz: gzip compressed data, from Unix $ file music.mp3 music.mp3: MP3, 128 kBits, 44.1 kHz, JStereo If you plan to run your script in a UNIX environment, maybe you can look this way, but if it must be portable, you can compile different versions of file.c to be called with popen. Or if you feel having a lot of free nights to spend on it, you can study the C source code and convert it to Python. Good luck! From abelikov72 at hotmail.com Thu Dec 4 12:51:10 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 04 Dec 2003 17:51:10 GMT Subject: ISO to Gregorian, strptime madness References: <3FCF562A.23E44C27@engcorp.com> Message-ID: On Thu, 04 Dec 2003 10:43:38 -0500, Peter Hansen wrote: >Afanasiy wrote: >> >> While I'm posting, how about this old dilemma... from the 2.3 modules. >> strptime exists in time, but not in datetime, while strftime exists in >> both. > >Uh, really? Ok, I checked it out, even though it's not my primary concern. >Looks to me like strptime and strftime are both in time and not in datetime. datetime the class in the datetime module has strftime but no strptime >>> datetime.datetime.strftime >>> datetime.datetime.strptime Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'datetime.datetime' has no attribute 'strptime' >>> So... I do this sort of thing : t1tmp = time.strptime(sometext,timeformat) t1 = datetime.datetime(*t1tmp[0:6]) -AB From anton at vredegoor.doge.nl Sun Dec 14 12:00:34 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 14 Dec 2003 18:00:34 +0100 Subject: optimization pointers? References: <3fd9cdf1$0$6970$7a628cd7@news.club-internet.fr> <3fdb7e6f$0$6968$7a628cd7@news.club-internet.fr> Message-ID: <3fdc986a$0$117$3a628fcd@reader1.nntp.hccnet.nl> "Anthony McDonald" wrote: >return len (voc.keys()) > >Which creates a list of keys to then apply len to, but thats an unneeded >step as len applied directly to a dictionary returns the number of keys. Below are two more small optimization possibilities. Originally I wasn't going to post them because they are way into micro optimization country and because the setdefault solution is beautiful but blond. At least on some of my machines however they are both faster than the solutions offered so far. Anton def lzx(s): word,D = '',{} Dget, Dset = D.get, D.__setitem__ for c in s: word += c if not Dget(word): Dset(word,True) word = '' return len(D) def lzy(s): j,D = 0,{} func = D.setdefault for i in xrange(1,len(s)+1): if func(s[j:i],j) is j: j = i return len(D) From cartermark46 at ukmail.com Mon Dec 1 05:35:45 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 1 Dec 2003 02:35:45 -0800 Subject: wxPython: combining wxListCtrl and wxCheckBox Message-ID: I would like a wxListCtrl with 3 columns in it. The number of rows in it will vary during run-time. In the first column of each row should be a wxCheckBox, which the user can check or uncheck. Is such an arrangement possible? Any example source code? wxCheckListBox comes close - but not close enough. Unfortunately, it does not derive from wxListCtrl, which contains the function InsertColumn() needed for multiple columns From nospam at freeworld.fr Fri Dec 12 09:42:42 2003 From: nospam at freeworld.fr (Lucas Branca) Date: Fri, 12 Dec 2003 15:42:42 +0100 Subject: Zope import PythonScript.standard unauthorized References: Message-ID: > I found out that the problem is in Products/PythonScript permission. > To test them, in the ZMI, I created this script and then I tested it > > ============================================== > SCRIPT > ============================================== > # Example code: > from Products.PythonScripts.standard import html_quote, urlencode > return 1 > > ============================================== > OUTPUT DU TEST > ============================================== > Zope has encountered an error while publishing this resource. > > Error Type: ImportError > Error Value: import of "urlencode" from "Products.PythonScripts.standard" is > unauthorized > OK.... if somebody else have same problem and Googling come here, that's the way I went (and now all works) on Debian I used package for Zope (2.5.1) and Python (2.1.3) from woody and I received the error above now I removed debian zope package ( :( sigh sigh ) , and I 'm using http://zope.org/Products/Zope/2.6.2/Zope-2.6.2-linux2-x86.tgz Finally, all works fine ..... Lucas From tim.golden at viacom-outdoor.co.uk Tue Dec 30 05:17:06 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 30 Dec 2003 10:17:06 -0000 Subject: Monitoring an MS Exchange mailbox Message-ID: >From: Lindstrom Greg - glinds [mailto:Greg.Lindstrom at acxiom.com] > >I have written a script to monitor my MS Exchange mailbox for certain >messages and post information to an MS SQL Server Database. Everything >works great except that each time I run the script I am >prompted by Windows >to choose the profile of the mailbox via a dialog box. > >Is there any way to either specify the profile or accept the default? You have three options that I can think of. I assume you're using CDO (ie the MAPI.Session COM object). Each of the techniques should leave you with a working session. The Logon method has a number of other parameters controlling, for example, whether a dialog box should be displayed if the logon fails and so on. Consult MSDN for details: it's quite lucid on the subject. 1) Hardcode a profile name with the options you need and pass it in: import win32com.client session = win32com.client.Dispatch ("MAPI.Session") session.Logon (ProfileName="Tim Golden") # obviously replace my name by the # display name of your profile, the # one that appears in the dialog box 2) If you don't have that much control, find the user's default profile and use that: import win32com.client import _winreg reg1 = "\\".join ([ "Software", "Microsoft", "Windows NT", "CurrentVersion", "Windows Messaging Subsystem", "Profiles" ]) reg2 = "\\".join ([ "Software", "Microsoft", "Windows Messaging Subsystem", "Profiles" ]) try: key = _winreg.OpenKey (_winreg.HKEY_CURRENT_USER, reg1) except: try: key = OpenKey (_winreg.HKEY_CURRENT_USER, reg2) except: key = None if key: try: default_profile, should_be_string = \ _winreg.QueryValueEx (key, "DefaultProfile") except: default_profile = "" session = win32com.client.Dispatch ("MAPI.Session") session.Logon (ProfileName=default_profile) 3) One other option, with limitations, is to construct a profile info string on the fly, and pass that to the logon method: import win32com.client EXCHANGE_SERVER = "xyz" MAILBOX_NAME = "tim.golden" # # Obviously replace the server and # mailbox names to suit. # session = win32com.client.Dispatch ("MAPI.Session") session.Logon ("%s\n%s" % (EXCHANGE_SERVER, MAILBOX_NAME)) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From alanmk at hotmail.com Wed Dec 10 08:01:18 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 10 Dec 2003 13:01:18 +0000 Subject: Python and Flash References: Message-ID: <3FD7191E.2F2FBDC7@hotmail.com> [Mars Spider] > Is there a way to embed a Flash Animation (es: a menu) into a Python > aaplication for desktop? There was a thread about doing this on Windows, using COM, a few months back. http://groups.google.com/groups?selm=RvPFa.37%24zx6.1430%40news.optus.net.au I don't know how one would approach the problem on other platforms. HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From sillyman71 at hotmail.com Mon Dec 15 15:21:39 2003 From: sillyman71 at hotmail.com (Scott Silliman) Date: 15 Dec 2003 12:21:39 -0800 Subject: ImportError on _socketmodule.so when running a frozen program References: <1c03f108.0312111557.7a183f4@posting.google.com> Message-ID: <1c03f108.0312151221.4f4239ad@posting.google.com> Hmm, I just ran objdump and it definitely looks like the PyInt_FromLong definition is statically linked into the executable. Any ideas as to why loading a shared library would fail saying PyInt_FromLong is an undefined symbol? 0807cf90 : 807cf90: 55 push %ebp 807cf91: 89 e5 mov %esp,%ebp 807cf93: 83 ec 18 sub $0x18,%esp 807cf96: 89 75 f8 mov %esi,0xfffffff8(%ebp) 807cf99: 8b 75 08 mov 0x8(%ebp),%esi . . . sillyman71 at hotmail.com (Scott Silliman) wrote in message news:<1c03f108.0312111557.7a183f4 at posting.google.com>... > I'm getting the following when I run my executable: > > File "/usr/lib/python2.2/socket.py", line 41, in ? > from _socket import * > ImportError: /usr/lib/python2.2/lib-dynload/_socketmodule.so: > undefined symbol: PyInt_FromLong > > However, if I run 'nm' on the executable, I get the following output: > > 0807cf90 T PyInt_FromLong > > doesn't this mean that PyInt_FromLong() is staticly linked into the > executable (got it when it staticly linked in > /usr/lib/python2.2/config/libpython2.2.a )? > > Any ideas as to why it doesn't think this symbol is defined? > > -Scott From peter at engcorp.com Wed Dec 10 09:24:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Dec 2003 09:24:21 -0500 Subject: Test References: Message-ID: <3FD72C95.5411A70@engcorp.com> Andre Louw wrote: > > a Test post Please use misc.test instead of this or other newsgroups for testing your posting ability. Thank you. -Peter From lunqual at gmx.de Thu Dec 18 13:27:10 2003 From: lunqual at gmx.de (Karlheinz Klingbeil) Date: Thu, 18 Dec 2003 19:27:10 +0100 Subject: [reportlab] print directly to printer Message-ID: I have deonwloaded and tested reportlab, which seems to be good enough for my needs with printing reports, formatted text and such things. But i have a question: I have not seen any hint in the docu how to print a generated PDF directly to the printer in a portable manner, it has to work under all OS's any comments ? -- Greetz Karlheinz Klingbeil (lunqual) http://www.lunqual.de oder http://www.lunqual.net From newsgroups at jhrothjr.com Sun Dec 21 07:41:40 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 07:41:40 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Bengt Richter" wrote in message news:bs2j3b$fc5$0 at 216.39.172.122... > On Sat, 20 Dec 2003 06:38:20 -0500, "John Roth" wrote: > > > >Sure, you can use a property to not have to put > >in the explicit function call, but then you can't put > >in the explicit function call *anywhere* you use that > >property. > > > Nor can you supply explicit arguments if you want to, though you could > provide an alternate name, so you could access either way. That's really an inherent feature of the 'property' notion: since it's accessed like a variable, the getter can't have any parameters. Since the property access return an object, I suppose you could have something that looks like an indexable or slicable property. > Nor can we do properties without accessing them via the attribute magic (i.e., > not via bare global names for example). > > >Ruby syntax makes it *optional*. That's what is > >missing here. > I've floated various ideas/brain_farts more/less seriously for triggering magic > via name access alterantive to getattr magic, but there seems to be no enthusiasm > or else horrification at the thought, so I haven't stirred that pot for some time ;-) > > What would be the syntax you would like to use, with what effect? Well, the basic idea was simply to make the () optional for functions with no parameters. No particular syntax there but it would require some major jump through hoops gyrations from the virtual machine, and there would have to be some way of getting the function object when you wanted it, and I suspect the difference between a function object and a more general 'callable' would totally confuse most people. And of course, does a function/method with only keywords count as a function with no parameters? Ruby can get away with it because, as far as I know, functions are not first class objects. They certainly aren't in Perl which was Ruby's inspiration. It's a non-starter for Python, though. John Roth > > Regards, > Bengt Richter From skip at pobox.com Mon Dec 15 14:40:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Dec 2003 13:40:30 -0600 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031215191023.GB26055@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> Message-ID: <16350.3630.307765.836000@montanaro.dyndns.org> >> My understanding was that in 2.0 it was also broken, but that >> (relatively) recent changes to Python made the breakage easier to >> exploit. Luke> the issue is [back-tracking to the 2.0 code], Luke> were those "breakages" actually features, or were they definitely Luke> "breakages"? Dunno. Take a look at the 2.3 Whats New: http://www.python.org/doc/current/whatsnew/node18.html Search for "rexec". I don't know more than that. It only mentions back as far as 2.1, so I don't know if rexec could be made to work based upon the code in 2.0. Also, check this thread from python-dev: http://mail.python.org/pipermail/python-dev/2003-January/thread.html#31842 That thread includes some indication of what the problem is and how it got worse in 2.2 and 2.3. Skip From paulo.pinto at cern.ch Mon Dec 15 10:37:11 2003 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Mon, 15 Dec 2003 16:37:11 +0100 Subject: Build classes/packages dinamicaly Message-ID: Hi, I have a package that generates classes from a set of XML files using exec. So far the classes appear in the global namespace. Is there any way to also create packages dinamicaly and add the classes to those packages? Thanks in advance, Paulo Pinto From __peter__ at web.de Tue Dec 30 18:50:39 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Dec 2003 00:50:39 +0100 Subject: selecting a random item from a set References: <7xsmj1dgox.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The classic way to do it goes something like this: > > for n, randomElement in enumerate(s): > if random() < (1.0 / (n+1)): > e = randomElement 0 <= random() < 1 1.0/(n+1) == 1 for n == 0, so this will always choose the first element. > # possibly followed by > s.remove(randomElement) > > Note that you don't need to know the size of the set in advance. You > can use the same method for (e.g.) choosing a random line from a file, > without knowing how many lines the file has, and without having to > read the file twice or store it in memory. > > Seeing why this works (unless I made an error) is left as an exercise :). Peter From tchur at optushome.com.au Tue Dec 30 02:05:08 2003 From: tchur at optushome.com.au (Tim Churches) Date: 30 Dec 2003 18:05:08 +1100 Subject: New candidate for Python mascot Message-ID: <1072767908.4130.1248.camel@emilio> See http://news.independent.co.uk/world/asia/story.jsp?story=476931 -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From eddie at holyrood.ed.ac.uk Tue Dec 2 11:40:18 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 2 Dec 2003 16:40:18 +0000 (UTC) Subject: language learning vs. process References: Message-ID: "Ryan Walker" writes: >Hi, >I'm getting started with python and have almost zero programming experience. >I'm finding that there are tons of tutorials on the internet -- such as the >standard tutorial at python.org -- that tell you all about the language. >That is, what are the methods, functions, modules, syntax, punctuation, etc. >No problem there! >Meanwhile, I'm finding that there is very little (that I can find) about how >to do basic logistical things related to using python and implementing >programs. For example: how to run a program. That's pretty basic, but I >don't see anything in the tutorials about it. With IDLE, it's easy enough: >just hit F5. But working on my server via Putty, trying to get a concrete, >meaningful result, it's hit and miss. For example, I find that sometimes a >program will run if I import it. I typed "import smtpmail" and it ran -- it >asked me to input From, To, Subj, Message. Other times, I type in "import >smtpmail" and it imports but doesn't run. My server is Unix. Typing >"python smtpmail.py" doesn't do it. That seems to be what a few websites >say to do to run a program. Doesn't work for me. It returns 'File >"", line 1' and a little carrot pointing up at the 'l' in smtpmail. >I know it's on the path since I can import it. And the permissions are 755. It sounds like what you are looking for really is a tutorial on the OS itself so that you understand more about where files are etc. I've been using Unix for a long time so I have no idea what introductory material is good (just avoid Dummies and learn X in 24 hrs type books should cut it down). What's happening in the instance you give is that when people say type 'python smptmail.py', they mean to do it at the Unix command shell (sh or bash or whatever) NOT inside the python interpreter. >Another example of a very basic problem I can't find a solution to in any >tutorial: how to log in to an SMTP server (authentication). My web >searches have turned up only a few snippets of listserv conversations >between people who already know enough about the subject that I'm not able >to divine anything from the code they pass back and forth. A search on >Python.org doesn't turn up anything that would help newcomers. >So basically, what I'm saying is, there is a wealth of information about how >to concatenate strings and stuff like that, but I'm finding it very >difficult to get started with basic processes and logistical things. For >example, it took me longer than I care to admit to figure out how to append >the sys.path (that's actually in the tutorial but it's somewhat >inconspicuous.) >My ideal beginner resource would be a complete, step-by-step explanation of >how to implement a simple program -- starting with typing "python" at the >command prompt and ending with some kind of concrete result. Then, with a >complete understanding of the process of writing and implementing (emphasis >on the latter) a program, my efforts to learn the content and syntax of the >language itself will be a lot more meaningful. That is, I can learn things >like what a string is and have some confidence that I'll actually be doing >something (other than playing with a calculator) that can provide something >of value to end users in far flung places. >Might seem weird to start with learning process and implementation, since >it's all dependent to a large extent on using the language properly, but I >do think it's possible to learn implementation first (with a bare minimum of >language learning) and then go back and learn more about the language. Just >something to think about for the excellent people who teach ingrates like me >how to program. >If anyone has any pointers on where to get more how-to information more >oriented towards process/logistics please let me know. It occurs to me that some of the Linux and even PC magazines seem to be running tutorials on how to use Python. They probably cover some such issues. Eddie From jjl at pobox.com Wed Dec 24 08:03:42 2003 From: jjl at pobox.com (John J. Lee) Date: 24 Dec 2003 13:03:42 +0000 Subject: creating EPS with Python References: Message-ID: <87fzfa5pw1.fsf@pobox.com> hwlgw at hotmail.com (Will Stuyvesant) writes: [...] > error: Python was built with version 6 of Visual Studio, and > extensions need to be built with the same version of the compiler, but > it isn't installed. > > Bah! > > Maybe there is something in the .py files I can use. You could rebuild Python with MSVC 7 (free download of non-optimising compiler), or use cygwin Python (or mingw Python? Not sure if that exists...). John From fumanchu at amor.org Wed Dec 10 16:44:13 2003 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 10 Dec 2003 13:44:13 -0800 Subject: Invocation, how to Message-ID: One way would be: getattr(foo, "method")(arg1, arg2, ...) FuManChu > -----Original Message----- > From: Raaijmakers, Vincent (IndSys,GE Interlogix) > [mailto:Vincent.Raaijmakers at ge.com] > Sent: Wednesday, December 10, 2003 1:32 PM > To: python-list at python.org > Subject: Invocation, how to > > > I admit.. must be in the manual but can't find it. > > > If my method is a string, say "method" > > How to call foo."method" ? > This is invocation in java, but how to do it in python? > > Thanks, > Vincent > > -- > http://mail.python.org/mailman/listinfo/python-list > From edreamleo at charter.net Thu Dec 11 13:48:46 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 11 Dec 2003 12:48:46 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: > that's why you should design your own leo widget: > > http://effbot.org/zone/wck.htm > > half-serious-ly yrs /F Thanks for this link. I'll look into it. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From exarkun at intarweb.us Tue Dec 16 10:58:20 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 16 Dec 2003 10:58:20 -0500 Subject: introspecting builtin functions/methods In-Reply-To: References: Message-ID: <20031216155820.GA32321@intarweb.us> On Tue, Dec 16, 2003 at 03:56:45PM +0000, Gon?alo Rodrigues wrote: > Hi, > > Does anyone know if and how I can, from within Python, read the > signatures of builtin methods/functions? > The signatures for builtins are not available via any of the normal introspection routines. The way argument parsing works in C makes it so that the expected arguments are not available anywhere (typically) except as a string literal inside the function definition. It would be pretty handy if this information was available, but I think converting the existing code to make it available would be a herculean effort. Jp From fperez528 at yahoo.com Mon Dec 15 17:32:45 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 15 Dec 2003 15:32:45 -0700 Subject: run Fortran from python References: <31e18870.0312142131.5cf4d329@posting.google.com> Message-ID: SamX wrote: > I know Tcl can run Fortran excutables. Can python do the same? > Thank you google('f2py') From mesteve_b at hotmail.com Wed Dec 24 09:34:35 2003 From: mesteve_b at hotmail.com (python newbie) Date: Wed, 24 Dec 2003 14:34:35 GMT Subject: IDE for debugging Message-ID: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> I need the ability to debug, so I think I'm learning toward buying Komodo, however this would only be for straight Python. When I start building a wxPython interface to my current program, will this work? Does anyone currently develop in wxPython and if so, are you using a dependable tool for debugging in this? Thanks Steve From jjl at pobox.com Thu Dec 11 18:09:49 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 23:09:49 +0000 Subject: More than one cookie with urllib2 References: Message-ID: <8765gn2bpe.fsf@pobox.com> "Rafael T. Ugolini" writes: > Im trying to add more than one cookie with urllib2 but im not getting > much sucess. > An example... > > > >>> req = > urllib2.Request('http://localhost','j_username=psyca&j_password=******',{ > 'Cookie':'sab=contextUrl+https%3A%2F%2Fwwws.vexbr.com.br%2Fcafedev%2F%7CnasIp+10.50.0.3%7CneedCheckCode+false%7ClocationId+85%7CautoLogout+false%7CserviceProviderId+1%7CorigUrl+%2Findex.html%7CwebContext+cafedev%7CclientIp+192.168.1.107%7CnasId+vex_cafedev%7CloginType+0%7Cclass+class+com.wificom.sab.aaa.dto.SessionDTO%7CloginResumed+false%7CloggedIn+false%7Clanguage+en%7CpricingPlanId+0%7CsslPort+443%7CroamingPriceId+0%7CclientMac+00%3A07%3A95%3AD3%3A0C%3A7C%7CserverUrl+https%3A%2F%2Fwwws.vexbr.com.br%2F', > 'Cookie':'JSESSIONID=DFA58D39389BA5E3CEB5C92F9308792C', > 'Content-type':'application/x-www-form-urlencoded', > 'Content-length':str(len('j_username=psyca&j_password=******'))}) > >>> urllib2.urlopen(req) [...] Blech. > and another thing , headers is a dic , you cant add 2 equal keys... > dunno how to do it. [...] If you want to stay sane, use this: http://wwwsearch.sourceforge.net/ClientCookie just say: ClientCookie.urlopen(req) and forget about cookies. If you insist on doing it by hand, though: you need to join your key=value pairs with semicolons: Cookie: foo=bar; spam=eggs John From nospam at nowhere.com Tue Dec 9 19:26:08 2003 From: nospam at nowhere.com (Courageous) Date: Wed, 10 Dec 2003 00:26:08 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com><4redncaHtOe2LEmiRVn-ig@comcast.com> Message-ID: >what parts of "The CLS does have pointers to methods, but the situations >in which they can be used are limited by the code validator" and "in neither >case can the function pointer come from a variable" did you have trouble >understanding? Probably most of it. I was tired. :) C// From joconnor at cybermesa.com Tue Dec 2 12:15:58 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 02 Dec 2003 10:15:58 -0700 Subject: python's threading has no "interrupt"? In-Reply-To: References: Message-ID: Dave Brueck wrote: >Jay wrote: > > >>>You've noticed that there isn't an identical construct for what you were >>> >>> >doing > > >>>in Java, so it may be that the Python way will be a completely different >>>approach to the problem rather than just a direct conversion from Java to >>>Python syntax. >>> >>> >>Well, I'll give an example from something I tried to do a few years ago >>which I couldn't translate to Python, though I took a stab at it. >> >>The language in question was a VM language with it's own internal >>process model. The process model was all inteneral to on eOS process to >>it was a cooperative model of multi-threading >> >>The application I wrote was a web server on the front of an application >>so that web requests were all handled in the application. IOW, the >>application had a web server interface) >> >>The language process model had both the ability to set process >>priorities, as well as allow processes to sleep and cede control to >>other processes. >> >>When a web request would come in, the handling of the request would be >>forked as a seperate process so that the server could accept the next >>request. Both the server process and the handling process(es) were at >>the same priority level so in theory each process would run to >>completion before allowing another process to run. For this reason, >>both the server process and the handling processes would issue a 'yield' >>at periodic strategic points, allowing themselves to temporarily halt >>and for the next process of equal priority that was waiting to run. >> >> > >So, if I understand this correctly, this amounted to a manual task switcher, >right? (as no more than one job was allowed to run concurrently). Was this >really the desired behavior? If each process halts while the others run and >does so only to prevent starvation in the other processes, wouldn't you get >more or less the same results by just using normal forking/threading wherein >the OS ensures that each process/thread gets a slice of the CPU pie? (IOW, >unless there was some other reason, it seems that the explicit yielding was to >work around the constraints of the process model) > > Partially, the processes were sharing a (sometimes very large) common in-memory object web so forking seperate os level threads was not feasible. Also, the server ran on multiple OS platforms so OS level tricks or threading mechanisms were not viable So... what was going wrong that warranted killing the process in the first >In practice the need for that is pretty rare, especially for a server, >the main case coming to mind being the execution of user-supplied code (which >is pretty scary in and of itself!). > Irt didn't happen that often but it was mostly due to the client disconneecting permaturely and when yuor server is handling heavy traffic, it does become a resource issue after awhile. Like I said in anoter post, there was also bookkeeping down during this time as well. From shlomme at gmx.net Wed Dec 3 11:21:49 2003 From: shlomme at gmx.net (Torsten Marek) Date: Wed, 03 Dec 2003 17:21:49 +0100 Subject: Advice on Python C modules In-Reply-To: References: Message-ID: Mike Rovner schrieb: > Torsten Marek wrote: > >>I think about rewriting one C++ library with Python wrappers (by sip) >> to a pure Python module (because I just use it from Python). >> >>I have to create custom types and inherit from those custom types. >>Is it better to use pure C for that module, Pyrex or should I stay >>with my current library (which has to be modified for some other >>reasons, too)? > > > It seems to me that you contradict yourself here. > Pure python is pure python without any c, c++, pyrex, sip, etc. > OTOH, if you still need compiled extension for some reason > (usualy only two excuses are good enough- speed and low-level > interface to something as hardware or 3rd party libraries) > why throw out good working code? It's not a good practice. > > So if you don't *have to* use compiled extension you can ask how to achieve > desired results in pure python. > You're right, sorry. What I meant was compiled extension, because I need access to 3rd party libs and I do not want to use their Python bindings for speed reasons. Torsten From ferdy at ferdy.com Fri Dec 26 15:04:25 2003 From: ferdy at ferdy.com (ferdydurke) Date: Fri, 26 Dec 2003 21:04:25 +0100 Subject: Help ! newbie problem Message-ID: hi, I am trying to learn python... I can't explain the difference beetween these two programms, Fibonacci suites : >>> a,b,c = 1,1,1 >>> while c<12: ... print b, ... a,b,c = b,a+b,c+1 ... 1 2 3 5 8 13 21 34 55 89 144 and >>> a,b,c = 1,1,1 >>> while c<12: ... print b, ... a=b ... b=a+b ... c=c+1 ... 1 2 4 8 16 32 64 128 256 512 1024 how about the instructions on the same block ? I thought they could be on the other lines... perhaps I don't understand a=b and b=a+b ? thanks in advance. From peter at engcorp.com Mon Dec 8 13:57:45 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Dec 2003 13:57:45 -0500 Subject: Elementric(?) import problem? References: Message-ID: <3FD4C9A9.A8A03CBB@engcorp.com> Rasmus wrote: > > Still learning python, I have searched for guides, and found this one: > http://www.cs.lth.se/Education/LU/kurser/dat108/PythonProgramming.pdf > > When trying some of the examples like > >>> from Numeric import * You need to download the package, as it's not part of the standard distribution: http://www.pfdubois.com/numpy/ See the last page of your PythonProgramming.pdf document for links including the above... -Peter From John_Dutcher at urmc.rochester.edu Thu Dec 4 11:36:53 2003 From: John_Dutcher at urmc.rochester.edu (John F Dutcher) Date: 4 Dec 2003 08:36:53 -0800 Subject: Why 'string' functions i.e. rstrip, upper, lower are 'not found'......... Message-ID: <2c82369d.0312040836.7374c789@posting.google.com> There must be a 'fundamental' reason why 'string' functions are reported as 'not found' even though the 'import string' statement is present. If the script has user-defined functions at its beginning and I remove them...doing all code inline, the 'not found' error goes away. Is there some 'placement of user functions' issue that explains why the 'import string' doesn't make the various string functions visible when I use various 'def userfunc's in the script ?? Thanks much, John D. From jzgoda at gazeta.usun.pl Fri Dec 12 17:16:41 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 12 Dec 2003 22:16:41 +0000 (UTC) Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> <3FD9D38F.C85433C9@engcorp.com> Message-ID: Edward K. Ream pisze: > My experience isn't that wxWindows doesn't work at all, it is that it takes > a lot more work to make wxWindows work as I expect than with, say, Tkinter. > It's a cost/risk issue. I should have made that clearer. wxPython reduces > that cost difference substantially, and Python provides ways of end-running > problems that didn't exist when I was using C++. There are times, when Tkinter doesn't work at all, i.e. on "second-half-of-world" terminals (non-ASCII/non-LATIN1). wxPython has no problems there. Yes, I know, it's due to flaws in TCL/Tk, not in Tkinter itself. But all Pythons ship with this flawed, broken, unusable Tk. And don't even try to argue, that my customers can "build their own Tk with bcc32 or OpenWatcom", they dont need to do anything more than install wxPython from readily-available binary distribution. NP: Sex Pistols - EMI -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From fredrik at pythonware.com Wed Dec 3 06:47:49 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Dec 2003 12:47:49 +0100 Subject: redirecting Stdin References: <3FCDB2C3.B87DE2BE@alcyone.com> Message-ID: Jon Arter wrote: > This results in a parsing error when the file reading reaches the > def detectip(): > sentence . > You can execute the command line as long as it is a single line > command > > How to Get arround this ? if you're trying to write your own Python command-line interface, use a real tool: http://www.python.org/doc/current/lib/module-code.html if you're just trying to run code from a file, load the entire file before you pass it to exec (or use execfile). From michael at foord.net Fri Dec 5 07:19:30 2003 From: michael at foord.net (Fuzzyman) Date: 5 Dec 2003 04:19:30 -0800 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: <8089854e.0312050419.2cf36e34@posting.google.com> "Francis Avila" wrote in message news:... > Fuzzyman wrote in message > <8089854e.0312040649.4a7f1715 at posting.google.com>... > >Pythons internal 'pointers' system is certainly causing me a few > >headaches..... When I want to copy the contents of a variable I find > >it impossible to know whether I've copied the contents *or* just > >created a new pointer to the original value.... > > > You don't need to divine the rules for copy vs. reference: Python NEVER > copies values, ONLY dereferences names, unless you EXPLICITLY ask for a copy > (which Python-the-language doesn't have any special machinery for; you have > to use the copy module or figure out how to copy the object yourself.) > [snip...] Interesting discussion reluctantly snipped....... > > The only mutable objects you usually have to worry about are dicts and > lists. Right - because if I do something like : a = 4 b = a a = 5 print b It prints 4... not 5. In other words - the line b = a creates a name pointing to the object 4, rather than a name pointing to the contents of a..... I think I see what you mean - since the object 4 is immutable...... the line a = 5 destroys the old name a and creates a new one pointing to object 5, rather than changing what the name a is pointing to. Since lists and dictionaries are mutable..... changing the contents modifies the object rather than destroying the refereence tothe old one and creating a new one..... Hmmmmmm... thanks......... Fuzzy From steve at ninereeds.fsnet.co.uk Sun Dec 28 21:23:10 2003 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Mon, 29 Dec 2003 02:23:10 +0000 Subject: recursion in grammar? References: <34ea966a.0312270509.5ecc2095@posting.google.com> Message-ID: <3hvuuvgenp6tjvadovhfdckqdrmj1agv13@4ax.com> On Sat, 27 Dec 2003 13:04:15 -0500, "Terry Reedy" wrote: > >"Peri" wrote in message >news:34ea966a.0312270509.5ecc2095 at posting.google.com... >> I'm trying to create Python parser/interpreter using ANTLR. >> Reading grammar from language refference I found: >> or_expr::= xor_expr | or_expr "|" xor_expr >> >> For me it looks like infinite recursion. > >Better to call it unbounded recursion. This is what makes general CF >languages/grammars more extensive/powerful that regular languages. > >In particular, the recursion is written as left recursion. >The equivalent right recursion would be >or_expr::= xor_expr | xor_expr "|" or_expr >The recursive 'call' is to the right of the connector literal instead of >the left. > >There are two types of linear CF parsers: bottom-up LR and top-down LL. >Each handles recursion written one way and chokes on recursion written the >other way. The two types have opposite requirements. (I forget which is >which.) Since Antler choked on left recursion, I presume that it is the >'other' type than Python's and that it requires right rather than left >recursion. So try reversing all the recursive definitions. (Or try first >the one that gives first error message and see if you get farther.) Unless I am seriously mistaken, bottom-up LR parsers do not choke on either left or right recursion. Right recursion, IIRC, requires unbounded stack space in principle, but works OK in practice for the simple reason that the input always defines a finite bound. It is certainly less efficient, and carrys the risk that a complex input might overflow the available stack space, but those are rarely serious issues these days. If LR parsing could not handle both left and right recursion, it equally could not handle both left-associative and right-associative operators. Of course most real parsers have specialised support to optimise these common cases, but pure-form bottom-up LR parsing algorithms such as LR(1) and LALR(1) are perfectly capable of handling both left and right associative operators, and they do so using left and right recursion as appropriate. Which raises an important point - if you change the grammar to swap the recursions from left to right or whatever, that results in a major code-breaking change in how the parser interprets the language. Left-associative expressions will be parsed as right-associative and visa versa. Maybe worthwhile as a test to see what happens, but no good for a final parser that is intended to work on real Python code. Well, not without some post-processing of the resulting AST anyway. ANTLR definitely uses LL parsing. I don't know about Pythons parsing engine, though I suspect it uses LR-style parsing. It is a basic fact of life that LL parsers and LR parsers do have quite different limitations, and if Python uses LR parsing it will probably be impossible to build a parser for the (unmodified) Python grammar using an LL tool such as ANTLR. However, I find it hard to believe that ANTLR has no means of working around these issues with some relatively simple tweaks to the grammar specification. I would raise the question in comp.compilers, or check if ANTLR has a mailing list. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From antonmuhin at rambler.ru Mon Dec 29 08:46:21 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Mon, 29 Dec 2003 16:46:21 +0300 Subject: Best match searching In-Reply-To: References: Message-ID: Daniel Pryde wrote: > Hi everyone. > I was wondering if anyone might be able to help me out here. I'm > currently looking to find the quickest way to find a best fit match in a > large array. > My problem is that I have an array of, say, 600*400, which contains a > value at each point, and I need to find the value in that array which is > closest to the input value. It's basically some euclidean distances that > I've calculated, and I need to be able to find the best matches over a > large number of input values, so I was looking for a speedy solution to > this. > The array is implemented simply using a list of lists. The only solution > I could think of is to use some for statements, but that seems to take a > while, even for just one search. > Any hints or tips would be really helpful. :-) > > Daniel > > _________________________________________________________________ > Express yourself with cool new emoticons > http://www.msn.co.uk/specials/myemo > > I'm not an expert, but I'd use numarray module. The most simple example can look like: a = numarray.array(....) # An array to look in value = x # Value to look for c = a.copy() # Create a copy print numarray.abs(a.copy() - value).argmin() # Finds minimal absolute difference If performance of numarray is still too slow, I'd resort to simple hasing scheme: you can split your inputs in reasonable ranges and look for closest match only in this ranges. hth, anton. From tjreedy at udel.edu Fri Dec 5 23:54:59 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 Dec 2003 23:54:59 -0500 Subject: min and max id numbers References: Message-ID: "r.e.s." wrote in message news:l08Ab.449$_r6.361 at newsread1.news.pas.earthlink.net... > Just curious ... > > On a given machine, is it possible to create objects LO and HI, > such that for all objects x, id(LO) <= id(x) <= id(HI) ? You have no control over the id of PyObjects. id's are mostly for internal use of the interpreter. tjr From simonb at NOTTHISBIT.webone.com.au Sun Dec 28 20:36:20 2003 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Mon, 29 Dec 2003 12:36:20 +1100 Subject: Special-purpose extension of Python -- new kinds of objects References: <6714766d.0312281442.78cd0a4b@posting.google.com> <7xwu8glali.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 28 Dec 2003 16:40:57 -0800, Paul Rubin wrote: > Jeff Epler writes: >> In your case, you could re-cast the "decision network" in terms of class >> definitions, and get pretty similar behavior if those classes have the >> right behavior in metaclasses: >> class my_example(DN): >> class X(Chance): >> cpd = gaussian(mean=25, std_dev=75) >> class Y(Chance): >> cpd = gaussian(mean=12, std_dev=19) >> Z = X + Y > > When you say Z = X + Y, you've added two classes together. Can you > actually do that with metaclasses? Yeah, i did this with the comparison operators on classes: http://groups.google.com.au/groups?hl=en&lr=&ie=UTF-8&threadm=pan.2003.09.11.01.50.58.897682%40webone.com.au&rnum=1&prev=/groups%3Fq%3Dburton%2Bclass%2Bgroup:comp.lang.python.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.lang.python.*%26selm%3Dpan.2003.09.11.01.50.58.897682%2540webone.com.au%26rnum%3D1 funkalitious. Simon. From paul at boddie.net Wed Dec 10 06:52:36 2003 From: paul at boddie.net (Paul Boddie) Date: 10 Dec 2003 03:52:36 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: <23891c90.0312100352.73db003c@posting.google.com> "Mike Rovner" wrote in message news:... > > It reminds me of Microsoft's promise to combine RDBMS and file system in a > new Longhorn OS. Several years ago that idea was highly popular but nothing > came out. Longhorn isn't supposed to be out before 2006, unless you live in Malaysia (apparently). Is this a message from the future? ;-) Actually, I can imagine that it isn't quite equivalent to the much-hyped Longhorn features and the GNOME Storage stuff, since a filesystem typically provides a fairly rigid naming interface, although I'd admit that the same kinds of naming issues superficially exist with Web applications, and you can always disregard the hierarchical "assumptions" there and interpret the query string in your own way. One thing I dislike about various Web frameworks is that they don't really let you disregard the directory-like nature of the namespace, forcing you into mod_rewrite and other magic to "name things your own way". > That approach may be very interesting to allow user to use some plug-ins for > the file system (access, security, notification, etc.). What about doing the kinds of things that KDE's IOSlaves and GNOME's VFS do, but at a lower layer in the system (and in a sane language, of course)? Python lets you do HTTP, FTP and loads of other protocols fairly trivially - imagine hooking that up to a filesystem interface. Paul From tr at jotsite.com Sat Dec 13 10:30:39 2003 From: tr at jotsite.com (Hoang) Date: Sat, 13 Dec 2003 15:30:39 GMT Subject: install multiple versions of activepython Message-ID: Is it possible to install multiple versions of ActivePython on the same machine? Many modules which used to work with Python 2.2 now don't on 2.3. I am using some 2.3 features but lots of programs that used to work, don't anymore. This is especially true with modules that expose their libraries as DLLs. Has backward compatibility been a nagging problem with Python? Please feel free to chide me if this is a no-brainer question. Hoang Do http://jotsite.com From miki.tebeka at zoran.com Tue Dec 30 07:47:35 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 30 Dec 2003 04:47:35 -0800 Subject: Programming language from python References: Message-ID: <4f0a9fdb.0312300447.47c421ec@posting.google.com> Hello Alejandro, > I need to create a programming language. Can this be done with the > latest version of python? Yes. There are many compiler tools written in python. Google for "python lex yacc". > Is python the best computer programming > language development tool in the entire universe? I've heard they have some very good programming languages over at Venus :-) A programming language is like a tool, it's good for some things and not good for other things. As a general purpose langauge it's as good a they come. HTH. Miki. From just at xs4all.nl Wed Dec 10 16:59:16 2003 From: just at xs4all.nl (Just) Date: Wed, 10 Dec 2003 22:59:16 +0100 Subject: Lists and Tuples References: Message-ID: In article , "Fredrik Lundh" wrote: > Robert Brewer wrote: > > > Now if somebody can just figure out why: > > > > threading.Thread(args=()) > > > > but: > > > > threading.Timer(args=[]) > > > > we'll have this topic nailed down pretty well. ;) > > different authors; the threading module itself is really old (1.5?), > but the Timer class was added in 2.2, and nobody spotted the > inconsistency at that time. > > not sure if this can/should be fixed; there might be someone out > there doing: > > t = threading.Timer(interval, function) > t.args.append(value) > t.start() That would be totally broken, mutable default args and all. In the Thread class, the mutable kwargs argument isn't so bad, since it's assigned to a "private" attribute, but the _Timer class uses a plain attr, so is asking for trouble. Even if I know my code doesn't modify mutable arguments yet need a default, I'd still code it like this: def foo(kwargs=None): if kwargs is None: kwargs = {} ... Maybe I'm too strict here, but I think using mutable default arguments is at _least_ bad style. Just From max at alcyone.com Wed Dec 3 15:54:45 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 03 Dec 2003 12:54:45 -0800 Subject: lambdas (lambda x: printx) References: Message-ID: <3FCE4D95.A57F312D@alcyone.com> Michal wrote: > Today I started with python and I cannot understand why expresion > lambda x: print x > returns syntax error (but for example lambda x: sys.stdio.write(x) > does not) > First I fought the reason is scopeing, but it shouldnt return syntax > error. The problem is that you can only put an expression in a lambda form. print is a statement, not an expression. Other examples of statements are if...else control structures, variable assignments, and return statements. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Bring me men / Bring me men to match my plains -- Lamya From mlh at furu.idi.ntnu.no Fri Dec 12 16:58:56 2003 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Fri, 12 Dec 2003 21:58:56 +0000 (UTC) Subject: Why not match.expand('\\0')? Message-ID: I'm using the expand method of re MatchObjects, and was surprised to find that the references don't work with group 0... >>> import re >>> p = re.compile('foo') >>> m = p.match('foo') >>> m.group(0) 'foo' >>> m.expand('\\0') '\x00' Is this intended behavior? Why should group 0 behave differently from the others? -- Magnus Lie Hetland "The mind is not a vessel to be filled, http://hetland.org but a fire to be lighted." [Plutarch] From peter at engcorp.com Tue Dec 9 18:08:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Dec 2003 18:08:05 -0500 Subject: Using XUL with python References: Message-ID: <3FD655D5.274BA950@engcorp.com> Gabriele Farina wrote: > > Tnx a lot to everyone. > > I looked at Luxor yesterday, but I don't want to use jython to build my > application. > > Instead pyXPCOM seems a good job, but I cant install the estension under > windows. > > Now I'll try to read the documentation you give me and then I'll try to > install the extension. > > It seems pyXPCOM needs mozilla running to be functional. Is this true?? How > can I merge my program and mozilla toghether to work like Komodo does? It seems likely to me that since so few people are approaching application development this way, the answers are not straightforward and you should be prepared for a lot of trial-and-error development on your own, rather than finding a nice tutorial that tells you how to do it all. I could be wrong... it just doesn't look like mainstream technology from here. -Peter From guettli at thomas-guettler.de Tue Dec 2 10:07:43 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 02 Dec 2003 16:07:43 +0100 Subject: pygtk talk oinline References: <%3_yb.2963$nm6.17520@news.indigo.ie> Message-ID: Am Tue, 02 Dec 2003 10:45:27 +0000 schrieb Padrai: > Hi, > > I gave this talk about python and gtk programming > a couple of times, and it seemed to go down well. > The highlight I think were the sample apps which > people might find useful? > http://www.pixelbeat.org/talks/pygtk/ Hi, Would be nice to have a HTML version, for those don't have openoffice. thomas From http Thu Dec 11 04:22:37 2003 From: http (Paul Rubin) Date: 11 Dec 2003 01:22:37 -0800 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> Message-ID: <7xisknr9nm.fsf@ruckus.brouhaha.com> Robin Becker writes: > I was just about to ask if generators allow for a stream like mechanism, > but obviously if we're not allowed to change the generator state then it > seems quite hard. Well, there's always global state. From michael at foord.net Mon Dec 22 05:14:37 2003 From: michael at foord.net (Fuzzyman) Date: 22 Dec 2003 02:14:37 -0800 Subject: IDLE Problems - Subprocesses Under Windows Message-ID: <8089854e.0312220214.12bb92d7@posting.google.com> First of all a thanks to the guys at help at python.org who helped me get this far - when all I had was email access from a PocketPC ! I had problems using IDLE for editing modules in my code..... the only way I could find of forcing IDLE to re-import edited modules was to exit my main program and reload it... (Short of adding the location of my source code to the PYTHONPATH every time).... I used the windows installer to install Python and IDLE... by default it launches it with '-n' which starts IDLE *without* a subprocess.... I've edited it now and have *two* file associations - one to edit a file *with* subrocess and one *without*. This is because if I select 'edit with IDLE' it always opens a shell window.... if it tries to open a *second* shell with a subprocess then it hangs at that stage and I have to kill the process.... It obviously works fine if I remember to open the second file from within IDLE. I looks like I can have several versions of IDLE without subrocesses happily co-existing with one shell with a subprocess. Is this a known limitation with IDLE under windoze in it's correct incarnation ? - or is there something weird about my system (entirely possible).... Fuzzy From jburgy at hotmail.com Tue Dec 2 05:32:25 2003 From: jburgy at hotmail.com (Jan Burgy) Date: 2 Dec 2003 02:32:25 -0800 Subject: split on blank lines References: <807692de.0312010610.4461c0e3@posting.google.com> Message-ID: <807692de.0312020232.3c548c16@posting.google.com> Duncan Booth wrote in message news:... > jburgy at hotmail.com (Jan Burgy) wrote in > news:807692de.0312010610.4461c0e3 at posting.google.com: > > > can somebody tell me why (using Python 2.3.2) > > > >>>> import re > >>>> re.compile(r"^$", re.MULTILINE).split("foo\n\nbar\n\nbaz") > > ['foo\n\nbar\n\nbaz'] > > > > ? Being used to Perl semantics, I expect > > > > ['foo\n', 'bar\n', 'baz'] > > > > or something equivalent without the '\n' characters in the result > > strings. I have found that > > > >>>> re.compile(r"^\n", re.MULTILINE).split("foo\n\nbar\n\nbaz") > > ['foo\n', 'bar\n', 'baz'] > > > > I prefer the first version however because my intent is stated more > > clearly. Could this be a bug in sre.py (I looked at the code for a > > good two minutes but then my head started hurting) > > > > Given that re.compile("^$", re.MULTILINE).findall("foo\n\nbar\n\nbaz") > returns ['', ''] I would agree this looks like a bug. You could submit a > bug report on Sourceforge. > > Of course, if you really want to state your intentions, you could just use: > > >>> "foo\n\nbar\n\nbaz".split('\n\n') > ['foo', 'bar', 'baz'] > > as you aren't doing anything here that obviously benefits from regex > obfuscation. Thank you Duncan for your input. You're right, I will post a bug report on sourceforge. Why, you ask, do I split on "^$" and not simply "\n\n"? Simply because I'm dealing with an idiotic file format (not my own mind you) and that I really want to split on "^\t*$" (I agree with you that it's a rather arbitrary definition of a blank line, once again, not mine). When the above didn't work, I spent a long time questioning my understanding of regular expressions until I could simplify my code to the minimal amount that still yielded the error. Sometimes I wish that Python contained more elements from AWK (in particularly "RS" for instance) Cheers, Jan -- Being an actuary is a lot harder than being a mathematician: it is enough for a mathematician to prove that he or she is right. From fnord at u.washington.edu Thu Dec 18 12:39:58 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 18 Dec 2003 09:39:58 -0800 Subject: Installing tcl/tk on Linux References: Message-ID: Have you installed Tcl/Tk? See: http://www.python.org/topics/tkinter/download.html "For Unix, you must download, build and install both Tcl and Tk from the source. Build Tcl first. Each source distribution contains a README file explaining the process. It's about as simple as building and installing Python. Tip for GCC users: you must pass "--enable-gcc" to the configure script." From echols at OCF.Berkeley.EDU Mon Dec 1 05:43:51 2003 From: echols at OCF.Berkeley.EDU (Nathaniel Echols) Date: Mon, 1 Dec 2003 02:43:51 -0800 Subject: segfault in extension module In-Reply-To: <6250403b.0312010017.27f5f341@posting.google.com> References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: > > I've written a function in C to perform protein sequence alignment. This > > works fine in a standalone C program. I've added the necessary packaging > > to use it in Python; > Which one? Are you using the C API? Yup - I'm reading right out of the manual. > Looks like refcount problems, check out > http://www.python.org/doc/current/ext/refcounts.html . I read this before and couldn't figure out what it meant. This does seem like it would relate, but I can't figure out what I'm doing incorrectly. I just have one function which calls a pure C function and returns a tuple of strings from it. I'm guessing I need to add a Py_INCREF() somewhere but so far this just makes it segfault sooner. (I'm not sure what argument to use for Py_INCREF(), either.) I've looked at several other pages, and they all seem to involve setups more complicated than what I'm doing. I'm already using Py_BuildValue() to generate the returned tuple, and my understanding is that this should avoid major problems. . . > IMO just avoid all this stuff and use SWIG/Boost.Python/Pyrex. I'll look at these, but I only have a tiny little bit of code I need to do this with - I coded it from scratch with the intention of using it this way, and could have written it in Python if I didn't care about speed. Would I really benefit from using one of the other methods? The goal here is explicitly to put only the very time-dependent code in C; everything else stays in Python. thanks, Nat From dima at xenon.spb.ru Tue Dec 23 11:23:53 2003 From: dima at xenon.spb.ru (Dmitry Rozmanov) Date: Tue, 23 Dec 2003 19:23:53 +0300 Subject: nonlinear least square Message-ID: Hi. I am looking for simple and convenient way to do nonlinear least square fit from within Python. I know that there are such a modules in Scientific Python and SciPy has it. But I would like to have it small and simple. Module with just this functionality. It can be not very fast, but in pure python for beter compatibility. Can you recommend such a module? Thank you in advance. Regards. ---Dmitry. From bkelley at wi.mit.edu Wed Dec 3 06:48:32 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 03 Dec 2003 11:48:32 GMT Subject: Building a GUI agnostic database application In-Reply-To: References: <3fcd9d2a@mail.netspeed.com.au> Message-ID: Uwe Grauer wrote: > Take at look at PAF http://www.dctools.org > > Uwe > > Rasjid Wilcox wrote: > >> I am wanting to write a database application using Python. >> >> I want it to be GUI agnostic. The GUI will probably be >> Python/wxPython, but >> I would also like the option of a Webbased (PHP?) gui, and possibly GUI's >> in Java or C++, Visual Basic etc. >> >> The Python 'backend' may run on the same machine as the client (thick >> client), or on the same machine as the database (thin client). >> >> My main requirements are: >> 1. Reasonably light-weight >> 2. Secure authentication between the GUI and the backend. >> 3. Ideally runs wherever Python runs, and at least on Linux, Mac and >> Windows. Why not just make a database model that doesn't know anything about the GUI? The model can a python compliant database driver (say odbc or whatnot) and you can supply the proper business logic in a concise model. For example class model: def connect(self,...) def adduser(self,...) def addPurchase(self,user,item,cosperunit,units): Now using this database model you can control it with a webbased gui or a wxPython gui. I don't think that there is a need to use a wire protocol in this case to attach to your database code which itself uses a wire protocol to attach to the database. Just consolidate your code into a model. This is a typical model->view->controller approach. In my experience the best way to program this is to write the model first without using a gui, just a lot of test cases. Once the model does what you want, hook it up to a gui. This helps to ensure that the model works in at least two independent environments, the python interactive environment and also your gui code. Brian From Padraig at Linux.ie Tue Dec 16 04:54:49 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Tue, 16 Dec 2003 09:54:49 +0000 Subject: downloading long files In-Reply-To: <95aa1afa.0312152351.7b6143be@posting.google.com> References: <95aa1afa.0312152351.7b6143be@posting.google.com> Message-ID: <3FDED669.3060803@Linux.ie> Michele Simionato wrote: > I have a connection which is not 100% rock solid, so if I try > to download a large file (i.e. a Linux ISO image) chances are > that the connection will break. Is there a way to check periodically > if the connection is open, reopen it if needed, and continue the > download without restarting from the beginning? What has this to do with python? Anyway I'm assuming linux since you mentioned it, so use wget or even better: rsync -P rsync://rsync.server.com/path/to/file file P?draig. From jjl at pobox.com Tue Dec 16 08:40:07 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Dec 2003 13:40:07 +0000 Subject: compiling python-bibtex References: Message-ID: <87vfogyj7s.fsf@pobox.com> Alex Olivas writes: > i'm not sure whether this is the correct list for this question, but > i'm trying to > build python-bibtex-1.1.93.1 with gcc 3.3.2 and am getting the following [...] I presume this is from pybliographer? If so, post your question to the pybliographer-general mailing list. John From jester.dev at NOSPAMcomcast.net Fri Dec 12 18:09:25 2003 From: jester.dev at NOSPAMcomcast.net (Lord Jester) Date: Fri, 12 Dec 2003 23:09:25 GMT Subject: Linux GUI for python? References: <0mgna1-qv1.ln1@dman13.dyndns.org> Message-ID: On Fri, 12 Dec 2003 01:03:55 +0000, Derrick 'dman' Hudson wrote: > On Thu, 11 Dec 2003 23:20:01 GMT, Lord Jester wrote: >> Looking for any suggestions for a GUI for python >> under linux. Right now I'm just starting out but >> latter on I want to get into building programs >> that have GUIs. Any suggestions? > > I like wxPython or PyGTK. > > You'll have to investigate each and decide what you want in terms of > API and Look-and-Feel. > > -D Thanks everyone for the assistance. :) JesterDev From nessus at mit.edu Fri Dec 5 13:58:34 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 05 Dec 2003 13:58:34 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: mwilson at the-wire.com (Mel Wilson) writes: > To me, it's a distinction without a difference. Tuples > *act* like immutable sequences, and I use them that way. I > don't know, though, that I won't get caught some day. You'll be fine. The only thing you have to watch out for is that some rude folks here might call you names. |>oug From bwglitch at hotpop.com Wed Dec 17 13:53:49 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Wed, 17 Dec 2003 13:53:49 -0500 Subject: Compiling an *.exe from Python script In-Reply-To: References: Message-ID: Giraud, Sebastien wrote: > All in the subject : how can i do to make a win32 stand alone *.exe file > from a python *.py file?? Py2exe and McMillan's Installer are two of the most known for "compiling" Python source files into Windows executables. You should check them out and see which one fits you better. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- One good shot is worth a hundred bad ones! -- Big Shot (G1) From skip at pobox.com Sat Dec 20 23:08:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 22:08:11 -0600 Subject: Unicode from Web to MySQL In-Reply-To: <3FE4F2BC.5070901@rfa.org> References: <3FE47726.90504@rfa.org> <3FE4796D.1010609@rfa.org> <16356.44377.466955.783810@montanaro.dyndns.org> <3FE4F2BC.5070901@rfa.org> Message-ID: <16357.7339.91932.270995@montanaro.dyndns.org> Bill> Encoding for example is a UTF-8 page Vietnamese, Bill> try: Bill> http://www.rfa.org/service/index.html?service=vie ... Bill> I've tried grabbing this, doing vietstring.decode(None,'strict') Bill> gives an error (wants a string, not None), doing Yeah, I can see that passing None would be a problem. I assume vietstring is a string object, not a unicode object? If so, try uviet = unicode(vietstring, "utf-8") which would give you a unicode object. You can then convert it to other encodings if you want. Furthermore, if you know the string is already encoded as utf-8, you should be able to just stuff it in your database as-is. I store utf-8 strings in MySQL all the time. Bill> unicode(data,'unicode','replace') fails, Bill> unicode(data,'raw-unicode-escape','replace') somewhat works, Bill> I can then try Bill> unicode(data,'raw-unicode-escape','replace').encode('utf-8') Bill> but I get a SQL error at that point. Bill> (SQL statement is: Bill> ' Insert INTO test_utf8 (title) VALUES ( '%s') ' % data2 Bill> which if I put straight ascii text of some 1000 characters or so has Bill> no problem, Vietnamese gives me the SQL error. Can you paste an actual Python session into an email? Here's an example. Table looks like this: mysql> describe testac; +--------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | object_id | int(11) | YES | | NULL | | | object_title | varchar(64) | YES | | NULL | | +--------------+-------------+------+-----+---------+-------+ 2 rows in set (0.03 sec) Code looks like this: >>> conn = MySQLdb.Connect(host="localhost", db="test", user="someuser", ... passwd="somepasswd") >>> c = conn.cursor() >>> s = u'\u1234' >>> s u'\u1234' >>> s.encode('utf8') '\xe1\x88\xb4' >>> c.execute('insert into testac values (47, %s)', (s,)) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in execute return self._execute(query, args) File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.2/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue UnicodeError: Latin-1 encoding error: ordinal not in range(256) Note that trying to directly insert a Unicode object fails because it tries to perform a default encoding (in this case to Latin-1). The Latin-1 charset doesn't have an encoding for that codepoint. >>> c.execute('insert into testac values (47, %s)', (s.encode('utf-8'),)) 1L But encoding it as utf-8 succeeds. >>> c.execute('select * from testac where object_id=47') 1L >>> c.fetchall() ((47L, '\xe1\x88\xb4'),) And fetching that row shows that the object_title field does indeed have the three-byte utf-8 encoded string. Skip From claird at lairds.com Mon Dec 15 13:45:20 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 15 Dec 2003 18:45:20 -0000 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: In article , Gustavo Niemeyer wrote: . . . >Guile's static library is about 1MB in size. In that case I'd >choose Python, not Guile. I don't remember about Scheme, but while >looking for some embeddable language I've gone trough that path, >and ended up in Lua as the best option. Let me know if you find >something better. . . . I think your decision in favor of Lua's a good one. Guile and Scheme, from the last I saw of them, are *not* slender enough to compete. Forth is the one other serious language that can be tiny enough to make Lua look stout; while Forth hasn't made a good impression on me as a "configuration language", that might reflect my limits more than Forth's. -- Cameron Laird Business: http://www.Phaseit.net From bokr at oz.net Fri Dec 5 20:22:56 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Dec 2003 01:22:56 GMT Subject: How to tell the difference between string and list References: <877k1bmc2g.fsf@pobox.com> <87r7zjui71.fsf@pobox.com> Message-ID: On 05 Dec 2003 20:24:02 +0000, jjl at pobox.com (John J. Lee) wrote: >bokr at oz.net (Bengt Richter) writes: >[...] >> >>> s2 = ['abc','def'] >[...]> >> >>> s2 += 'ghi' >> >>> s2 >> ['abc', 'def', 'g', 'h', 'i'] > >That's not what the code I posted tests for. You mean __iadd__? I know, I was just showing ordinary list behavior, and showed that as well to imply that that's also something you might want to override in a consistent way if you were overriding __add__ as in my example. > >And the fact that having a+b not raise TypeError breaks that function >seems to me to be a good reason not to do that. Convince me ;-) _Any_ object with an __add__ method that does not exclude a string as a thing to add would pass your/Alex's isstringlike test. IMO that's too big a set of unanticipatable possibilites. Do you really want to dictate "never accept a str instance as other in __add__(self, other)" ;-) What do you want to be able to assume about an object obj for which isstringlike(obj) returns True, besides that it accepts strings for addition? Do you want to make those additional assumptions requirements for all objects that do pass the isstringlike test? Don't forget, an object's __add__ could be defined to accept _anything_ for addition, and a string would just be a generic thing, whose stringness was really irrelevant to the adding object. Are you making other assumptions based on isstringlike? If so, I think those assumptions should be an explicit part of the test, or you are setting yourself up for using the test and assuming the wrong things about some object. You can say you'll use exceptions will sort those things out, but then why pre-screen for stringlikeness? You may have a use case, but I suspect it will be context-dependent. The test is fine in a context where you can reasonably anticipate the mix of objects to be tested, but as a universal test, I would say s/isstringlike/willaddstrings/ or perhaps s/isstringlike/willaddatleastonestringbutyoumayhaveusedupthequota/ ;-) Regards, Bengt Richter From grey at despair.dmiyu.org Tue Dec 16 14:50:08 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Tue, 16 Dec 2003 19:50:08 -0000 Subject: Linux GUI for python? References: Message-ID: On 2003-12-11, Lord Jester wrote: > Looking for any suggestions for a GUI for python > under linux. Right now I'm just starting out but > latter on I want to get into building programs > that have GUIs. Any suggestions? Personally I use wxPython as the base with Boa-Constructor as the RAD IDE. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From francisgavila at yahoo.com Fri Dec 5 17:26:40 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Fri, 5 Dec 2003 17:26:40 -0500 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: Fuzzyman wrote in message <8089854e.0312050419.2cf36e34 at posting.google.com>... >Right - because if I do something like : > >a = 4 >b = a >a = 5 >print b > >It prints 4... not 5. >In other words - the line b = a creates a name pointing to the object >4, rather than a name pointing to the contents of a..... Correct, but it's not so much the contents of 'a', but the thing that 'a' points to. Thinking of names as having a "contents" is bound to lead to confusion later. In any case, as far as 'b' is concerned, there's nothing in the universe besides itself and the object it points to. It doesn't know anything about the existence of 'a'. Python sees what object the right side of the assignment operator points to, and then tells the names on the left side, "Hey, you! Point to this object!" Names are not objects, and names point only to objects, not to names. This doesn't mean that names aren't *things*: they certainly are, because objects can contain names. This is more natural than you might think, because you do it in language. When you say "chair", the sound points to the concept "chair". The sound isn't a chair, nor does it contain a chair, but when someone else hears the sound, it evokes the same "chair" concept, and not the sound itself. However, the name is still a *thing* (you can speak it, put it in a book, etc.), even though its existence is transparent. >I think I see what you mean - since the object 4 is immutable...... >the line a = 5 destroys the old name a and creates a new one pointing >to object 5, rather than changing what the name a is pointing to. It doesn't create or destroy the old name: it just makes it point to something else. Names are created by '=' if the name didn't exist before, and destroyed by 'del' or by going out of scope. >Hmmmmmm... thanks......... No problem. I think you've got the hang of things. -- Francis Avila From hjwidmaier at web.de Wed Dec 31 12:28:49 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Wed, 31 Dec 2003 18:28:49 +0100 Subject: canonical file access pattern? References: <874qvhkpm2.fsf@pobox.com> Message-ID: Am Wed, 31 Dec 2003 14:51:01 +0000 schrieb John J. Lee: > If that were true, why did exceptions get invented? If you don't need > to do something different in all those except: clauses, then don't put > them in. One thing I need is to create an informative and useful error message > As you know, the nice thing about exceptions is that you're > allowed to handle them in sensible places, so typical usage is like > this: [handling exceptions in the caller] > Shock, horror, where's the except IOError:, you ask?! It's in the > calling function, of course. Hmm. The farther away from the actual point of error you catch it, the harder it is to tell exactly what happened and to redo/work around it. > Also, if you want to catch both OSError and IOError, note that > EnvironmentError is their common base class. Good tip! I didn't know that before. Hans-Joachim Widmaier From bokr at oz.net Fri Dec 5 11:36:19 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 16:36:19 GMT Subject: ANN: Leo 4.1 beta 5: An outlining editor References: Message-ID: On Fri, 5 Dec 2003 08:54:53 -0600, "Edward K. Ream" wrote: [...] >-------------------------------------------------------------------- >Edward K. Ream email: edreamleo at charter.net Parsing ambiguity: Is that e-dream-leo or ed-ream-leo ? ;-) Regards, Bengt Richter From newsgroups at jhrothjr.com Thu Dec 11 08:34:34 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 11 Dec 2003 08:34:34 -0500 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: "Fernando Perez" wrote in message news:br8nop$t97$1 at peabody.colorado.edu... > Allenabethea wrote: > > > Jython is 100% java coded python. > > Python objects work with javacompilers and Virtual machines. > > > > I am a hobby programmer so the technical reasons are probably beyond me... > > Why is python incompatible with .net? Why can't python be coded in C#? > > > > I see the the MONO project on linux/unix is advancing. .Net seems to be a > > juggernaut especially if programmers will be able to use their favorite(most > > productive) language to program in. (every language but python) > > > > I am a new python tinkerer. I love the language. But what is its future but > > as a legacy tool? > > > > allen > > Some who I suspect know a thing or two about python and .NET seem to disagree: > > http://primates.ximian.com/~miguel/activity-log.php This is real good news, but the fact that it's only at 0.1 makes me suspect that they might find some real issues later that will slow things down. But then, I'm old and cynical. John Roth > > Cheers, > > f From LittleDanEhren at yahoo.com Fri Dec 19 17:45:20 2003 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 19 Dec 2003 14:45:20 -0800 Subject: Newbie Question HELP! References: Message-ID: <711c7390.0312191445.53feebf@posting.google.com> "TyBriD" wrote in message news:... > hello guys i am new top programming and was told python is the best place to > start i so far understand variables ex: > print ("Fill In Below") > name = raw_input("Enter Your Name Please: ") > age = input("Enter Your Age Please: ") > print "Your Name Is", name > print "Your Age Is", age > > but i was wondering if there was a way to compile a EXE file to display the > print because this only seems to run in python shell, or is there a way to > create my own interface for my program in python thanks in advanced Somebody already answered your question, but just so you know, you don't need to put parenthases around what's after print. From newsgroups at jhrothjr.com Mon Dec 29 15:33:08 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Dec 2003 15:33:08 -0500 Subject: [Mailman-Developers] python is slow References: <3FE20578.7060402@gmx.at> <1072458360.4458.13.camel@anthem> Message-ID: "Michael Hudson" wrote in message news:m3llovqsxo.fsf at pc150.maths.bris.ac.uk... > "John Roth" writes: > > > In interpreting it, note that the Python was 1.5.2, which is quite a > > bit slower than the current 2.3 release. > > You sure about that? I'd guess that 1.5.2 was faster for some things, > slower for others compared to 2.3. You're probably right. Now that you mention it, I believe I've heard that 2.0 was the big slowdown, and then it's improved from there. 2.3, for example, is quite a bit faster than 2.2. John Roth > > Cheers, > mwh > > -- > "declare"? my bogometer indicates that you're really programming > in some other language and trying to force Common Lisp into your > mindset. this won't work. -- Erik Naggum, comp.lang.lisp From mwilson at the-wire.com Sun Dec 21 19:37:56 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 21 Dec 2003 19:37:56 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: In article , Steve Lamb wrote: >On 2003-12-21, Jarek Zgoda wrote: >> Jp Calderone pisze: >>> A function must return to have a return value. When does sys.exit() >>> return? > >> Something, that is of type NoneType. > > He didn't say what, he said when. Can anyone show a program that will >evaluate the return of sys.exit() and successfully parse it? =D Cute. Every function returns something.. None if nothing else.. except for functions that don't return. def v(): raise ValueError would be another variation on the theme. Regards. Mel. From bjorn.pettersen at comcast.net Thu Dec 25 06:17:47 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Thu, 25 Dec 2003 05:17:47 -0600 Subject: 2.3 list reverse() bug? References: Message-ID: cartermark46 at ukmail.com (Mark Carter) wrote in news:d3c9c04.0312250303.561b119d at posting.google.com: > I did this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > >>>> d1 = [1,2] >>>> d2 = d1 >>>> d2.reverse() >>>> print d1 #note: d1, not d2 > [2, 1] >>>> > > Surely that can't be right: d1 should still be [1,2]. If it is > "right", then I expect that many people are in for a suprise. Nah, not really. Why do you expect d2 = d1 to make a copy of d1 before assigning it to d2? (and if d1 contained nested lists, should it copy them too or just make references to them?) In Python, assignment binds a name on the left hand side, to the object on the right hand side... period. There is no magic going on behind the scenes. In your example d2 and d1 are two names for the _same_ object, [1,2], which means that any way you mutate the object through one name will be visible when the object is accessed through the the other name. There is a module called copy that let you get the semantics that you're looking for. I've never used it in my 6+ years of Python programming, since it normally indicates the presence of flawed logic . -- bjorn From r_sridhar at users.sf.net Tue Dec 16 07:41:58 2003 From: r_sridhar at users.sf.net (Sridhar R) Date: 16 Dec 2003 04:41:58 -0800 Subject: What GUI toolkit looks the best? References: <7xllpj81wv.fsf@ruckus.brouhaha.com> Message-ID: <2d54dd6.0312160441.3c9120be@posting.google.com> Well. I personally prefer PyGTK2. The reasons are ... 1. Great GTK/GNOME integration - Looks great under GNU/Linux and any system with GNOME desktop. 2. Looks even great under Windows (also XP). If you don't believe check out the Gtk-Wimp project. http://gtk-wimp.sourceforge.net/ GTK-Wimp is a Windows GTK theme that mimicks a Windows native look and feel by delegating the drawing to the Windows API, resulting in near perfect desktop integration, especially when you run XP. GTK-Wimp respects your system font and colors. And see the screenshots here http://gtk-wimp.sourceforge.net/screenshots/ Somebody in the thread said that Gtk code is lengthier. But in any project, GUI contributes only few lines of code. So this doesn't matters anyway. Also PyGtk(GTK) API is nice for programmers. I am not happy with wxPython's (wxWindows either) API. Also, for me the wxPython demo application crashed in (Slackware) GNU/Linux. From mwh at python.net Tue Dec 9 09:30:25 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 9 Dec 2003 14:30:25 GMT Subject: Speed: bytecode vz C API calls References: Message-ID: "Terry Reedy" writes: > "Jacek Generowicz" wrote in message > news:tyf7k171jbq.fsf at pcepsft001.cern.ch... > > I have a program in which I make very good use of a memoizer: > > > > def memoize(callable): > > cache = {} > > def proxy(*args): > > try: return cache[args] > > except KeyError: return cache.setdefault(args, callable(*args)) > > return proxy > ... > > I've got to the stage where my program is still not fast enough, and > > calls to the memoizer proxy are topping profiler output table. So I > > thought I'd try to see whether I can speed it up by recoding it in C. > > Have you tried psyco on above? Or rather, on the proxies? I doubt that would help -- the largest overhead is likely the function call, and I think calling across the pysco/python boundary is expensive. Cheers, mwh -- Screaming 14-year-old boys attempting to prove to each other that they are more 3133t than j00. -- Reason #8 for quitting slashdot today, from http://www.cs.washington.edu/homes/klee/misc/slashdot.html From bokr at oz.net Sun Dec 21 14:01:45 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Dec 2003 19:01:45 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 21 Dec 2003 12:02:04 -0500, "Terry Reedy" wrote: > >"Bengt Richter" wrote in message >news:bs1lov$3vu$0 at 216.39.172.122... >> That's useful, but IMO not the optimal syntax, >because cache here is really not >> being used as a parameter. That's why I would >like a way to bind locals similarly >> without being part of the calling signature. >E.g., >> >> def _tento(n)( >> # preset bindings evaluated here at def-time >> cache={} >> ): >> try: >> return cache[n] >> except KeyError: >> answer = cache[n] = 10L ** n >> return answer > >I have also thought of using a ';' as in >def _tento(n; cache = {}): > [etc] > >to indicate a def-time initialized non-parameter. > That's nice and concise. I wonder how best to use that for generators. I.e., the current parameter list of a generator is effectively gen(; current_stuff): ... where the first part could be interpreted as optional parameters of .next(). Regards, Bengt Richter From kahanpaa at gstar.astro.helsinki.fi Tue Dec 16 11:18:20 2003 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 16 Dec 2003 16:18:20 GMT Subject: Python in a spreadsheet References: <3064b51d.0312151318.277c8c06@posting.google.com> Message-ID: Thomas Guettler wrote: > Depending on your problem, I would suggest to use > XML instead. I think it is more stable to export > the office file to XML, process it with your script, > and import it again. The remote procedure call solutions > (COM, pyUNO) don't scale well. Note that the OpenOffice.org native format (sx? files) are nothing but zipped XML files: [kahanpaa at nosuchaddress ~/diptera]$ unzip -l brachycera.sxc Archive: brachycera.sxc Length Date Time Name -------- ---- ---- ---- 28 12-09-03 17:37 mimetype 281295 12-09-03 17:37 content.xml 29859 12-09-03 17:37 styles.xml 1007 12-09-03 17:37 meta.xml 8779 12-09-03 17:37 settings.xml 750 12-09-03 17:37 META-INF/manifest.xml -------- ------- 321718 6 files You could manipulate them directly using Python's XML facilities. Jere -- Lord, make my words as sweet as honey, for one day I may have to eat them - Daryl Benson From hwlgw at hotmail.com Sat Dec 27 06:33:48 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 03:33:48 -0800 Subject: Project dream References: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> Message-ID: > [Paul Rubin] > A CVS-like system for email... > ...It should be able to create a single > tarball or zipfile that you download, and accept a single tarball or > zipfile when you upload > > I've been wanting for a while to write something like this. Everyone > I've mentioned it to wants to use it. I'm amazed it doesn't exist > already, at least in any well-known form. Indeed an interesting project! And include newsgroups like comp.lang.python too! For another project I finally got the "upload zip", "unzip", "base64encode" etc. thing right: users can send a .zip file via a HTML INPUT file="type" and the CGI script unzips it, and can send zipped parts to the next page, etc. Would like to warn you: it seems easy but it took me some retries to get it right. If you are interested I can put the code somewhere on the net. From jetmano1 at yahoo.com Fri Dec 5 00:54:53 2003 From: jetmano1 at yahoo.com (Jethro Ma) Date: Fri, 05 Dec 2003 05:54:53 -0000 Subject: Embedding Python in C++ Message-ID: Here is what I have: ... pName = PyString_FromString("btdownloadheadless"); pargs = PyString_FromString("argv = 'foo.torrent'"); PyImport = PyImport_ImportModuleEx ("btdownloadheadless",pargs, pargs, 0); ... I have a feeling my pargs is wrong. How do I make it so that it is the equivalent of typing btdownloadheadless.py --responsefile=foo.torrent in the command line From bignose-hates-spam at and-benfinney-does-too.id.au Mon Dec 15 18:34:39 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 16 Dec 2003 10:24:39 +1050 Subject: Beginner question - How to effectively pass a large list References: Message-ID: On Mon, 15 Dec 2003 15:14:48 +0800, J.R. wrote: > The python can only support passing value in function call (right?) Wrong. Function parameters in Python are always passed by reference, not by value. The local function parameter gets a binding to the same object that was passed, so there are not two copies of the object in memory. Of course, because of the way that Python treats assignment, you can then change that local parameter within the function and it will re-bind to the new value, without altering the original value passed. -- \ "I went to a fancy French restaurant called 'D?j? Vu'. The head | `\ waiter said, 'Don't I know you?'" -- Steven Wright | _o__) | Ben Finney From tjreedy at udel.edu Tue Dec 30 12:43:13 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 12:43:13 -0500 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: "David M. Wilson" wrote in message news:99dce321.0312300655.14c5a8db at posting.google.com... > Further to my last post here, I was playing some more with building a > regex object and storing it somewhere for use internally by a > function. I'm not happy with any of my solutions: > # I don't like this, but the fact that you can modify the procedure's > # function via a named argument seems neat in a hacky sort of way. > > def uses_default_parm_yuck(x, r = re.compile("...")): > pass I default args less bothersome than some people. The only problem for me is that a caller may accidentally give nonesense second param. If this can silently give a junk answer, this is not very acceptable. In this case, random objects without a match() method would raise an exception. > g = re.compile('...') Use _ to indicate 'private' or 'local-use-only' status. _hex = re.compile() > def uses_global_yuck(x): > global g > pass The global declaration is not needed for read-only access and is therefore misleading. So delete and just use _hex in the body. Python functions constantly use globals and builtins, both functions and other values, in read-only mode. So I see no problem with this standard Python idiom. > # This is horrible and probably slow. > > class is_hex: > def __init__(self): > self.r = re.compile('...') > > def __call__(self, x): > r = self.r > pass One should at least generalize this to re_matcher and pass specific re to init. OO purists might prefer this but I agree that it is overkill unless, possibly, one has lots of instances. OO was made for man, not man for OO purity. > is_hex = is_hex() is_hex = re_matcher(hex_re) > # This mucks up scoping so that your procedure can't access it's > # parent scope like it could normally. Funny, you just objected above to having a function access is parent scope for the re. > def is_hex(): > r = re.compile('...') > def is_hex(s): > return r.match(s) is not None > return is_hex > is_hex = is_hex() Same comment: generalize def re_matcher(some_re): r = re.compile(some_re) def is_some(s): return r.match(s) is not None return is_some is_hex = re_matcher(hex_re) I would use this in preverence to class version for making multiple matchers. I think closures are great as one-method instances (or as callable no-method instances, if one prefers). Terry J. Reedy From martin at v.loewis.de Sun Dec 7 12:43:39 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Dec 2003 18:43:39 +0100 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: allenabethea at aol.com (Allenabethea) writes: > Why is python incompatible with .net? Why can't python be coded in > C#? Who says that it cannot be coded in C#. It is a matter of fact that it currently isn't, but it would be possible to reimplement the Python interpreter in C# (instead of implementing it in C). As for generating MSIL byte codes: This is also possible, and has been demonstrated. It also has been demonstrated that an initial implementation is likely to be *very* slow. The question is whether a Python implementation for .NET would be CLS compliant (CLS == Common Language Specification). The existing implementation has shown that this is not possible without giving up parts of the Python semantics. > I am a new python tinkerer. I love the language. But what is its > future but as a legacy tool? No. Instead, most .NET users will find out that .NET is *not* a juggernaut, but restricted to C#, in practice. So Python might even survive .NET :-) That said: If you think the Python-.NET story should be a better one, feel free to contribute. Python is a volunteer effort, and without volunteers, there will be no progress. Before starting, please have a look at the excellent Python-for-.NET, which uses the native-code Python implementation to host .NET, giving Python programs full access to the framework. Regards, Martin From cpl.19.ghum at spamgourmet.com Wed Dec 3 14:36:55 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 3 Dec 2003 20:36:55 +0100 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> <153fa67.0311261206.648e73c6@posting.google.com> Message-ID: Kylotan, I use PyChecker with great joy together with scite. Scite is a free editor based on scintilla. I put PyChecker on Ctrl+3, so I only press Ctrl+3, PyChecker runs from a batch on the currently edited file, all the output is put in a window beside my prgramfile. With double clicking on errors & warnings scite skips to that line. VERY helpfull Harald From skip at pobox.com Sat Dec 20 15:13:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 14:13:13 -0600 Subject: Unicode from Web to MySQL In-Reply-To: <3FE4796D.1010609@rfa.org> References: <3FE47726.90504@rfa.org> <3FE4796D.1010609@rfa.org> Message-ID: <16356.44377.466955.783810@montanaro.dyndns.org> Bill> Note that I am able to do create Unicode data and insert it with a Bill> carefully controlled unicode string Bill> data = u"Make \u0633\u0644\u0627\u0645, not war" Bill> c.execute ( INSERT INTO junk (junklet) VALUES ('%s') ''' % Bill> data.encode('utf-8','ignore') Bill> but this won't work with what I find on the Web. I suspect you either don't know the encoding of the data you find on the web. Once you know that, you can convert it to unicode, then encode that as utf-8, placing the result into the database. You should know the encoding of the data from the Content-Type header. If that's missing or incorrect, you should be able to make a reasonable guess based upon the non-ASCII patterns you find in the data. Skip From alan.gauld at btinternet.com Sun Dec 28 04:06:52 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Dec 2003 09:06:52 GMT Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> <3fee1d7d.350511859@news.blueyonder.co.uk> <3fee224a.65125244@news.iprimus.ca> Message-ID: <3fee99e9.382363329@news.blueyonder.co.uk> On Sun, 28 Dec 2003 00:23:14 GMT, MidasOneTwo at hotmail.nospam.com (Midas) wrote: > Part 1) Create 10 new assorted objects > Part 2) Link up the objects, somehow, so they can communicate with each other directly, > like parts of an electrical circuit. Sounds like you need a list or dictionary full of objects. > Part 3) Call the first object, which calls another, etc. like an electrical circuit. That's a pretty unusual electrical circuit, but I think I see what you mean... You want a calling sequence that can be changed. That could be another list or dictionary mapping inputs to responses. > To change the circuit, I would only change part 2 and perhaps part 3. In which case to change the circuit you only need to change the calling sequences. > For example, ObjectX could have an input, for a string, and two outputs. > If the input is "TurnOnS", it calls ObjectY.Input3 > If the input is "TurnOnT", it calls ObjectZ.Input7 So far it looks more like a list of functions than a list of objects. > ObjectX would call either, ObjectY.Input3 or ObjectZ.Input7, > because it was connected that way in part 2. You can either hard code Object X or have object X hold the tewo lists I mentioned above. When you intialise ObjectX you need to pass in the data to populate the lists. The other, arguabluy more OO solution, would be to have the inputs as message objects which know which objects to call. Thus when you pass the "TurnOnS" message it has embedded within it a reference to ObjectY.Input3 and a method called doit() or somesuch. Then when object X receives the message it performs some sanity/security checks then X tells the message to doit(). Probably a better solution would be to have the message objects hold the sequence information but ObjectX hold the objects. X then applies the sequence to its own objects. That way when a message needs a new sequence you make the change to the message that is affected. This encapsulates the change in a much more logical way. Lots of possibilities. Few of them actually requiring that you pass around object and method names explicitly. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From mark at mceahern.com Wed Dec 10 07:48:30 2003 From: mark at mceahern.com (Mark McEahern) Date: Wed, 10 Dec 2003 06:48:30 -0600 Subject: What is the "self" name always referring to...? In-Reply-To: <9b849915.0312092231.1a843c02@posting.google.com> References: <9b849915.0312092231.1a843c02@posting.google.com> Message-ID: <1071060509.11531.82.camel@dev.internal> On Wed, 2003-12-10 at 00:31, Todd Gardner wrote: > Is there something special about the word "self" or did Mr. Guido van > Rossum just decide to us the word arbitrarily? Yes, there is something special about "self": It's what most people use when writing Python to refer to the current instance within a method of a class. You can spell "the current instance" however you want: class Foo: def __init__(iLikeToBeARebelWithoutACause): iLikeToBeARebelWithoutACause.bar = True f = Foo() print f.bar But *should* you? Cheers, // m From fumanchu at amor.org Mon Dec 1 12:29:16 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 1 Dec 2003 09:29:16 -0800 Subject: Python for web ? Message-ID: Jay O'Connor wrote: > Same here. I do the backend programming and usually give the > designer a > page (See these marks? Don't touch them, the rest of the page is > yours) Works well because I'm *not* a graphices designer and > I get much > better results when I make it work and I give it to a friend > to make it look good. Heh. I'm trying to move into the opposite situation: I do the design and give a backend programmer a page (See these marks? Touch them and them only; the rest of the page is mine). Works well because the design is not then driven by someone who's not a designer. :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 16 13:31:31 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 16 Dec 2003 19:31:31 +0100 Subject: continue and break frustration References: Message-ID: Glen Wheeler: >a performance intensive program in python. > The problem I'm having is I want to use break and continue to get >out from more than one level of loop. If I set a variable and then >check it my program will take too much of a performance hit. > Are there any alternatives people can think of? Exception handling perhaps. Or old fashioned if-then-else, while etc. But if the application is performance critical to the extent of one variable set-and-test, I doubt that Python is the best choice. -- Ren? Pijlman From http Mon Dec 29 18:34:03 2003 From: http (Paul Rubin) Date: 29 Dec 2003 15:34:03 -0800 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> Message-ID: <7x3cb3mc5w.fsf@ruckus.brouhaha.com> engsolnom at ipns.com writes: > After looking at the suggestions for a ishexdigit method, (thanks > again), I decided on the following, partly because I don't have to > import string, and I believe it's pretty readable by Python newbies, > which we (including myself) have at work: > > def ishexdigit(sx): > ix = 0 > for cx in sx: > ix += 1 > if not cx in '0123456789abcdefABCDEF': return 0 > if ix % 2 == 0: return 1 > else: return 'Extra nibble' Some remarks: 1) I think the name is a misnomer: "ishexdigit" should test just one digit, not a multi-digit string. This function should be called "ishexnumber" instead. 2) I'm not sure why you return 'extra nibble' if there's an odd number of digits. Isn't '123' a perfectly good hex number (= 291 decimal)? 3) Even if you do want to check that the length is odd, you don't need to count the chars in the loop: def ishexnumber(sx): for cx in sx: if not cx in '0123456789abcdefABCDEF': return 0 if len(sx) % 2 == 0: return 1 return 'Extra nibble' (the final 'else' is not needed) 4) You could also use a regular expression to test for hex digits: def ishexnumber(sx): import re if not re.match('[0123456789abcdefABCDEF]*$', sx): return 0 if len(sx) % 2 == 0: return 1 return 'Extra nibble' 5) If you want the number of bytes to be even because the hex string is supposed to represent a character string, and you're going to do the conversion next, there's already a library function for that: import binascii s = binascii.unhexlify(sx) 6) If you want it to be a number but still need the digit count to be even for some reason, then checking for the special value 'Extra nibble' is messy. It's usually better to raise an exception instead: def ishexnumber(sx): for cx in sx: if not cx in '0123456789abcdefABCDEF': return 0 if len(sx) % 2 != 0: raise ValueError, 'Extra nibble in hex string' return 1 The caller then has to catch the exception, of course. 7) If you want to just check that the hex string represents an integer, possibly the most robust way is: def ishexnumber(sx): try: n = int(sx, 16) except ValueError: return 0 return 1 Note this will fail for hex strings are too long to fit in a short int. From db3l at fitlinxx.com Tue Dec 30 19:00:21 2003 From: db3l at fitlinxx.com (David Bolen) Date: 30 Dec 2003 19:00:21 -0500 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> <3ff0a90e.517312596@news.blueyonder.co.uk> Message-ID: alan.gauld at btinternet.com (Alan Gauld) writes: > No, there are several things that you can do using the Win32 API > that you can't do with MFC. Also winall doesn't expose all of MFC > (last time I looked, although it does do the 80%(95%!) that you > need most. > > This is especially true when you start to get into controlling > strange peripheral devices etc. MFC is great for standard > business type apps but it is not 100% complete win32 coverage. This was also addressed in some of the other responses, but I had to mention that I found it interesting that it would appear that your past experience yields a perspective that Windows programming is MFC, with the Win32 API being a really low layer interface. Anything outside of MFC support is a "strange peripheral device"? :-) >From my perspective, MFC is a particular high level GUI package that you might or might not use, but the Win32 API is definitely the way to program for Windows. I've rarely ended up using MFC (and never since moving to Python/wxPython), but I did and still do use the Win32 API all of the time (whether from Python or other languages). True, Win32 is lower level than MFC, but to me, it's the normal level, rather than a low level (low level on Windows would be the kernel or device driver interfaces). And since I can get to the Win32 API in general (even if not wrapped with win32all, there's the older calldll and the newer ctypes), I always figured there was very little that that Python couldn't do under Windows if I needed it. But again, that's thinking of the Win32 API and ignoring MFC entirely. Anyway, I just found it interesting how past experience (and the sorts of apps we've probably worked on) can bias a viewpoint to what it means to program for a specific system. For the obligatory in-context comment, for me, I cover true standard Windows apps with Python+wxPython+installer+InnoSetup. -- David From marklists at mceahern.com Wed Dec 10 07:37:31 2003 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 10 Dec 2003 06:37:31 -0600 Subject: About the use of **args In-Reply-To: References: Message-ID: <1071059848.11531.78.camel@dev.internal> On Wed, 2003-12-10 at 03:24, Graham Ashton wrote: > [snip] > I've not run that so it may have syntax errors. It should illustrate the > principle though; you can use attributes directly until you want to take > actions when you set them. Then you can make the attribute "private" and > replace it with a property that access the real attribute, and does > whatever else you want to do when it's accessed. A couple of points on Graham's example: 1. You have to subclass from object in order to use property. 2. When Graham nominalizes private, he means that you can still access the attribute variable directly--and that's by design. See example below. Cheers, // m #!/usr/bin/env python class Shoe: def __init__(self): self._size = None def getSize(self): print "In getSize..." return self._size def setSize(self, size): print "In setSize..." self._size = size size = property(getSize, setSize) class Shoe2(object): def __init__(self): self._size = None def getSize(self): print "In getSize..." return self._size def setSize(self, size): print "In setSize..." self._size = size size = property(getSize, setSize) s = Shoe() # Since we haven't subclassed from object, the property descriptor # doesn't work; notice that setSize() isn't getting called... s.size = 1 print s.size # We can still access the "private" member variable. In Python, # private is merely a convention. print s._size # Now that we've subclassed from object, our get/set methods are # called. s2 = Shoe2() s2.size = 1 print s2.size # And we can still access the "private" member variable. print s2._size From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 31 05:37:10 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 31 Dec 2003 11:37:10 +0100 Subject: Try except - bug? References: <104c369a.0312300851.4f23759e@posting.google.com> <1ne3vvobhp2u6mqar4khk84h64hcmu8h1o@4ax.com> <104c369a.0312301901.3e4f8207@posting.google.com> Message-ID: Askari: >OSError: [Errno 2] No such file or directory: '' If I'm not mistaken this is another exception!? >at line 355 you have : "fileDest.close()" No, line 355 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: #afficher confirmation >and at line 363 you have : "os.remove(destination)" No, line 363 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: pass >What is your version of python? (I have 2.3.2) I use UltraEdit 8.0 on Windows XP to count the line numbers. -- Ren? Pijlman From duncan at NOSPAMrcp.co.uk Fri Dec 12 09:19:08 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Dec 2003 14:19:08 +0000 (UTC) Subject: Function application optimization. References: Message-ID: "John Roth" wrote in news:vtjhmt7idn3k6b at news.supernews.com: > Building on a couple of other responses: > > Untested code: > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > results = [] > for function, arguement in zip(fncs, args): > results.append(function(arguement)) > > Notice the use of zip() to put the two lists together. > I haven't timed it, but removing an extra layer of > function call has got to be faster. Likewise, zip > and tuple unpacking is most likely going to be > faster than indexing every time through the loop. > The append, on the other hand, might slow things > down a bit. Yes, getting rid of the append does indeed speed things up. On the same system as I posted timings for the list comprehension, the fastest way I've found so far is to get rid of the appends by preallocating the list, and to go for the plain old simple technique of writing a for loop out explicitly. Using 'enumerate' to avoid the lookup on one of the input lists is nearly as fast, but not quite. >>> setup = """import itertools def fn1(a): pass fns = [fn1] * 1000 args = [0] * 1000 """ >>> stmt1 = """result = args[:] for i in range(len(fns)): result[i] = fns[i](args[i]) """ >>> min(timeit.Timer(stmt1, setup).repeat(3,1000)) 2.9747384094916924 >>> stmt3 = "results = map(lambda f,a: f(a), fns, args)" >>> min(timeit.Timer(stmt3, setup).repeat(3,1000)) 3.3257092731055309 >>> -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From __peter__ at web.de Fri Dec 5 12:49:08 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Dec 2003 18:49:08 +0100 Subject: Turning f(callback) into a generator References: <3FD0BC51.597C3E95@hotmail.com> Message-ID: Alan Kennedy wrote: > Peter, you may find the following message from Stephen Taschuk > interesting. It is an approach to the producer/consumer problem, > through the use of coroutines. Only the bottom half of his post will > be of interest. The top half relates to another question I was asking > him at the time. > > http://groups.google.com/groups?selm=mailman.1054317657.5272.python-list%40python.org&rnum=8 > > I think it might be something closer to what you're looking for. Very interesting indeed, thanks. At first glance I think it will not solve the particular problem, as all participants (read/write/consumer/producer) are generators, which is not an option here, as I want to "tunnel" data from a callback inside code that assumes it is calling a normal function. On the other hand, although I always thought of the callback as the producer, there might be a way to put the *dispatcher* into the callback - and then bingo. So I'll definitely have a closer look at this promising approach. Peter From jacobsmail at postmark.net Mon Dec 29 17:14:43 2003 From: jacobsmail at postmark.net (Jacob H) Date: 29 Dec 2003 14:14:43 -0800 Subject: Graceful failures Message-ID: <85b54e91.0312291414.6e61e535@posting.google.com> Hello all, I'm nearing the completion of my first graphical console game and my thoughts have turned to the subject of gracefully handling runtime errors. During development I like to not handle exceptions, so that program execution will halt and I can immediately read the traceback to see what's up. Once the bugs are more or less worked out, I have a system ready wherein any exceptions are caught and an attempt is made to write the traceback object to a log file. This system suits me for the upcoming testing phase - if my beta testers do anything to make the game crash, I can read about the error and its causes in the log later. But what about the eventual production version that I distribute to the public? My current understanding is that there's always a chance a computer program can fail in some way at runtime, disk access being an example. Suppose the startup code for my game fails to load one of the images from disk. I can't think of any reasonable way to rescue things, and under such conditions I would prefer that the program gracefully exits. The aforementioned traceback logging is fine for me as the developer, but useless to the end user of the production version. So - I'm real curious - what are the canonical ways that a computer application should gracefully fail? I'm somewhat reluctant to write a bunch of code for pretty windows that pop up with some message to the effect of, "internal error, game exiting." My main reservation here is it doesn't seem it can be done cross platform, and since my game is in a graphical console there's no place for stdout to write. However, if this is the best way to go about error handling, I'm willing to write the code. And I would appreciate advice about how to handle the cross platform problem. :) Thanks in advance for any help! Jake From oren-py-l at hishome.net Sat Dec 20 08:28:17 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 20 Dec 2003 08:28:17 -0500 Subject: Threads with Python 2.2.2 on Red Hat 9.0 In-Reply-To: References: Message-ID: <20031220132817.GD99675@hishome.net> On Fri, Dec 19, 2003 at 12:27:50AM +0000, Neil Hodgson wrote: > I am seeing some problems with threads on Red Hat Linux 9.0. With no > LD_ASSUME_KERNEL environment variable set, a large proportion, possibly > 20%, of threads do not run. They are created OK and their __init__ which > includes a setDaemon(1) is successful. start() is called on the thread > object and a message successfully displayed after the start() call. But > no message is produced by the thread's run() method. The thread class is > derived directly from threading.Thread and in its __init__ calls > threading.Thread.__init__(self) before calling self.setDaemon(1). Can you post the code that causes this problem? Preferably, it should be the smallest program that consistently displays different behavior with and without setting LD_ASSUME_KERNEL. The regression tests for threads pass fine on RH9. Oren From cpl.19.ghum at spamgourmet.com Sun Dec 21 09:08:41 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 21 Dec 2003 15:08:41 +0100 Subject: web programming: experiences with non-zope frameworks? References: Message-ID: Brendan, I just wanted to explain my experience using a rather special Web- Toolkit. It's not really a framework - even if Quixote http://www.quixote.ca/ is called that. Quixote was created by employees of mems-exchange - as much as I understand a virtually connected collaboration of chip producing facilities (I'm not connected to them in any way besides using Quixote) I had to do a mid-sized web project early this year, I fell in love with Python around November last year. This falling in love ... was after a quite long marriage with PHP. And I really thought PHP was a sexy thing when I started that relationship. PHP was a really sexy thing, good for a great nightout and a good time. But --- a marriage with a language asks more than being sexy from a language. Yeah, it was great, being a Web-Virgin to have the first time dynamic webcreation with PHP quickly. But I learned that that is not enough for a language to have a stable relationship. So I thoroughly searched the various approches to Python Web Working - and got stuck with Quixote. Why? It's really not suited for fancy webworking, flashing here and there. But my applications are rather "database interfaces" than flashing playgrounds. And that's where Quixote excells - programming the web. The website as a programm - the URL as index into the Python namespace. It was a tough learning, though. I just had started my relationship with Python, was just getting familiar with what is called "namespace" - and now that was the basis for webworking. BUT... Quixote is very very elegant. I could read the entire source code in a matter of 2 to 3 hours. And after four weeks I integrated speedups and even was able to isolate bugs in mod_scgi - it's a great game, once you get used to it. My application deals with "getting stuff from Office into a database and publishing that database contents to the web" In the end, only a very very small number of Python code lines - what makes ground for a stable marriage, 'cause supporting a small code base is WAY easier. Harald From klappnase at web.de Tue Dec 9 12:55:03 2003 From: klappnase at web.de (klappnase) Date: 9 Dec 2003 09:55:03 -0800 Subject: drag-and-drop GUI interface builder for Tkinter? References: Message-ID: "John Benson" wrote in message news:... > I was looking at the Scriptics/Tcl website and followed a link to a Tk GUI > builder called Gypsy. I'm just curious to know if there's any Tk GUI builder > utility available to me in the Python environment. Try Page: Regards Michael From nid_oizo at yahoo.com_remove_the_ Wed Dec 3 17:59:08 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 03 Dec 2003 17:59:08 -0500 Subject: How to know a system command doesn't exist Message-ID: <0Vtzb.114323$PD3.5798298@nnrp1.uunet.ca> Hi, How can we know when using popen if the process returned 1 *or* the requested command is simply not found? I'm using latest ActivePython on Windows. Thx Nicolas From fumanchu at amor.org Fri Dec 5 12:33:08 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 5 Dec 2003 09:33:08 -0800 Subject: Threading - Why Not Lock Objects Rather than lock the interpreter Message-ID: Fuzzyman wrote: > Looking at threading code it seems that the Global Interpreter Lock is > a bit of a 'brute force' way of preventing two threads attempting to > access sensitive objects simultaneously.... > > Why not have a new type of object with a 'lock' facility... if an > object is locked then any thread trying to access the object other > than the one obtaining the lock is blocked until the lock is > released..... rather than blocking *all* threads until one thread has > finished with the object..... > > It could be implemented as a new attribute of existing objects... or > new types of objects..... You mean like an RLock? acquire( [blocking = 1]) Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. I use this for dictionaries, where I don't want it modified while another thread is iterating over it: import threading class UnitCollection(dict): _mutex = None def __init__(self): self._mutex = threading.RLock() def acquire(self): self._mutex.acquire(True) def release(self): self._mutex.release() Robert Brewer MIS Amor Ministries fumanchu at amor.org From hjwidmaier at web.de Sat Dec 27 09:24:04 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Sat, 27 Dec 2003 15:24:04 +0100 Subject: canonical file access pattern? Message-ID: Recently, there was mentioned how someone who had understood Python's error handling would write the "open and read file with error handling" idiom. If I remember correctly, it went like this: try: f = file(filename, op) except IOError, e: # Handle exception else: # Use the file f.close() I don't think that's sufficient. First of all, opening a file is only part of the job--reading and writing can go wrong too, and these are not handled by the above code. Then I've seen OSError as well as IOError raised occassionaly. Seems like I have do this, then: try: f = file(filename, op) except (OSError, IOError), e: # Handle open() error else: try: # read/write to the file f.close() # flushes write buffers, so can fail, too except (OSError, IOError), e: # Handle read/write errors Is it really so wrong, then, to fold the read/write operations and close() into the first try suite and handle all those errors in one go? I'd just like to have a definitive pattern that I can stick to that is considered bullet-proof. Hans-Joachim Widmaier From jochen at helferlein.net Sat Dec 13 06:06:07 2003 From: jochen at helferlein.net (Jochen Wersdoerfer) Date: 13 Dec 2003 11:06:07 GMT Subject: beginner python cgi question References: Message-ID: <3fdaf29f$0$17571$9b4e6d93@newsread4.arcor-online.net> +--[ Brandon Boles ]---[ email at nowhere.foo ] | ...snip... | fields=cgi.FieldStorage() | if (fields.has_key("name") and fields.has_key("emailaddr")): | SenderName=fields["name"].value | Address=fields["address"].value | City=fields["city"].value | State=fields["state"].value | ...snip... | | I think what the problem is that if my form does not have one of the | fields (except 'name' and 'emailaddr') with data in it, I get this error. | What is the best way to fix this? Getting a default value, if "address" is not set: Address = fields.get("address", "n/a") jochen From borcis at users.ch Mon Dec 22 09:58:33 2003 From: borcis at users.ch (Borcis) Date: Mon, 22 Dec 2003 15:58:33 +0100 Subject: Python, Jython, Pypy, etc - and python standard lexemes References: <3FE703B8.2030108@users.ch> Message-ID: <3FE70699.9070404@users.ch> > > Suppose you want to hook a CPython process and a JPython process > together, while minimizing "C2J" impedance. > >...devise a lexical format, > made to save communicating py processes, > better than 50% over transmitting py source... Not to forget "decompyle", a beautiful effort, towards the demonstration that *pure* compiled cpython *bytecode* contains eg 99 % of source. Aren't we seeing that Saddam's surrender shows, George W. Bush would have been at no risk, had he upheld the challenge of single combat while requiring the weapon to be fair russian roulette ? From alan.gauld at btinternet.com Sat Dec 13 03:47:01 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Dec 2003 08:47:01 GMT Subject: Python code to replace shell scripts References: <3fd9832d.385255327@news.blueyonder.co.uk> Message-ID: <3fdad096.470669617@news.blueyonder.co.uk> On 12 Dec 2003 20:17:04 GMT, William Park wrote: > > often execution time. Python provides a different approach that is > > generally better where the solution must be repeated often or where no > > suitable set of commands already exists. > > That is true, until you learn and program in shell. Well I've been programming Bourne and Korn shells for about 15 years now. But I still pick python for anything that needs a GUI or has to run as a daemon or does heavy network calls. I'd also use Python if I had to write a Web Browser or Word Processor or Programming/Test environment. In fact anything that needs more than a few hundred lines of code. Shell is great for what its good at but orders of magnitude slower and more resource hungry than Python for complex tasks. Just think about how many processes get launched, the inefficient text parsing, the nested shells etc. And as for data structure support! For sys admin type tasks, Shell is great, for applications its a forced fit. Alan g Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From John_Dutcher at urmc.rochester.edu Tue Dec 2 13:40:04 2003 From: John_Dutcher at urmc.rochester.edu (John F Dutcher) Date: 2 Dec 2003 10:40:04 -0800 Subject: import of 'string' fails in CGI-BIN script...but works in IDLE Message-ID: <2c82369d.0312021040.2f6fd8ca@posting.google.com> Having 'cloned' an existing python script that imports 'string' and uses "string.rstrip()" without incident... I am at a loss to explain why the new 'cloned' script (brief sample below) continually errors with: NameError: global name 'string' is not defined args = ("global name 'string' is not defined",) when run from the server CGI-BIN. If the same script is run in 'IDLE' it works with no problem. Yet, the "import urllib, string" statement is clearly present in the script. I am running Python 2.3.1 on Win 95, using XITAMI as the server. Troublesome script follows: #!c:\Python\python.exe import cgitb; cgitb.enable() import traceback, sys, os, cgi import urllib, string sys.stderr = sys.stdout form = cgi.FieldStorage() def writeHTML(rec): print "Content-Type: text/html" print print '''


''' print ''' ''' cycle = 1 drptr = 7 for x in range(10): uvalue = string.rstrip(rec[drptr]) <-----(** failure occurs here) if not ((cycle % 2) == 0): print '''''' cycle = cycle + 1 drptr = drptr + 1 print '''
''' else: print '''
''' print '''''' print '''Doctor Color Code
''' fileName = os.path. join("c:", "/xitami", "cgi-bin", "dsysmst.dat") #print 'Globals: ' + str(globals()) #print 'Locals: ' + str(locals()) f = open(fileName, 'rb') f.seek(-2690,2) recd = f.read(2690) if recd[3:7] == '0000': f.close() writeHTML(recd) sys.exit() else: print "Did not get utility record" f.close() sys.exit() From brett at python.org Thu Dec 4 14:05:34 2003 From: brett at python.org (Brett C.) Date: 4 Dec 2003 11:05:34 -0800 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: Message-ID: <8ab0589d.0312041105.29ea9f5f@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article , > Brett C. wrote: > > > >This is the twenty-eighth and twenty-ninth summaries written by Brett > >Cannon (does anyone even read this?). > > Hey, I've sent you enough corrections on your drafts, do I need to read > the final copy, too? ;-) =) Sorry, Aahz. You do deserve recognition as the second most prolific editor of the Summaries. But I really should just be thanking everyone who has ever helped me correct the darn thing. My adversity to proof-reading would probably lead to a sub-par Summary if other people were not willing to pick up my slack and tell me where I need to fix things. -Brett From gherzig at fmed.uba.ar Tue Dec 23 09:25:34 2003 From: gherzig at fmed.uba.ar (Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina) Date: Tue, 23 Dec 2003 11:25:34 -0300 Subject: list.index() like...but returning lists (for avoiding '0' on multiples hits) In-Reply-To: References: Message-ID: <200312231125.34232.gherzig@fmed.uba.ar> Um...my little brain came with something very much like Peter's example, without list comprehensions, but really close in terms of performance. The Francis example work well, and about 3 times faster for python 2.3, but i cant migrate now (im using 2.2 right now), and the extra parameter on index() trows exception "index() takes exactly one argument" I'm reading now the py.docs for that 'end' arg. Thank you, Peter and Francis!!!!! Gerardo El Lun 22 Dic 2003 21:07, Francis Avila escribi?: > John Roth wrote in message ... > > >But what does that have to do with the question? > > > >As far as I know, there is no such built-in for lists. > >You can do something similar with the "re" module > >for strings, but not for lists. > > > >John Roth > > More and more I am finding myself wishing for a neat way to *add* > functionality to a builtin. Not subclass a builtin, but add methods to the > builtin type. > > Like (the function does what the OP wants, btw): > >>> def indices(self, value): > > ... return [i for i,v in enumerate(self) if v == value] ------Francis response... > Oh well. Anyway, the following might be faster: > > def indices2(L, value): > res = [] > last = -1 #below, last+1 to prevent infinite loop. > try: > while True: > last = L.index(value, last+1) > res.append(last) > except ValueError: > return res -- Gerardo Herzig Departamento de Proyectos Especiales e Internet Facultad de Medicina U.B.A. From francisgavila at yahoo.com Sat Dec 13 19:28:58 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 13 Dec 2003 19:28:58 -0500 Subject: Shell quoting as part of the standard library? References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: David M. Wilson wrote in message <99dce321.0312131439.1612dee2 at posting.google.com>... >Hello fellow users! > >I've been using Python in a couple of different environments for a few >years now. I have quite often found that I have needed to deal with >filenames which may contain characters that confuse the UNIX shell >(space and double quote in particular). Isn't this the more general problem of escaping shell metachars in user-supplied input? Why don't you just let the shell deal with it? $ cat > do_st_evil #! /bin/sh echo "Gotcha!" ^D $ chmod u+x do_st_evil $ python Python 2.2.1 (#1, Apr 21 2002, 08:38:44) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information >>> import os >>> badness = '$(./do_st_evil)' >>> os.popen('echo '+badness).read() 'Gotcha!\n' >>> os.environ['shellvar'] = badness >>> os.popen('echo $shellvar').read() '$(./do_st_evil)\n' -- Francis Avila From blk at srasys.co.in Thu Dec 4 00:56:18 2003 From: blk at srasys.co.in (bala) Date: Thu, 4 Dec 2003 11:26:18 +0530 Subject: How to log the TestResult in the Excel or Notepad.... Message-ID: <001e01c3ba2b$563a3080$440210ac@Bala> Hi, After running the TestCase in UnitTest Module...I want to log the Result in Excel or Notepad(ie as a Text or xls) Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsgroups at jhrothjr.com Mon Dec 29 14:36:02 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Dec 2003 14:36:02 -0500 Subject: [Mailman-Developers] python is slow References: <3FE20578.7060402@gmx.at> <1072458360.4458.13.camel@anthem> Message-ID: "Bernhard Kuemel" wrote in message news:mailman.14.1072720549.8134.python-list at python.org... > > Barry Warsaw wrote: > > On Thu, 2003-12-18 at 14:52, Bernhard Kuemel wrote: > > > > Someone on mailman-developers at python.org then was interested in > "convincing evidence" that python is slower than perl. But as we > agree that such evidence is difficult to produce and does not > mean much I cited Eric Stephen Raymond's book "The art of unix > programming" where he says ... > > "In fact it's generally thought to be the least efficient and > slowest of the major scripting languages, a price it pays for > runtime type polymorphism." I originally quoted the whole > paragraph to be fair. I have some vague memories of a speed comparison done in conjunction with a programming problem or challenge. Python seemed to be pretty similar to Perl, and lots better than TCL. However, that's memory, and I don't have the reference to hand. Someone else might. The comparison included C++, Java and the rest of the usual suspects. I believe REXX was the real dog, though. John Roth From list.adam at twardoch.com Tue Dec 30 17:47:45 2003 From: list.adam at twardoch.com (Adam Twardoch) Date: Tue, 30 Dec 2003 23:47:45 +0100 Subject: OT: World's largest Python caught!:) Message-ID: http://www.wftv.com/news/2732086/detail.html Adam -- "My mother never saw the irony in calling me a son-of-a-bitch" [Jack Nicholson] From pedrosch at gazeta.pl Sun Dec 14 05:11:03 2003 From: pedrosch at gazeta.pl (Przemo Drochomirecki) Date: Sun, 14 Dec 2003 02:11:03 -0800 Subject: connection to samba server Message-ID: hi, does anyone knows how to connect to samba server (from windows) thx in adv. Przemo From jorgencederberg at hotmail.com Tue Dec 16 03:21:45 2003 From: jorgencederberg at hotmail.com (=?Big5?B?Sj9yZ2VuIENlZGVyYmVyZw==?=) Date: Tue, 16 Dec 2003 09:21:45 +0100 Subject: How to integrate python, vtk and C++ object ? In-Reply-To: References: Message-ID: Yi-Yu Chou wrote: > Dear all, > > I need to integrate python, vtk and my own C++ object. > Is it possible to do it by using python/C API ? > Or there is a more efficient way to do it. If you need prebuilt vtk DLL's you can find them at http://av.stanford.edu/~prabhu/download/vtk/win32/ (Python 2.3) or http://basic.astrian.net/godzilla/ (Python 2.1) Hope this helps Jorgen From paulo.pinto at cern.ch Tue Dec 16 06:22:10 2003 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Tue, 16 Dec 2003 12:22:10 +0100 Subject: Build classes/packages dinamicaly In-Reply-To: References: Message-ID: Thanks it is want I was looking for. However I still have a problem. I want to make the module available to the caller as if he did an import. For example, if I make the following call some_module.generate_module('dummy') Where some_module is the module that generates modules dinamicaly, and dummy is the name of the new module. I would like to be able to do dummy.something() after that call. I've discovered that if I do something like this globals()['dummy'] = module_instance_returned_by_new.module() It works, but it must be done at the same level I want to call dummy.something() and not from inside some_module. Because if I do it inside the module, globals() will be refering to the module globals and not to parent scope. Basically I would like to import the generated module to the module that is invoking generate_module() like an uplevel in Tcl. Is this possible? Cheers, Paulo Pinto Peter Otten wrote: > Paulo Pinto wrote: > > >>I have a package that generates classes from a >>set of XML files using exec. >> >>So far the classes appear in the global namespace. >> >>Is there any way to also create packages dinamicaly >>and add the classes to those packages? >> >>Thanks in advance, >>Paulo Pinto > > >>>>import types >>>>mymodule = types.ModuleType("mymodule") >>>>exec "def demo():\n\tprint 'hello from', __name__\n" in > > mymodule.__dict__ > >>>>mymodule.demo() > > hello from mymodule > > > Seems to work. I haven't used it myself, though. > > Peter > From peter at engcorp.com Fri Dec 5 12:49:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 12:49:22 -0500 Subject: Hopelessly Lost And Desperate Newbie References: <20031204092605.01786.00000161@mb-m20.aol.com> <6a6a43ab0ae25b7a0654dcad51867322@news.teranews.com> Message-ID: <3FD0C522.51D9C5A4@engcorp.com> Dennis Lee Bieber wrote: > > ; ensure until Year_Numering := Falso In_File. > ; end_File. > In_File. > ; be willush, Generic contd) Real := Numerict Data_Error | Constand > the bothe bothen then the involead, Put ver. > ; beyonding_Ptr_Ptr := Numeriction_1, 1, 1, Lang := Number, the > boundent_Error. ; end_File. > In_String a the bothe body would but, raint_Error | Constatil. > (8) Avoidable => Action_Id (see In Ada 83 Annex suite, whose > avoidance. [snip] > 7). > type => Nument_Error | Constraise, whose power hen those involve not > year the by del number has hank Kanji and, Pure untentatibility : > Curreclar, to using := Numer'Last. > (80); be would to unlikely. > (80); RM95-8. > task_Diging :=Function has hang annoth (3. > ; be withosent_Error. > ; end to unities be would to a the both, Get_In_File. > > Seems to be a lack of randomness in the sentence starts... I predict that if you train it on comp.lang.perl instead, the output will be executable code! -Peter From miki.tebeka at zoran.com Tue Dec 23 10:33:30 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 23 Dec 2003 07:33:30 -0800 Subject: OT: Why -g when compiling Message-ID: <4f0a9fdb.0312230733.736d124d@posting.google.com> Hello All, Can anyone tell me why when builiding Python gcc gets "-g" option as well as "-O3"? Apart from bigger objects what does "-g" gives a non-developer of Python? Thanks. Miki From spiffy at worldnet.att.net Wed Dec 10 18:04:26 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Wed, 10 Dec 2003 23:04:26 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <_DNBb.430596$0v4.20515253@bgtnsc04-news.ops.worldnet.att.net> "Fredrik Lundh" wrote in message news:mailman.26.1071059811.9307.python-list at python.org... > Spiffy wrote: > > > > that indicates that it's supposed to work, don't you think? > > > > IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? > > sure. if multiple independent sources say the same thing, your > first thought should be that they're all wrong. > > > > > Both the .exe and the .mid file are in the python path and the spelling > > > > been checked. > > > > > > you mean sys.path? > > > > IF I HAD MEANT sys.path, I WOULD HAVE SAID sys.path, DON'T YOU THINK? > > the python path is stored in the sys.path variable. why did you > say python path if you didn't mean it? > > > I DO NOT THINK THE PROBLEM IS IN HOW I USED THE FUNCTION > > NOR WHAT I EXPECTED FROM IT. > > no, your problems are obviously elsewhere. good luck with your > programming career. > > It's interesting to me that, although you provided no help or answers to me, you are convinced that you did. In fact, it is clear from your first response that your intention has been to amuse yourself by spouting attitude at me. Hope you had a good time. Meanwhile, Fredo has provided a nice answer that WORKS... along with an explanation of why my code didn't work. He was HELPFUL and didn't seem to have the need to belittle me for not being a professional Python Master. You remind me of one of these teens on IRC who have no other pleasure in life but to sit around and boot people out of their precious little chat rooms. I imagine if this was IRC, you would have booted me at the first post. From spam-trap-095 at at-andros.demon.co.uk Mon Dec 1 17:48:08 2003 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Mon, 1 Dec 2003 22:48:08 +0000 Subject: PyNum, A multidimensional array where the elements are arrays? References: <9832606.0312010634.170e50d3@posting.google.com> Message-ID: In article <9832606.0312010634.170e50d3 at posting.google.com>, Jack Liddle writes >I'm using Numerical Python to handle my arrays but I'm not sure how to >accomplish the following. > >I want a NxNxNxN array where each element of the the array >(A[i,j,k,l]) is itself a 3x3 array. So I can then slice my array >A[:,:,i,j] into planes and start grabbing matrices from it. I need to >slice it in all possible planes and I don't want to start messing >around with nested lists. > >How would I go about doing this in python, I guess in C I would have a >an NxNxNxN array full of pointers to matrix objects, but lifes to >short for C. Is there any reason not to just use an NxNxNxNx3x3 array? If you do this then the 3x3 matrices look like A[i,j,k,l,:,:] -- Andrew McLean From bsneddonNOspam at yahoo.com Wed Dec 24 12:06:40 2003 From: bsneddonNOspam at yahoo.com (Bill Sneddon) Date: Wed, 24 Dec 2003 12:06:40 -0500 Subject: Simple or Impossible in Python... dynamically dereferencing a class attribute In-Reply-To: References: Message-ID: Bruce Wolk wrote: >> > something like... > > setattr(myDict['one'],myletter,9) > This works!!! sorry for wasting bandwidth with such an easy question. but thank you for your answer. Merry Christmas! From newsgroups at jhrothjr.com Sat Dec 20 07:25:00 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 07:25:00 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <3fe43c97$0$19069$9b4e6d93@newsread2.arcor-online.net> Message-ID: "Hartmut Goebel" wrote in message news:3fe43c97$0$19069$9b4e6d93 at newsread2.arcor-online.net... > John Roth wrote: > > "Steve Lamb" wrote in message > >> If you had run it you would have understood it. You didn't run it, > >> did you? > > > > It doesn't matter. As you can see by my reply to Bengt, > > It does matter, since the _output_ of the result (which Steve posted for > your convenience) contains the answer to your question. I've been around long enough that that level of "cute" is simply irritating. I'm well aware of "explicit is better than implicit." > > the crux of the issue is that, in Ruby, the function call > > syntax is *optional.* > > The crux of this 'option' is that it's ambiguos whether you wnat to > _access_ or _call_ the function object. See line 12 of the output > meantioned above to know why Python will never implement such an > 'option'. [And BTW I probably will never use a language having such an > 'option'.] And if you read the rest of my comment, you would know that I am not suggesting that Python do so, for implementation reasons. There are ways around the ambiguity you mention, but they will not come out unless there is a *thoughtful* discussion, and in any case they would definitely break backwards compatability. > > What I'm missing, however, is any *thoughtful* > > discussion of the issues involved. Your [perjoritive > > adverb deleted] response makes it clear that you > > didn't think of the issues, you just reacted. > > *walking to the fuel-station, filling my many-years-unused flame-thrower > for the upcoming flame-battle* Why bother? John Roth > > > John Roth > > -- > Regards > Hartmut Goebel > > | Hartmut Goebel | We build the crazy compilers | > | h.goebel at crazy-compilers.com | Compiler Manufacturer | > From CousinStanley at hotmail.com Sun Dec 7 07:31:40 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 7 Dec 2003 05:31:40 -0700 Subject: Moving around in a string References: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> <5PSdndqm1duFeEyiRVn-sw@sysmatrix.net> Message-ID: | words_within = sentence.split() | | word_count = 0 | | for i in words_within: | word_count = word_count+1 | | print "There are", word_count, "words." Ryan .... You might also find the len() builtin function useful to provide the length of a list or string .... sentence = 'yo ho ho and a bottle of rum' words = sentence.split() word_count = len( words ) print word_count -- Cousin Stanley Human Being Phoenix, Arizona From newsgroups at jhrothjr.com Sat Dec 20 06:50:23 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 06:50:23 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Ville Vainio" wrote in message news:du74qvwuv28.fsf at lehtori.cc.tut.fi... > "John Roth" writes: > > > a third is the ability to forget the empty parenthesis after > > a function/method call that doesn't require parameters. > > Doesn't this suck big time? How can the interpreter tell whether you > are trying to call a function or just want a reference to a callable > object? That's the crux of the implementation issue, and I, for one, haven't got an answer that doesn't look real ugly (let alone break backwards compatability.) That's why I'm not pushing this particular issue seriously - I don't see a way of doing it, given the rest of Python, and completely independently of any "Python philosophy" issues. > > harder" syndrome. One of these days, someone is going > > to start chewing up the user base, and for a while it looked > > like Ruby might have been it. > > I dunno. It just doesn't seem likely that people who have "got" Python > would switch to ruby. If the extra features of ruby were really > worthwhile, they would be added to Python (which has happened > before). I trust the Py development team to do the right decision at > all times (apart from ternary operator, obviously ;-). The people who have switched don't post here. I'm very active on the XP mailing list, and I see lots more references to Ruby than to Python. Maybe the fact that such industry heavy hitters as Robert Martin, David Thomas, and any number of others have switched shouldn't count. In fact, the head of this thread should really be a wakeup call: the *only* reason that Python was chosen instead of Ruby is the lack of *current* market penetration. As far as doing the "right" thing, check the partial list of Ruby features I gave, and ask yourself how much each of them would break the "feel" of Python. It's not that the features aren't worthwhile, it's that there is a serious philosophy issue, which I think I'm going to address in my reply to Skip. John Roth > > -- > Ville Vainio http://www.students.tut.fi/~vainio24 From http Wed Dec 31 00:51:17 2003 From: http (Paul Rubin) Date: 30 Dec 2003 21:51:17 -0800 Subject: Project dream References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> Message-ID: <7xllotv8kq.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > Suppose it takes 15 minutes for Christian to write up an idea. > Suppose it then starts a thread, and he spends another 45 minutes > on that thread to get his point across. And suppose it goes nowhere. > (As he says, that's the usual case. It's easy to talk, hard to do.) > Then that's an hour which could have been spent on more productive > efforts. There could be a wiki page somewhere with a list of interesting project suggestions. I'd put stuff there. I can think of all kinds of cool programs that I'd like for other people to write ;-). > Are you going to the Python conference? That's a great way to > talk with a lot of people and get ideas for projects. (And they > too have their own way to convert sugar into artificial sweetners.) Nah, too expensive, I may go to CodeCon. From netnews at goldenspud.com Sun Dec 28 10:40:00 2003 From: netnews at goldenspud.com (Matthew Scott) Date: Sun, 28 Dec 2003 15:40:00 GMT Subject: indendation error References: Message-ID: km wrote: > kindly enlighten hwo to fix this -- > it will be great if someone can direct me to an online link regarding??the > rules?of?indendation. PEP 8 is the "Style Guide for Python Code" and is available here: http://www.python.org/peps/pep-0008.html Indentation and other code layout issues are addressed in the third section. >From personal experience, 99% of the Python code I've seen uses 4 spaces per indent, and no TAB characters. -- Matthew Scott From mbabcock at fibrespeed.net Fri Dec 5 15:14:11 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 05 Dec 2003 15:14:11 -0500 Subject: Lists and Tuples In-Reply-To: References: Message-ID: <3FD0E713.6040306@fibrespeed.net> > > >That's true, but another answer is: you should use tuples for short >>sequences of diverse items (like the arguments to a function). You >>should use lists for longer sequences of similar items. >> > > >I'm curious what you're getting at. I.e., what does diversity or >similarity have to do with the choice? Is that an aesthetic thing? >(In which case 'should' should be qualified a bit, IWT >Or what am I missing? > I think what he may be getting at is that in the case of a list, you should be able to perform the same operation(s) on all members. I'm not sure this is a should or not, but its true in my behaviours as a programmer at least. def runquery(query): try: # do stuff except query_error, e: errors += e result_count = len(results) return (result_count, results, errors) (count, results, errors) = runquery( ... ) ... but then results would probably be a list of rows ... results = [ { 'id': 1, 'name': 'Michael', 'position': 'Hacker' }, { 'id': 2, 'name': 'Dave', 'position': 'Boss' } ] Each item in the list does not have to be the same, but I usually assume that a list of 'somethings' is homogenous. In this case, all items are result-sets from the database. I expect nothing from a tuple ;-). Does this make sense? -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From skip at pobox.com Sat Dec 20 23:31:51 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 22:31:51 -0600 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: <279b566d.0312201935.38fb2156@posting.google.com> References: <279b566d.0312201935.38fb2156@posting.google.com> Message-ID: <16357.8759.734915.275270@montanaro.dyndns.org> John> On the other hand, claiming that sum() is an adequate replacement John> for reduce() is so silly that it borders on the absurd. >> No, operationally that's a correct statement. People have looked at >> the use of reduce() in a number of different contexts. In all but >> the rarest of cases, reduce() was used to sum a list of numbers. >> sum() is a perfectly adequate replacement in all but those rare cases >> and is easier to read as well. As Guido mentioned in the talk I >> referenced above: >> >> reduce() >> nobody uses it, few understand it >> a for loop is clearer & (usually) faster HV> I think no one even tries to understand the very concept of reducing HV> sequence to a single object using a rule . Sum is not a replacement HV> of this *concept*. Just what is so wrong with having such a general HV> tool available in a programming language ? Doesn't it hurt to HV> understand how to use it? It doesn't hurt to understand the concept of reduce(), but if it's never (or very rarely) used, it's just extra (nearly dead) code which has to be maintained. It's easy enough to write reduce() in Python, and if/when PyPy is a reality shouldn't be any less efficient than the current C version. >> No, it's simply not used very much. Python never has been a very >> strong functional language. It's always been a very strong >> object-oriented language. Use it the way it's strongest. HV> I think Guido should put his money where his mouth is and simply HV> eliminate functions as first class objects then ! There are lots of use cases for functions as first class objects which don't intersect with the usual notions of functional programming. Here's one rather silly example: l = [] append = l.append for i in range(25): append(i) Another less silly example is os.walk(). It's in some sense a specialized map() function, so does overlap a bit more with the usual notion of functional programming. HV> If python ever gets very fast, people will reimplement things like HV> reduce in their own code or in a functional module. As well they should. It's a five-liner in Python. I've never used it for anything but summing a list of numbers. That appears to be true of most people. John> There is no replacement for lambda in sight, even though lambda is John> arguably the ***largest single*** one of the functional constructs John> that needs work, and has obviously needed work for a long time. >> Once again, you desire Python to be something it is not. If you want >> a strong functional language, program in Lisp or Haskell. HV> Functions are supposedly first class, regular objects in python. Why HV> can't they be sometimes anonymous, just like tuples, lists and user HV> defined objects can ? One doesn't even need to consider other HV> languages to make this point. Having functions as first-class objects doesn't mean you have to be able to define anonymous functions. Functions as first-class objects worked just fine before Guido introduced lambda to the language in Python 1.0. HV> Does anyone care about consistency in python ? For real, if you HV> don't want functional programming, make functions non first class HV> and stop claiming that they are objects just like every object. As I indicated above, "functions as first-class objects" is not synonymous with "functional programming". There are plenty of uses for function objects without considering map(), apply(), lambda(), filter(), reduce() and friends. Skip From swalters_usenet at yahoo.com Wed Dec 31 15:28:45 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Wed, 31 Dec 2003 20:28:45 GMT Subject: Graceful failures References: <85b54e91.0312291414.6e61e535@posting.google.com> Message-ID: |Thus Spake Hans-Joachim Widmaier On the now historical date of Wed, 31 Dec 2003 18:19:00 +0100| > It is quite a coincidence that a thread like this pops up right when I > feel I have to start one - with almost exactly the same subject - > myself. > > Error handling can easily be the hardest task in a program, and that's > why its being neglected most of the time. Agreed. Another problem is that programmers often forget what it's like for people who don't understand computers. It's hard to overestimate the apprehension many users feel towards computers. I've seen very competent and intelligent people frozen with fear in front of a word processor because they were afraid that they'd break the computer. > I would like it much more detailed, like: Most people that will read this post would prefer a more detailed message. Of course one should tailor the system to your program's target audience, but let's assume, for the sake of this particular discussion, that the errors will mostly be read by non-technically oriented people. I think that detailed error reports should always be readily available, but should not necessarily be the first thing presented. > """ > Foo has encountered a problem. It was trying to load a necessary image > from the file '/usr/share/Foo/images/up.png'. This file does apparently > not exist. The problem may be caused by a broken installation of Foo. > Alas, Foo cannot be continued and will be closed. """ That's a good message. I would avoid putting raw filenames in the non-technical description. (Unless, of course, the user was trying to open a document, then it's okay to list the path.) I would also avoid using the words like "broken." Both of these things look normal to you and me, but to a lot of people they're Scary Things(tm). By simply hiding the filename behind a button that says "Technical Details" you have said "Hey, you might not understand this, but that's OK because it's meant for the geeks." Heck, they might take a look at it and feel proud that they understand more of it than they thought they would. I like the increased specificity of your error message. I might suggest: """ Foo has encountered a problem. It was trying to load necessary image files. At least one image apparently does not exist. Uninstalling and then Reinstalling Foo may correct this problem. Unfortunately, Foo cannot be continued and will be closed. """ > (I'm not the best error message designer, but I hope you get the point: Nor am I. Most of the reason I offered up my opinion is so that other people might clue me into new ideas on the matter. > Which means the details I want go there - fine with me. As most people like you and me wouldn't mind one extra click to get at the juicy details. > This, of course, is a bit overkill for a little freeware program, but > sounds good for a "big" application with a hefty price tag. It makes as much sense as installing something like bugzilla. (more on that in a minute) > Handling every conceivable error right is quite a challenge and lots of > work, especially in the test department. Let me digress for a moment and explain how I stumbled into this idea of allowing the user to jump to an online information system based on their particular error. It might make more sense if you know where it came from. Or, at least, you can pin-point the critical flaw in my logic. My last development job was with a large company that preprocessed medical insurance claims. Essentially, we took on contracts to collect insurance claims from doctors, verify that the data was well-formatted (there are several hundred formats for medical insurance claims) translate them into the single format requested by our client, transmit them to the client, receive the response and deliver the responses back to the doctors. Karl Marx would have hated us. We were nothing but big-time middle-men. When asked where I worked, I used to say "I work for a huge quasi-governmental corporation that exists solely to shuffle paper." The method for transferring data was plain old 56k modems and a simple BBS. Our competitive advantage in the market was that we handled all end-user support and that we offered a pretty gui program tailored specifically for the medical field. (At this point, anyone who's worked in that field knows exactly who I worked for.) The gui program, essentially a fancy modem driver that allowed the user to track which files had been sent and pair them with the proper responses. Unfortunately the code for it was one huge tangled mess. It was the first program I was asked to make changes too and, as I hadn't mastered the Borland C++ debugger, I resorted to the tried and true method of keeping a log file while debugging. Every time that the program began an action, I had it write and flush, in plain english, what it was attempting to do. I found that when I sent the product on to QA, that having that log was invaluable. After some discussion with our tech support department, we decided to keep the code in for the production version. It was a smashing success. The front line tech support people were able to get much more reliable information about how the user's particular error came about. They started a database around the log-file so that they could reference the solutions for people with the same or similar problems. Most importantly, for me at least, I knew exactly where the end users were having problems. I didn't have to deal with errors like "Version Foo failed an assertion on line X in module Bar." I was able to implement more graceful error handling. So, I read the OP and thought to myself: Couldn't python keep a stack of the 'goals' it's attempting to achieve, then if an exception was thrown or an assertion failed couldn't this become part of the information about the error. You would push goals onto the stack, then pop them off if the program was reasonably certain that the action wasn't going to cause a problem. Then, couldn't that information be used to see if other users were having the same or similar problems? Couldn't that information be used to register and track problems via a hybrid of a message-board and bugzilla? Well, I don't see why not. In fact, since Python's exception system is so wonderful you could have the error dialog marshal error codes and basic stack-trace info into the get portion of a url and probably even make it open a browser with the press of a button. The user wouldn't have to know that all this went on in the background. All they would know is "I pressed a button and it took me to a place where people wanted to help me make it work." I want to work on something like that someday. I've already got a couple of projects on my plate, so at the moment this is blue sky thinking, but don't you think it would be nice if things could work this way? Maybe when my current project becomes stable, I'll see if I can add this as a feature. Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From CousinStanley at hotmail.com Tue Dec 30 21:23:37 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 30 Dec 2003 19:23:37 -0700 Subject: GO AHEAD -MAKE ME LOOK DUMB- Please References: <2_ednbq16ZkVg2-iRVn-iQ@comcast.com> Message-ID: Under Win98 pythonpath is used as an environment variable and its string value can be displayed from a DOS command prompt using the echo command .... echo %pythonpath% K:\Python\Lib\site-packages\fixedpoint;G:\dislin\python;K:\Python\py_Work\GUI\Tk \Grayson\Examples;K:\Python\py_Work\GUI\Tk\Grayson\Examples\Common >From the Python interpreter, pythonpath can be checked using the os.environ method .... >>> >>> import os >>> >>> list_pp = os.environ[ 'pythonpath' ].split( ';' ) >>> >>> for this_path in list_pp : ... print this_path ... K:\Python\Lib\site-packages\fixedpoint G:\dislin\python K:\Python\py_Work\GUI\Tk\Grayson\Examples K:\Python\py_Work\GUI\Tk\Grayson\Examples\Common >>> -- Cousin Stanley Human Being Phoenix, Arizona From spam at a-nan.net Tue Dec 2 12:28:57 2003 From: spam at a-nan.net (Spam Collctor) Date: Wed, 3 Dec 2003 01:28:57 +0800 Subject: Excuse me! Message-ID: How can I use RFC822 to do a mail header pasrser?If can do it,how do I make it? thx From adalke at mindspring.com Tue Dec 30 23:05:51 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 31 Dec 2003 04:05:51 GMT Subject: Project dream References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> Message-ID: Christian Tismer: > > Most of the > > time it was just some sugar spread around to make people excited, > > creating lengthy threads with no result. How serious are you about > > spending a reasonable amount for a really innovative application in > > Python. Paul Rubin: > I don't see any bad consequences of posting interesting ideas for projects, > even if nobody takes them up. Suppose it takes 15 minutes for Christian to write up an idea. Suppose it then starts a thread, and he spends another 45 minutes on that thread to get his point across. And suppose it goes nowhere. (As he says, that's the usual case. It's easy to talk, hard to do.) Then that's an hour which could have been spent on more productive efforts. Oh, the first couple dozen times it's fun to shoot the breeze like that, but after a while that sugar turns into saccarine. Are you going to the Python conference? That's a great way to talk with a lot of people and get ideas for projects. (And they too have their own way to convert sugar into artificial sweetners.) Andrew dalke at dalkescientific.com From __peter__ at web.de Tue Dec 16 03:45:51 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Dec 2003 09:45:51 +0100 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: Cameron Laird wrote: > We've probably convinced Mr. Sims that Python (and > object-oriented programming) is really, really hard, > particularly compared to Perl: we have to write > hairy Class definitions just to do the simplest > things. Posting a piece of ugly code to meet a specification that is incomplete or even wrong and at the same time showing Python in bad light compared to Perl... I have to be more careful with my posts. Peter From aleax at aleax.it Fri Dec 26 09:00:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Dec 2003 14:00:11 GMT Subject: Socket Programming References: Message-ID: Bjorn Pettersen wrote: ... > Finally, I'd be very surprised if "Python in a Nutshell" by Alex Martelli > didn't have the best coverage of them all, however that book is still on > my list so I'll have to let someone else comment on it... I'm obviously biased, so I won't comment, but the Nutshell does indeed have a full chapter devoted to sockets and server-side modules. Fortunately, you need not rely on others' opinions about it: you can visit safari.oreilly.com and join, for free, for two weeks, to read one or more chapter from the Nutshell (and/or many other books) online. Just remember to cancel the subscription within 2 weeks so you won't have to pay for it! Alex From theller at python.net Wed Dec 17 15:29:06 2003 From: theller at python.net (Thomas Heller) Date: Wed, 17 Dec 2003 21:29:06 +0100 Subject: "Bad file descriptor" after py2exe or Installer References: <3FD8B25A.7080103@gmx.net> <3FD97E83.2000703@gmx.net> <3FDDCE47.2000708@gmx.net> Message-ID: Luc Saffre writes: > On 12.12.2003 15:41, Thomas Heller wrote: > >> py2exe seems to pick up cygwin binaries. The reason could be that >> either you have cygwin extensions somewhere in your pythonpath, or parts >> of the PATH env variable points into the cygwin directories, or >> something like that. You should look at the output above carefully, and >> make sure that it is what one would expect. > > That's it! Thank you, Thomas, your hint helped. > > I had the Cygwin tcltk package installed. After removing this package > (using cygwin's setup.exe), I can use again the original PIL/Image.py > and everything works fine. > > My PATH contains the cygwin bin directories: > PATH=u:\CYGWIN\BIN; > c:\python23\Scripts;c:\python23; > ... > u:\CYGWIN\USR\BIN;u:\CYGWIN\USR\LOCAL\BIN;... > > Another workaround is to remove the cygwin directories from PATH: > I reinstalled the cygwin tcltk and the problem reappeared, > moving the first cygwin directory to come after the python directory > did not help. Then I removed those directories completely from PATH > (during the build) and the problem disappeared again. > > I would consider this as a bug (in both py2exe and Installer) since > they decide to pick some cygwin tcl/tk dll's who happen to hang around > while the Python runtime won't... Yep, that's a bug. Although I wonder: does it really make sense to include cygwin's path into PATH? Isn't cygwin only usefull from within the cygwin prompt? I tried cygwin some time ago, and was initially broken because I had installed (native) mingw32 somewhere, so it seemed to me to better keep cmd.exe and cygwin's paths separate from each other. Thomas From Dick.Zantow at lexisnexis.com Mon Dec 8 12:13:07 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Mon, 8 Dec 2003 12:13:07 -0500 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > David Eppstein writes: > >> This doesn't make sense to me as an explanation. Smalltalk didn't >> reach much of a mass audience until Goldberg's book was published >> in 1983, and other object-oriented languages (e.g. C++) did not >> immediately adopt CamelCase (I see none in Stroustroup's 1986 C++ >> book). In the meantime, CamelCase (with or without the initial >> capital) was certainly used prior to 1983 in languages such as >> Pascal. > > Someone else in this thread claimed that CamelCase came to Pascal > via Apple. And we know that Apple was lapping at the time from the > font of Xerox Parc. This would explain how CamelCase made it from > Smalltalk to Pascal. > > I used Pascal in the very late '70's and very early '80's, and I > never saw anyone use CamelCase in it. And now that David Epstein > has jogged my memory -- it is indeed in SmallTalk that I first saw > people using CamelCase, and, I must say, I was rather aghast. > > IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopleWouldWr iteLike > ThisAllTheTime. > >>> oug There's nothing about case standards that suggests that removing spaces between lexical units is a good thing. In any event, it would be preferable to "IFCAMELCASEWEREAGOODIDEAEVENINACASESENSITIVELANGUAGE, THENPEOPLEWOULDWRITELIKETHISALLTHETIME." in either a case-sensitive or case-insensitive language. The worst-case (as it were) scenario that I can remember happened when I was working with PL/I on an IBM mainframe, using 3270 terminals. This was a case-insensitive language, so some people adopted the conventions others have mentioned (constants in ALL_CAPS, functions and procedures in camelCase (sometimes) -- but some didn't. Some coded with the terminal set to *display* all caps (which allowed typing in lower case without being aware of it), and some didn't. Some of each group modified the code of programmers from the other group, and when the terminals displayed case as entered, the result was an unholy hodgepodge of upper and lower case clumps of letters in the oddest places imaginable. There was no apparent rhyme or reason to the case changes, even though everyone was utterly systematic about how they did their coding. The reason people chose to mix their cases is that one-case code is difficult to read. That's why alphabetic languages developed case conventions in the first place; the cases contain information in themselves. -- rzed From Scott.Daniels at Acm.Org Mon Dec 15 11:51:07 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 15 Dec 2003 08:51:07 -0800 Subject: Python Cookbook question re 5.6 In-Reply-To: References: Message-ID: <3fdcaf2d$1@nntp0.pdx.net> Joe wrote: > The recipe in question is "Implementing Static Methods". It shows how to > use staticmethod(). This sentence in the Discussion section isn't clear to > me: "An attribute of a class object that starts out as a Python function > implicitly mutates into an unbound method." I'm not sure what this means, > exactly. Can anyone elaborate? > > Thanks, > Chris First, you might cite the actual recipe here, so people can go look: The way a class is constructed consists of: 1) open a scope at the point where the class definition starts. 2) Collect each definition in the scope (value an name). At this point (during the collection), you are building "normal" functions with def. 3) When the end of the class definition is found, all of the definitions collected in (2), along with the class name and superclasses are used to build the actual class. This is the moment when the normal functions created in step 2 are used to build "unbound methods" -- the magic used to make objects work. Here's some code that, once you understand it, illustrates this: class SomeClass(object): def function(self, other): print 'called with self=%s, and other =%s' % (self, other) return self, other pair = function(1,2) # normal during class construction print pair # We can even see the pair. statmeth = staticmethod(function)# uses, not changes, function pair2 = function(2,3) # Demonstrate function still works print SomeClass.pair, SomeClass.pair2 # The class vars are there obj = SomeClass() # make an instance pair3 = obj.function(4) # Note only 1 arg is accepted. print obj, pair3 # the object was used as the first arg pair4 = SomeClass.statmeth(4, 5) # The old function behavior pair5 = obj.statmeth(5, 6)# Also the old function behavior pair6 = SomeClass.function(obj, 7) # An "unbound method" can # be used on the right kind of object pair7 = SomeClass.function(7, 8) # Raises an exception! An # "unbound method" needs the correct # kind of object as its first argument. -Scott David Daniels Scott.Daniels at Acm.Org From hans at zephyrfalcon.org Mon Dec 1 12:40:08 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 01 Dec 2003 12:40:08 -0500 Subject: split on blank lines In-Reply-To: References: <807692de.0312010610.4461c0e3@posting.google.com> Message-ID: <3FCB7CF8.2000904@zephyrfalcon.org> Duncan Booth wrote: > Given that re.compile("^$", re.MULTILINE).findall("foo\n\nbar\n\nbaz") > returns ['', ''] I would agree this looks like a bug. You could submit a > bug report on Sourceforge. I may be wrong, but I would think that the behavior is correct. "^$" matches an empty line. This is exactly what findall returns... two empty lines. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From aahz at pythoncraft.com Tue Dec 2 20:26:02 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2003 20:26:02 -0500 Subject: python's threading has no "interrupt"? References: <9btu91-s04.ln1@beastie.ix.netcom.com> Message-ID: In article <9btu91-s04.ln1 at beastie.ix.netcom.com>, Dennis Lee Bieber wrote: > >There's the first point of departure: Python threads (as long as you >aren't in a C language number crunching extension) are preemptive >scheduled, on something like a 10-20 byte-code interval. Cooperative >basically means /you/ had to handle the scheduling of threads; in >Python you don't, it happens automatically. Actually, that's not really correct. Cooperative threading means that there's no way to force a thread to yield up a timeslice, which is precisely the way Python works, because any bytecode can last an arbitrarily long time (consider 100**100**100). It is true that the Python core does switch between bytecodes, but that should not be considered preemptive in the traditional sense. OTOH, Python threads are built on top of OS-level threads, so extensions that release the GIL do run under the preemptive OS scheduler. To put it another way, the reason why Python threads aren't preemptive is because each Python thread acquires an OS-level lock that only the Python core will release, one thread at a time. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From chrisks at udel.edu Wed Dec 17 17:32:28 2003 From: chrisks at udel.edu (Chris S) Date: Wed, 17 Dec 2003 17:32:28 -0500 Subject: Sound generation recommendations? References: Message-ID: The only reasonably reliable python sound toolkit I know of is Snack, http://www.speech.kth.se/snack/. Unfortunately, it's mainly geared towards tcl, is relatively light on documentation (especially on sound generation), and the author seems to have lost interest in the project. Pygame, http://www.pygame.org/, also has some sound generation capabilities, although they're not its primary focus. Chris S. "Charles Hixson" wrote in message news:mailman.257.1071687046.9307.python-list at python.org... > I'm looking for a simple means of generatings sounds. Basically what I > want to do is play music from the information available in sheet music. > I would like to send the commands to the player in relatively short > bursts (the initial application is desired > to be a rising diatonic scale everytime the ball bounces off a paddle in > a game of pong, based on tomspong.py (an SDL application). I think that > the beep function in the winsound module would work, but I want this to > work on Linux and the Mac, and I don't even have a Windows box to test > it on. > > It would be nice if I could also specify the "instrument", for some > definition of instrument. But this would be useful only if I had access > to a library of instruments. Stereo might be a nice feature to add in > later, but not yet unless it were really easy. My feeling about this > part right now is "KISS, or you'll be diverted from the parts that are > more important.". > > All the sound modules I've looked at seem to run off of sampled wave > forms ... and this is nearly the opposite of what I want. > > From duncan at NOSPAMrcp.co.uk Fri Dec 12 05:57:28 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Dec 2003 10:57:28 +0000 (UTC) Subject: Function application optimization. References: Message-ID: Jacek Generowicz wrote in news:tyf7k128j09.fsf at pcepsft001.cern.ch: > Given > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > > How should one spell > > results = map(lambda f,a: f(a), fncs, args) > > in order to get the result most quickly ? > Well, the way you wrote it isn't actually bad. The obvious alternative (using a list comprehension) is slightly slower, but there isn't an awful lot to choos between any of them, I suspect most of the time goes in the actual f(a) function call. Any of these methods runs at about 300,000 function calls/second on my slow laptop. >>> setup = """import itertools def fn1(a): pass fns = [fn1] * 100 args = [0] * 100 """ >>> stmt1 = "result = [ f(a) for (f,a) in itertools.izip(fns, args) ]" >>> stmt2 = "result = [ f(a) for (f,a) in zip(fns, args) ]" >>> t = timeit.Timer(stmt1, setup) >>> t.repeat(3,10000) [3.5571303056673855, 3.5537404893639177, 3.5594278043718077] >>> t = timeit.Timer(stmt2, setup) >>> t.repeat(3,10000) [3.893281967400867, 3.87834794645687, 3.8829105375124868] >>> setup = """import itertools def fn1(a): pass fns = [fn1] * 1000 args = [0] * 1000 """ >>> t = timeit.Timer(stmt1, setup) >>> t.repeat(3,1000) [3.3503928571927304, 3.3343195853104248, 3.3495254285111287] >>> t = timeit.Timer(stmt2, setup) >>> t.repeat(3,1000) [3.8062683944467608, 3.7946001516952492, 3.7881063096007779] >>> stmt3 = "results = map(lambda f,a: f(a), fns, args)" >>> t = timeit.Timer(stmt3, setup) >>> t.repeat(3,1000) [3.3275902384241363, 3.3010907810909202, 3.3174872784110789] The f(a) call is taking about half the time in any of these methods, so you aren't going to get very much improvement whatever you do to the loop. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From peter at engcorp.com Thu Dec 4 10:43:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Dec 2003 10:43:38 -0500 Subject: ISO to Gregorian, strptime madness References: Message-ID: <3FCF562A.23E44C27@engcorp.com> Afanasiy wrote: > > While I'm posting, how about this old dilemma... from the 2.3 modules. > strptime exists in time, but not in datetime, while strftime exists in > both. Uh, really? C:\>python23 Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 >>> import time >>> import datetime >>> time.strftime >>> time.strptime >>> datetime.strftime Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'strftime' >>> datetime.strptime Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'strptime' Looks to me like strptime and strftime are both in time and not in datetime. -Peter From SBrunning at trisystems.co.uk Mon Dec 1 06:22:17 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 1 Dec 2003 11:22:17 -0000 Subject: Binary number manipulation Message-ID: <31575A892FF6D1118F5800600846864D01200D66@intrepid> > From: Matthew A. Berglund [SMTP:matt at satbp.com] > I am very new to python so I am working on some ass-umptions which may be > incorrect (please forgive me). > > I am working on a problem that requires me to take 2 decimal integers, > each of which represents half of a word. I need to slap these things > together and get out another decimal integer. > A couple of questions: > 1. Is there a way to typecast a variable as a binary? AFAIK, no. > 2. If 1 is no, does that mean that I need to do all the manipulation in > some icky string format and then go back? I use: ((high << 16) | low) > I do see the bit-wise operations available and this looks like I need to > simply perform these on my integers? Can it really be that simple? Yup. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From matt.gerrans at hp.com Tue Dec 16 15:59:55 2003 From: matt.gerrans at hp.com (Matt Gerrans) Date: Tue, 16 Dec 2003 20:59:55 GMT Subject: range of characters? References: Message-ID: I think the colon was on the wrong side of the 26, anyhow. By the way, I would use string.uppercase or string.lowercase, depending upon which I wanted. From newsgroups at jhrothjr.com Sat Dec 20 06:43:13 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 06:43:13 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Steve Lamb" wrote in message news:slrnbu7m1s.u03.grey at dmiyu.org... > On 2003-12-20, John Roth wrote: > > I'm not sure what your point is. > > If you had run it you would have understood it. You didn't run it, did > you? It doesn't matter. As you can see by my reply to Bengt, the crux of the issue is that, in Ruby, the function call syntax is *optional.* There is no way to make it optional in Python, and it is not clear whether it should be. What I'm missing, however, is any *thoughtful* discussion of the issues involved. Your [perjoritive adverb deleted] response makes it clear that you didn't think of the issues, you just reacted. John Roth > > -- > Steve C. Lamb | I'm your priest, I'm your shrink, I'm your > PGP Key: 8B6E99C5 | main connection to the switchboard of souls. No, you're not, and you will never be. John Roth From a at spam.nl Wed Dec 17 04:16:48 2003 From: a at spam.nl (duikboot) Date: Wed, 17 Dec 2003 10:16:48 +0100 Subject: change dpi without changing pixels dimensions with PIL? Message-ID: <3fe01f2a$0$44014$e4fe514c@dreader9.news.xs4all.nl> Hi there, In Photoshop I can, when I want to change the dpi(dots per inch) of a picture, arrange that the picture won't be resized. Do you know of a way, I can accomplish this in python with PIL? If I use this script it changes the dpi, but the picture becomes huge. Thanks Arjen import sys import Image import os a=sys.argv[1] print a c="or"+a b=os.system("rename %s %s" % (a, c)) im=Image.open(c) print im.info["dpi"] im.save(a, dpi=(150, 150) From robin at jessikat.fsnet.co.uk Thu Dec 11 04:15:00 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 11 Dec 2003 09:15:00 +0000 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> Message-ID: In article <7xwu93g759.fsf at ruckus.brouhaha.com>, Paul Rubin writes >"Fredrik Lundh" writes: >> 5) use an event loop and use a generator for the relevant code; >> when you discover that you need to pause, yield to the framework. > >This kind of design really could benefit from Raymond Hettinger's PEP >of a while back, proposing being able to pass parameters from the >caller back to the yield statement of a yielded generator. I was just about to ask if generators allow for a stream like mechanism, but obviously if we're not allowed to change the generator state then it seems quite hard. -- Robin Becker From sunas at web.de Thu Dec 11 03:08:29 2003 From: sunas at web.de (Alexander Schwaigkofler) Date: Thu, 11 Dec 2003 09:08:29 +0100 Subject: numarray doesn't work on win2k Message-ID: <3fd82588$0$18044$3b214f66@aconews.univie.ac.at> Hi! I have the following problem with numarray. I read the install.txt manual, but it doesn't already work. OS: Microsoft Windows 2000 [Version 5.00.2195] python: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 numarray: Version 0.7 the output from the installation (by hand) you can see below: The other possibility to install numarray on a win32 platform is to run the self-installing executable. If I tried it that way, I can't test the numarray package. Is there any problem with the installtion that doesn't descripe in the install.txt-File? kind regards Alexander C:\..\python223\numarray-0.7>python setupall.py install --gencode ================================================================= Installing numarray with python: (2, 2, 3, 'final', 0) ================================================================= Using EXTRA_COMPILE_ARGS = [] generating new version of Src/_convmodule.c generating new version of Src/_sortmodule.c generating new version of Src/_bytesmodule.c generating new version of Src/_ufuncBoolmodule.c generating new version of Src/_ufuncInt8module.c generating new version of Src/_ufuncUInt8module.c generating new version of Src/_ufuncInt16module.c generating new version of Src/_ufuncUInt16module.c generating new version of Src/_ufuncInt32module.c generating new version of Src/_ufuncUInt32module.c generating new version of Src/_ufuncFloat32module.c generating new version of Src/_ufuncFloat64module.c generating new version of Src/_ufuncComplex32module.c generating new version of Src/_ufuncComplex64module.c generating new version of Src/_ufuncInt64module.c generating new API module 'libnumarray' .c & .h generating new API module 'libteacup' .c & .h running install running build running build_py creating build creating build\lib.win32-2.2 creating build\lib.win32-2.2\numarray copying Lib\arrayprint.py -> build\lib.win32-2.2\numarray copying Lib\codegenerator.py -> build\lib.win32-2.2\numarray copying Lib\generic.py -> build\lib.win32-2.2\numarray copying Lib\ieeespecial.py -> build\lib.win32-2.2\numarray copying Lib\memmap.py -> build\lib.win32-2.2\numarray copying Lib\numarrayall.py -> build\lib.win32-2.2\numarray copying Lib\numarraycore.py -> build\lib.win32-2.2\numarray copying Lib\numarrayext.py -> build\lib.win32-2.2\numarray copying Lib\numeric.py -> build\lib.win32-2.2\numarray copying Lib\numerictypes.py -> build\lib.win32-2.2\numarray copying Lib\numinclude.py -> build\lib.win32-2.2\numarray copying Lib\numtest.py -> build\lib.win32-2.2\numarray copying Lib\objects.py -> build\lib.win32-2.2\numarray copying Lib\records.py -> build\lib.win32-2.2\numarray copying Lib\safethread.py -> build\lib.win32-2.2\numarray copying Lib\strings.py -> build\lib.win32-2.2\numarray copying Lib\teacup.py -> build\lib.win32-2.2\numarray copying Lib\template.py -> build\lib.win32-2.2\numarray copying Lib\testall.py -> build\lib.win32-2.2\numarray copying Lib\testdata.py -> build\lib.win32-2.2\numarray copying Lib\typeconv.py -> build\lib.win32-2.2\numarray copying Lib\ufunc.py -> build\lib.win32-2.2\numarray copying Lib\_ufuncall.py -> build\lib.win32-2.2\numarray copying Lib\__init__.py -> build\lib.win32-2.2\numarray running build_ext building 'numarray._conv' extension creating build\temp.win32-2.2 creating build\temp.win32-2.2\Release cl.exe /c /nologo /Ox /MD /W3 /GX -IInclude/numarray -IC:\..\python22 3\include /TcSrc\_convmodule.c /Fobuild\temp.win32-2.2\Release\_convmodule.obj error: command 'cl.exe' failed: No such file or directory Traceback (most recent call last): File "setupall.py", line 15, in ? import numarray.testall as testall ImportError: No module named numarray.testall From gagenellina at softlab.com.ar Wed Dec 31 14:23:18 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Wed, 31 Dec 2003 16:23:18 -0300 Subject: Maybe a stupid idea In-Reply-To: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: <5.2.1.1.0.20031231162109.023e5580@192.168.0.115> At 31/12/2003 09:49, you wrote: >I'm kind of newbie to programming, but I thought of something and I >want some opinions on that. > >It's about a new instruction block to do some cycles. > >I thought about that because it's not very easy to program a cycle. >Here is a simple example : > >b=0 > >while b < 50: > b+=1 > print "*" * b > >while b > 0: > b-= 1 > print "*" * b > >It takes two while blocks to do a cycle. No need for a new structure: for i in range(10)+range(10,-1,-1): print '*'*i Gabriel Genellina Softlab SRL From skip at pobox.com Mon Dec 29 09:27:27 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 29 Dec 2003 08:27:27 -0600 Subject: Seeking regex-to-re HOWTO In-Reply-To: References: Message-ID: <16368.14799.664786.536507@montanaro.dyndns.org> Josef> Is Andrew Kuchling's regex-to-re HOWTO available anywhere? Josef> I've found the following (dead) links on various Web pages: Looks like it is no longer officially available. I ran 'find' on www.python.org in the obvious places but didn't find it. Try the Wayback Machine: http://www.archive.org/ Search for regex-to-re. The third item points to: http://web.archive.org/web/20001119074200/www.python.org/doc/howto/regex-to-re/regex-to-re.html Skip From bjorn.pettersen at comcast.net Thu Dec 25 06:09:04 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Thu, 25 Dec 2003 05:09:04 -0600 Subject: Socket Programming References: Message-ID: "Kamuela Franco" wrote in news:KdzGb.23400$NZ1.18286 @nwrddc02.gnilink.net: > Can someone give me some general information on socket programming in > Python. > > trainee There's nothing special about socket programming in Python, any book on the subject will do (or just the Python docs, if you've done socket programming elsewhere). If you have specific issues, feel free to ask them (provide code for what you've tried if possible)... and if you give a hint about your experience level with sockets it would potentially prevent someone from writing the first chapters of a new book, and also be more useful to yourself . -- bjorn From fredrik at pythonware.com Tue Dec 16 16:39:02 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Dec 2003 22:39:02 +0100 Subject: ignore References: <030c01c3c419$266a40f0$891e140a@YODA> Message-ID: Dave Brueck wrote: > Just curious: what's the community-friendly way of testing if you don't use > comp.lang.python (the Usenet group) but instead use python-list (the > Mailman-managed list)? waiting 24-48 hours before checking the archives, and posting your original question again if and only if it's not there? From cartermark46 at ukmail.com Fri Dec 12 12:11:38 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 12 Dec 2003 09:11:38 -0800 Subject: Python progamming certification References: Message-ID: > consider FOSS work to be of any value (but then would I want to work > for such a company...?) At the end of the day, aren't we all wage slaves anyway? > rather commercial experience only being the I had the same problem with programming in academia; because it's not "real", or something. Makes me feel like punching someone in the neck. From skip at pobox.com Mon Dec 1 16:05:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 1 Dec 2003 15:05:01 -0600 Subject: sys._getframe() not behaving as expected Message-ID: <16331.44285.6257.338657@montanaro.dyndns.org> sys._getframe() is acting peculiar. At least it doesn't seem to be doing what I expect based upon a couple readings of its doc. Given this module (call it 'gl'): import sys def printframes(): print "frame[-2]:", id(sys._getframe(-2)) print "frame[-1]:", id(sys._getframe(-1)) print "frame[0]:", id(sys._getframe(0)) print "frame[-2] globals:", id(sys._getframe(-2).f_globals) print "frame[-1] globals:", id(sys._getframe(-1).f_globals) print "frame[0] globals:", id(sys._getframe(0).f_globals) print "my globals:", id(globals()) calling it like so from the interpreter prompt (CVS): >>> import gl >>> def f(): ... gl.printframes() ... >>> f() frame[-2]: 3822448 frame[-1]: 3822448 frame[0]: 3822448 frame[-2] globals: 11889232 frame[-1] globals: 11889232 frame[0] globals: 11889232 my globals: 11889232 >>> id(globals()) 3955136 The gl.printframes() function never prints the id of the interpreter's globals(), nor does it ever print different frames. What am I missing? I would like to get a handle on the globals for the frame from which printframes() is called. Skip From http Tue Dec 23 04:18:47 2003 From: http (Paul Rubin) Date: 23 Dec 2003 01:18:47 -0800 Subject: Flat file database References: <7xy8t4m1mw.fsf@ruckus.brouhaha.com> Message-ID: <7xk74n7uyw.fsf@ruckus.brouhaha.com> "Art Decco" writes: > And I don't think MySQL is available without switching to a more expensive > type of account. This application, essentially a fancy Christmas card list, > just isn't worth all that trouble, but it would be nice if someone knows of > a Python module that makes simple text file management a little easier. I don't understand then why you want such a module. If there's just a few dozen lines in the file, then read it into memory, change whatever you want, and write it out again. Personally for these kinds of database applications though, I usually use the anydbm module. From mnations at airmail.net Wed Dec 31 12:03:52 2003 From: mnations at airmail.net (Marc) Date: 31 Dec 2003 09:03:52 -0800 Subject: Freezing win32com with multi platform/version support Message-ID: <4378fa6f.0312310903.1ea2d50b@posting.google.com> Hi all, I have a program using win32com that I have successfully frozen and works for people who have the same Windows and Excel versions as I do. But there are problems that are possibly caused by other users who have newer versions of both. So my question has to do with the makepy.py file. Do I need to use the '-d' option in order to force the libraries to compile at run time? Because I thought that if you simply deleted the gen_py directory (from the frozen version) it would force the cache to rebuild no matter what computer the makepy file was originally generated on. Is there something else I should be doing in order to ensure multi-platform/version supprt? Thanks ahead of time, Marc From no.spam at no.smap.com Tue Dec 23 04:33:47 2003 From: no.spam at no.smap.com (Maciej Sobczak) Date: Tue, 23 Dec 2003 10:33:47 +0100 Subject: Default arguments, object sharing, name lookup and others In-Reply-To: References: Message-ID: Hi, Maciej Sobczak wrote: > Playing around with the Python Tutorial I found the following definition: > > def f(a,L=[]): > L.append(a) > return L [...] Thank you very much for your replies. The most enlightening was the one mentioning func_defaults. For your *amusement only*, here is the C++ analogy I devised for myself to better understand what is going on: The Python function definition is like definition *and* creation of C++ function object, initialized with what should be the default value for further function calls: class Fun { public: Fun(shared_ptr default_value) : def_val_(default_value) {} Any operator()(shared_ptr arg) { // here goes the body of the function // ... } Any operator()() { return operator()(def_val_); } private: shared_ptr def_val_; }; (of course, this applies to *one-argument* function with default argument value) Once the function object is created, it stores the default value for future. When it is called without arguments, it retrieves the default value from where it is stored. Now, the hard core: - If I do some mutating operation on the default value (like list append or insert operation), I can see it the next time I call the function. - If I reassign the arg shared pointer to something else (for example, to the new value like in "L = L + a" Python expression), it does not influence the object pointed by def_val_ pointer and is visible only to the end of the current flow in operator(), when the local arg variable goes out of scope. Regards to all, -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From jurgenex at hotmail.com Sat Dec 20 16:18:41 2003 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sat, 20 Dec 2003 21:18:41 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: Xah Lee wrote: > i have a bunch of java files that has spaced-out formatting that i > want to get rid of. I want to replace two end of line characters by > one end of line characters. The files in question is unix, and i'm > also working under unix, so i did: > > perl -pi'*~' -e "s@\n\n@\n at g" *.java > > but this to no avail. > > after many minutes of checking and rechecking and lots of trial and > error with frustration, i realized that the fucking perl to my > expectations again cannot do this simple fucking thing. Nor can the > unix utility tr. Fucking stupid perl couldn't do a simple task of > replacing strings. > > let me just take this opportunity to explain one shit from the > thousands from perldoc. [rest of rant snipped] Five seconds of thinking might have spared you from embarassing yourself like that (and is certainly more effective than 5 paragraphs of swearing). You are reading the file line by line. And with each line you are looking for two consecutive newlines. Now, how can a single line contain two newlines? jue From hungjunglu at yahoo.com Fri Dec 26 15:27:29 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 26 Dec 2003 12:27:29 -0800 Subject: dynamic typing question References: Message-ID: <8ef9bea6.0312261227.56ade9a9@posting.google.com> claird at lairds.com (Cameron Laird) wrote in message news:... > 1. Why, in your mind or your teammate's, > is dynamic typing a "lack"? What, pre- > cisely, is the benefit of static typing? > There are a number of legitimate > answers. It occurs to me that, without > precision on which interest you, we > might be missing an opportunity to > clarify "The Python Way" significantly. One static typing advantage I've run into: When you change the name of a variable in a class, and re-compile the program, the compiler shows you ALL places where compilation fails. These could be hundreds of places in dozens of files. In dynamically typed language like Python, you have to rely on text search, which often yields many false positives, especially for common/overloaded names like .count, .name, .type, etc. In statically-typed languages, making name changes is not very painful, since the compiler will tell you where exactly you need to follow up with the changes. In dynamically typed language, you will have to manually write unit test codes to ensure name consistency. I am sure Python people have come up with strategies to deal with this problem. That's what I'd like to hear. (Unit test is one route.) But this is one place where I've found statically-typed compilers useful. I mean, I have seen this discussion many times, but most responses from Python users have not been realistic (often simply shrugging off the problem and saying something like "compilers don't detect all the bugs, blah blah blah".) I would like to hear more real-life experience rather than academic conjectures. regards, Hung Jung From missive at frontiernet.net Sat Dec 13 19:32:46 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 14 Dec 2003 00:32:46 GMT Subject: python2.3 upgrade References: <87ekv8vl39.fsf@mobile.foo> <5FFCb.88560$AX1.3685023@news1.tin.it> Message-ID: On 2003-12-13, tudor wrote: > Lawrence Oluyede wrote: > >> tudor writes: >> >>> Traceback (most recent call last): >>> File "/usr/sbin/redhat-switch-printer", line 84, in ? >>> main() >>> File "/usr/sbin/redhat-switch-printer", line 68, in main >>> from switchprinter_gui import mainDialog >>> File "/usr/share/redhat-switch-printer/switchprinter_gui.py", line 51, >>> in ? >>> import gtk >>> ImportError: No module named gtk >> >> Have you reinstalled pygtk for the right python version? >> > I have pygtk-1.99 which I guess is too old.... > But I don't think I'm gonna find rpms for my rh8 of the new pygtk, so I'll > have to renew the whole gtk2 ! which kinda sounds scarry to me... I see 2 possibilities. Often, when "upgrading" python, what you really do is just install a new version, and the old version is still there. Try something like ... ls -l /usr/local/bin/py* and see if you get ... -r-xr-xr-x 2 root wheel 766652 Nov 21 03:53 /usr/local/bin/python -r-xr-xr-x 1 root wheel 520908 Oct 14 20:03 /usr/local/bin/python2.1 -r-xr-xr-x 1 root wheel 657928 Sep 26 13:20 /usr/local/bin/python2.2 -r-xr-xr-x 2 root wheel 766652 Nov 21 03:53 /usr/local/bin/python2.3 (you may have to look around for where your python is) If 2.2 is still there, but python is pointing to python2.3 you should be able to get the old version working again by doing rm /usr/local/bin/python ln /usr/local/bin/python2.2 /usr/local/bin/python Then when you want to run 2.3 for your own use, or for programs that require 2.3 you will have to run it specifically as python2.3 The other option would be to just copy the packages from the old install to the new one. Something along the lines of ... cp -R /usr/local/lib/python2.2/site-packages/* /usr/local/lib/python2.3/site-packages You will probably get warnings when programs start up, but it should work at least until you get a chance to rebuild things. From exarkun at intarweb.us Tue Dec 9 15:12:30 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 9 Dec 2003 15:12:30 -0500 Subject: Optimize flag on shebang line In-Reply-To: References: Message-ID: <20031209201230.GA12652@intarweb.us> On Tue, Dec 09, 2003 at 02:02:03PM -0500, Andres Corrada-Emmanuel wrote: > Hello, > > Does the optimize flag work on the shebang line of UNIX systems? I've > tried to execute a script on a Solaris system with a shebang line of the > form: > > #! /usr/bin/env python -O > Typically, you can pass only a single argument to the interpreter. Your platform may be silently ignoring the -O. Have you tried with simply "#!/path/to/python -O"? Note that -O hardly does anything, so even if you can't get this working, it's not much of a loss. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 19 18:38:49 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 20 Dec 2003 00:38:49 +0100 Subject: dynamic typing questions References: Message-ID: John Roth: >I'm beginning to think that debuggers were the single worst invention in history. Atomic bomb, MS-DOS, daylight saving time, C, ... are you sure? -- Ren? Pijlman From try_vanevery_at_mycompanyname at yahoo.com Wed Dec 17 23:44:43 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 17 Dec 2003 20:44:43 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: "Richard Brodie" wrote in message news:brpop1$1636 at newton.cc.rl.ac.uk... > > That said, Brandon's claim was fairly contentious and likely to get > someone to bite. It's a well worn debate though, and c.l.py probably > isn't the best place to renew it. It was a comment made in passing, and it takes quite a Trollhunter to make it otherwise. My motives for posting were quite explicit, and I could care less whether anyone wants to call .NET "a clone" or not. You can call it a sheep or a dog or a rock for all I care. You can debate it until the cows come home for all I care, I just want to know if people are using Python for .NET. Again in passing: the concept of .NET was of course based on Java and a number of other higher level languages. Every book on the subject I've read says so (which by now is a small handful), and the goal (aside from Microsoft dominating the world as usual) was to improve upon the basic premise of a virtual machine. They have been successful and the truth stands: the Unix world is cloning .NET because it is a superior technology for a certain class of language interop problem. It remains to be seen whether the *Windows Forms* part of .NET will be cloned successfully, or is desired by the Unix crowd. I'm referring mainly to the IL. Why bother to make another comment in passing? Because it's the truth, and I find it annoying to be labeled as trying to get people to "bite" on some advocacy debate when it's not my motive. If you want to debate the relevance or morality of it all, go talk to the Mono people. Right now, I don't care. I'm going to wait 4 years and then run .NET on Unix, picking up a residual and unimportant market of Linux gamers for very little effort. Sooner if things develop quicker. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From jnc at ecs.soton.ac.uk Wed Dec 10 11:04:41 2003 From: jnc at ecs.soton.ac.uk (John Carter) Date: Wed, 10 Dec 2003 16:04:41 +0000 Subject: Using PIL with py2exe Message-ID: Does anyone know how to embed PIL into a py2exe program. As far as I can tell PIL is not finding its plugins for Image I/O, they are imported dynamically as required. So I cant load or save pictures I tried making a copy of the plugin files to the application directory, but I've had no luck in making the code see the files I'd be grateful for any suggestion. Please e-mail me, as well as posting a reply. John Carter jnc at ecs.soton.ac.uk From adsl5lcq at tpg.com.au Sat Dec 20 18:15:15 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Sun, 21 Dec 2003 10:15:15 +1100 Subject: How to use a 5 or 6 bit integer in Python? References: <2u18uv8nosa821kptifdq1uei1t8koelsf@4ax.com> Message-ID: On 20 Dec 2003 18:35:31 GMT, bokr at oz.net (Bengt Richter) wrote: >> >Just to see if I understand your problem statement, does the following (though it's slow) >do what you are trying to do? Not exactly, although if you wc -l the result and then wrote down the number, then it would. I am only interested in the final result. >If so, what would be the point of generating >all those gray code sequences? IOW, how are you going to use them? Assuming my >prog generated all the 6-bit grey code seqences to a monster file, all the 64-number >sequences packed into 64-byte strings end to end, then you would either have to >read that file sequentially, or seek to some point and read 64 bytes to get a >given gray code sequence. If the latter, how about an algorithm that would >do a virtual seek into the whole data as a virtual file, and then generate >what you would read? I.e., there would be no point in storing all that data >if you could easily generate an arbitrary segment of it. Generating a single code of arbitrary digits is a relatively simple task; I am interested in generating the total *number*, not every code. Each of the codes I am generating also has (as one of the integers in it's data tuple) a `multiplicity' which is how many other Gray codes of that length are symmetrically equivalent. I am merely generating a very small subset which I can recombine (as a polynomial, say) and then work out how many there will be in total. >Of course, maybe that's >not so easy ;-) But I'm wonder what the use is going to be, and the access pattern, >if you assumed availability in a monster file, virtual or not. > Incidentally, I did try the method you have below. Almost identical I might add! It ran for around 3 weeks, and generated just over a million 5-digit Gray codes. For some interest, if G(n) represents the number of n-digit Gray codes then : G(1) = 2 G(2) = 8 (as you show below) G(3) = 144 G(4) = 91 392 G(5) = 187 499 658 240 (I can calculate this in under 8 hours) G(6) = ?? (but it's around 10^24) So if you allocate each code a minimal number of bits, storing every 5 or 6 digit BGC is a very different and much more impossible task than that which I am trying to achieve. >If you really do want to generate all that data, I suppose the loop and recursions >could be fanned out to parallel processing. But first, do I understand the problem? > >====< gray.py >========================================================= If instead of printing the successful code, or storing it, you simply incremented an internal counter, then yes that is exactly the problem I need to solve. For 6 digits. My representations and algorithm come from alot of theory that me and other associates have proven, although I can post it here or to your e-mail if you would like. I haven't included any of these tuples-as-strings speedups yet, as I'm working on integrating some new theory into the program, but comments would always be appreciated. It would be ironic if you did take me up on this, as I recently deleted all the comments from my code because I felt they were cluttering the code itself :). -- Glen From bwglitch at hotpop.com Fri Dec 5 13:46:48 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Fri, 05 Dec 2003 13:46:48 -0500 Subject: Python's simplicity philosophy In-Reply-To: References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: Douglas Alan wrote: > BW Glitch writes: > > >>Douglas Alan wrote: > > >>>C'mon -- to make robust programs you have to assume the worst-case >>>scenario for your data, not the best case. I certainly don't want >>>to write a program that runs quickly most of the time and then for >>>opaque reasons slows to a crawl occasionally. I want it to either >>>run quickly all of the time or run really slowly all of the time >>>(so that I can then figure out what is wrong and fix it). > > >>In theory, I'd agree with you Douglas. But IRL, I agree with >>Alex. If I have to choose between two algorithms that do almost the >>same, but one works on an special case (that's very common to my >>range) and the other works in general, I'd go with the special >>case. There is no compelling reason for getting into the trouble of >>a general approach if I can do it correctly with a simpler, special >>case. > > > When people assert that > > reduce(add, seq) > > is so much harder to use, read, or understand than > > sum(seq) > > I find myself incredulous. People are making such claims either > because they are sniffing the fumes of their own righteous argument, > or because they are living on a different planet from me. On my > planet, reduce() is trivial to understand and it often comes in handy. > I find it worrisome that a number of vocal people seem to be living on > another planet (or could use a bit of fresh air), since if they end up > having any significant influence on the future of Python, then, from > where I am standing, Python will be aimed at aliens. While this may > be fine and good for aliens, I really wish to use a language designed > for natives of my world. My question goes again, what is so difficult about sum()? You say you find yourself incredulous that people find reduce() much harder than sum(). It is not hard to see why. reduce() does not tell you anything about what is about to happen, despite your claims that it is easier. It doesn't offer any advantages over more readable ways of expressing it, namely loops. I'm already sick of you saying that reduce() is trivial. It took me well over a year to understand what it was for and I have yet to find any *good* use to it. My background? Started in TI Basic on my own, went to a course in C, learned C++, Matlab and Java on my own, then learned some Scheme/Prolog for a course and then I went to Python. I might not have the best background here (ie, Alex Martelli just outshines me in every single way), but I know my trade. As I said before, it seems to me that you only want people with your CS background to do the programming. > Reasonable people on my world typically seem to realize that sum() is > just not useful enough that it belongs being a built-in in a > general-purpose programming language that aims for simplicity. This > is why sum() occurs rather infrequently as a built-in in general > purpose programming languages. sum(), however, should be in the > dictionary as a quintessential example of the word "bloat". If you > agree that sum() should have been added to the language as a built-in, > then you want Python to be a bloated language, whether you think you > do, or not. It is arguable whether reduce() is useful enough that it > belongs as a built-in, but it has many more uses than sum(), and > therefore, there's a case for reduce() being a built-in. reduce() may > carry the weight of its inclusion, but sum() certainly does not. The question has come in this thread several times and it is still unanswered: show a case where reduce() _is_ the obvious way of doing something. I'm not asking for much, y'know... >>One example. I once wrote a small program for my graphic calculator to >>analyze (rather) simple electrical networks. To make the long story >>short, I had two approaches: implement Gaussian Elimination "purely" (no >>modifications to take into account some nasty problems) or implement it >>with scaled partial pivoting. Sure, the partial pivoting is _much_ >>better than no pivoting at all, but for the type of electrical networks >>I was going to analyze, there was no need to. All the fuzz about >>pivoting is to prevent a small value to wreck havoc in the calculations. >>In this *specific* case (electric networks with no dependent sources), >>it was impossible for this situation to ever happen. > > >>Results? Reliable results in the specific range of working, which is >>what I wanted. :D > > > You weren't designing a general purpose programming language -- you > were designing a tool to meet your own idiosyncratic needs, in which > case, you could have it tap dance and read Esperanto, but only on > second Tuesdays, if you wanted it to, and no one need second guess > you. But that's not the situation that we're talking about. Ah, but it is still related, y'know. The problem here was that I _could_ decide to make the app more sturdy by implementing Gaussian Elimination with scaled partial pivoting because it is the correct way of doing it. Also, it does happen that the elements in the diagonal in the admittance matrix is smaller than the sum of the non-diagonal elements of the corresponding row. This is the reason why scaled partial pivoting is used in the first place. There were lots of cases that happen in a circuit with frequency that I decided to ignore because they weren't relevant for what I needed (namely, dependent sourses). How does this ties to your statement on preparing for worst case scenario? Well, this ends up to be a design decision, because it might be irrelevant or difficult to prepare for it. Preparing something for worst case scenario is a Good Thing(tm) most of the time, but there are situations where it's your worst nightmare. If you do program with the worst case scenario every single time without giving thought to it, fine by me. But I like to make the desicion on how far should my software go. >>>>[Alex Martelli:] Me too! That's why I'd like to make SURE that >>>>some benighted soul cannot code: > > >>>> onebigstring = reduce(str.__add__, lotsofstrings) > > >>>The idea of aiming a language at trying to prevent people from >>>doing stupid things is just innane, if you ask me. It's not just >>>inane, it's offensive to my concept of human ability and >>>creativity. Let people make their mistakes, and then let them >>>learn from them. Make a programming language to be a fluid and >>>natural medium for expressing their concepts, not a straight-jacket >>>for citing canon in the orthodox manner. > > >>It's not about restraining someone from doing something. It's about >>making it possible to *read* the "f(.)+" code. > > > A language should make it *easy* to write readable code; it should not > strive to make it *impossible* to write unreadable code. There's no > way a language could succeed at that second goal anyway, and any > serious attemtps to accomplish that impossible goal would make a > langauge less expressive, more bloated, and would probably even end up > making the typical program less readable as a consequence of the > language being less expressive and more complex. IIRC again, readability and writability are in opposites. If you design a language to be highly readable, you're going to have a hell of a time writing it (ie, AppleScript, for example; note: it isn't that bad, just too wordy). Designing a language with high writability goes the other way (ie, Perl when used everything). So it's impossible to have it both ways, readable and writable. >>Human ability and creativity are not comprimised when restrictions >>are made. > > > That would depend on the restrictions that you make. Apparently you > would have me not use reduce(), which would compromise my ability to > code in the clear and readable way that I enjoy. Did you missed reduce() in C/C++/Assembly? >>In any case, try to program an MCU (micro-controller unit). Python's >>restrictions are nothing compared with what you have to deal in a >>MCU. > > > I'm not sure what point you have in mind. I have programmed MCU's, > but I certainly didn't do so because I felt that it was a particularly > good way to express the software I wished to compose. My point is that you are complaining about Python's restrictions. In a MCU, restrictions come in various ways. And there are times where programming an MCU is the best way to solve a problem. >>>Furthermore, by your argument, we have to get rid of loops, since >>>an obvious way of appending strings is: >>> result = "" >>> for s in strings: result += s > > >>By your logic, fly swatters should be banned because shotguns are >>more general. > > > That's not my logic at all. In the core of the language there should > be neither shotguns nor fly-swatters, but rather elegant, orthogonal > tools (like the ability to manufacture interchangable parts according > to specs) that allow one to easily build either shotguns or > fly-swatters. Perhaps you will notice, that neither "shotgun" nor > "fly-swatter" is a non-compound (i.e., built-in) word in the English > language. And which tool do you propose instead of shotguns and fly swatters? >>:S It's a matter of design decisions. Whatever the >>designer thinks is better, so be it (in this case, GvR). > > > Of course it is a matter of design decisions, but that doesn't imply > that all the of design decisions are being made correctly. Over all the time I've been doing design, I've learned that there's no bad design decision if it was reached in a logical way. Now, doing something just because is a bad design decision. >>At least, in my CS introductory class, one of the things we learned >>was that programming languages could be extremely easy to read, but >>very hard to write and vice versa > > > Or they can be made both easy to read *and* easy to write. That's impossible, my friend. >>>You are correct, sorry -- I misunderstood your proposed extension. >>>But max() and min() still have all the same problems as reduce(), and >>>so does sum(), since the programmer can provide his own comparison >>>and addition operations in a user-defined class, and therefore, he can >>>make precisely the same mistakes and abuses with sum(), min(), and >>>max() that he can with reduce(). > > >>It might still be abused, but not as much as reduce(). But >>considering the alternative (reduce(), namely), it's *much* better >>because it shifts the problem to someone else. We are consenting >>adults, y'know. > > > Yes, we're consenting adults, and we can all learn to use reduce() > properly, just as we can all learn to use class signatures properly. Sheez. >>>>So, you're claiming that ALL people who were defending 'reduce' by >>>>posting use cases which DID "abuse this generality" are >>>>unreasonable? > > >>>In this small regard, at least, yes. So, here reduce() has granted >>>them the opportunity to learn from their mistakes and become better >>>programmers. > > >>Then reduce() shouldn't be as general as it is in the first place. > > > By that reasoning, you would have to remove all the features from the > language that people often use incorrectly. And that would be, ummm, > *all* of them. My time to say I don't see your point. reduce() is way too general for its own good. Almost every other feature in the language is controlled in different ways, allowing flexibility and reducing side effects. >>>And Python suits me fine. But if it continues to be bloated with a >>>large number special-purpose features, rather than a small number of >>>general and expressive features, there may come a time when Python >>>will no longer suit me. > > >>reduce() ... expressive? LOL. I'll grant you it's (over)general, but >>expressive? Hardly. > > > You clearly have something different in mind by the word "expressive", > but I have no idea what. I can and do readily express things that I > wish to do with reduce(). For me, expressive is describing something that can other people can understand. The more expressive something is, the less "aftermath" explaining is needed. In out example at hand, if I have to explain one function everytime to everyone, and another just once in a while, the latter is more expressive than the former. >>It's not a bad thing, but, as Martelli noted, it is >>overgeneralized. Not everyone understand the concept off the bat (as >>you _love_ to claim) and not everyone find it useful. > > > If they don't find it useful, they don't have to use it. Many people > clearly like it, which is why it finds itself in many programming > languages. Please name mainstream languages that do have reduce(). >>What I understand for simplicity is that I should not memorize anything >>at all, if I read the code. > > > There's no way that you could make a programming langauge where you > don't have to memorize anything at all. That's ludicrous. To use any > programming language you have to spend time and effort to develop some > amount of expertise in it -- it's just a question of how much bang you > get for your learning and memorization buck. Obviously, some memorizing is needed. But I don't want to memorize every single feature just to know what a code is doing. >>That's one of the things I absolutely hate >>about LISP/Scheme. > > > You have to remember a hell of lot more to understand Python code than > you do to understand Scheme code. (This is okay, because Python does > more than Scheme.) You just haven't put in the same kind of effort > into Scheme that you put into Python. I tried, but the damn parenthesis just got in the way. Getting something as simple as adding an array the old fashioned way was painful. > For instance, no one could argue with a straight face that > > seq[1:] > > is easier to learn, remember, or read than > > (tail seq) And I won't. >>Now, what's so hard about sum()? > > > There's nothing hard about sum() -- it's just unneccessary bloat that > doesn't do enough to deserve being put into the language core. If we > put in sum() in the language core, why not quadratic_formula() and > newtons_method(), and play_chess()? I'd use all of those more > frequently that I would use sum(). The language core should only have > stuff that gives you a lot of bang for the buck. sum() doesn't. Not necessary. The ternary operator is quite specific (unless you start abusing it) to the situation and it is included in many languages. So the rule of the thumb generally is to put in the core what makes sense. Not all the general stuff, but what is useful. reduce() is everything *but* useful. It would be interesting to hear why sum() was included in the core, though. >>>That's because I believe that there should be little distinction >>>between features built into the language and the features that users >>>can add to it themselves. This is one of the primary benefits of >>>object-oriented languages -- they allow the user to add new data types >>>that are as facile to use as the built-in data types. > > >>_Then_ let them *build* new classes to use sum(), min(), max(), >>etc. These functionality is better suited for a class/object in an >>OO approach anyway, *not* a function. > > > No, making new classes is a heavy-weight kind of thing, and every > class you define in a program also should pay for its own weight. > Requiring the programer to define new classes to do very simple things > is a bad idea. sum(), min() and max() are "simple" things in the abstract. However, they depend on the object. So, in an OO language, these are better modeled _inside_ an object, which in Python's case is a class. >>>>and you claimed that reduce could be removed if add, mul, etc, would >>>>accept arbitrary numbers of arguments. This set of stances is not >>>>self-consistent. > > >>>Either solution is fine with me. I just don't think that addition >>>should be placed on a pedestal above other operations. This means that >>>you have to remember that addition is different from all the other >>>operations, and then when you want to multiply a bunch of numbers >>>together, or xor them together, for example, you use a different >>>idiom, and if you haven't remembered that addition has been placed on >>>this pedestal, you become frustrated when you can't find the >>>equivalent of sum() for multiplication or xor in the manual. > > >>Have you ever programmed in assembly? It's worth a look... > > > Yes, I have. And I've written MCU code for microcontrollers that I > designed and built myself out of adders and other TTL chips and lots > of little wires. I've even disassembled programs and patched the > binary to fix bugs for which I didn't have the source code. I think the reason addition is "above" all other operations is because every other operation can be defined with addition. But only substraction can be used to define addition, if the latter is not defined. >>(In case someone's wondering, addition is the only operation available >>in many MPU/MCUs. Multiplication is heavily expensive in those that >>support it.) > > > If your point is that high-level languages should be like extremely > low level languages, then I don't think that you will find many people > to agree with that. My point is that addition can be used to define the other operations. >>>>The point is that the primary meaning of "reduce" is "diminish", and >>>>when you're summing (positive:-) numbers you are not diminishing >>>>anything whatsoever > > >>>Of course you are: You are reducing a bunch of numbers down to one >>>number. > > >>That make sense if you are in a math related area. But for a layperson, >>that is nonsense. > > > It wasn't nonsene to me when I learned this in tenth grade -- it made > perfect sense. Was I some sort of math expert? Not that I recall, > unless you consider understanding algebra and geometry to be out of > the realm of the layperson. I am not talking about you, I'm talking about the average person. >>>Yes, I taught a seminar on Python, and I didn't feel it necessary >>>to teach either sum() or reduce(). I taught loops, and I feel >>>confident that by the time a student is ready for sum(), they are >>>ready for reduce(). > > >>But why didn't you teached reduce()? If it were so simple, it >>was a must in the seminar. > > > I did teach lamda in the seminar and no one seemed to have any > difficulty with it. I really couldn't fit in the entire language in > one three-hour seminar. There are lots of other things in the > language more important than reduce(), but *all* of them are more > important thhan sum(). > > >>Now in a more serious note, reduce() is not an easy concept to >>grasp. That's why many people don't want it in the language. The >>middle land obviously is to reduce the functionality of reduce(). > > > That's silly. Reducing the functionality of reduce() would make it > *harder* to explain, learn, and remember, because it would have to be > described by a bunch of special cases. As it is, reduce() is very > orthogonal and regular, which translates into conceptual simplicity. Not at all. If the functionality of reduce() is, well, reduced, it would make it easier to explain, as it would have some real connotation. As is, reduce() serves no purpose. >>You mention here "general-purpose programming". The other languages >>that I have done something more than a small code snippet (C/C++, Java >>and PHP) lack a reduce()-like function. > > Lots of languages don't provide reduce() and lots of languages do. Either lots of languages do, or lots of languages don't provide reduce(). This is a mutually exclusive. > Few > provide sum(). I agree. But its functionality can be easily implemented in most languages. > Higher-order functions such as reduce() are > problematic in statically typed langauges such as C, C++, or Java, > which may go a long way towards explaining why none of them include > it. Neither C, C++, or Java provide sum() either, though PHP provides > array_sum(). How difficult is it to implement the sum() functionality in either of these languages? How difficult is it to implement the reduce functionality? > But PHP has a huge number of built-in functions, and I > don't think that Python wishes to go in that direction. No, that's not the direction Python should take. However, built-in functions should be things that make sense (no reduce()). Or are you going to argue to eliminate the print statement, like in C? >>>You have to educate people not to do stupid things with loop and sum >>>too. I can't see this as much of an argument. > > >>After reading the whole message, how do you plan to do *that*? > > > You put a line in the manual saying "As a rule of thumb, reduce() > should only be passed functions that do not have side-effects." That would work in an ideal world. Please come to the real world. >>The only way to effectively do this is by warning the user >>explicitly *and* limiting the power the functionality has. > > Is this the only way to educate people not to abuse loops? > > I didn't think so. Me neither. But what other option is there for overgeneralized functions? >>As Martelli said, APL and Numeric does have an equivalent to >>reduce(), but it's limited to a range of functions. Doing so ensures >>that abuse can be contained. > > > Doing so would make the language harder to document, remember, and > implement. Not in my book. Limiting the power of reduce() will actually make it more useful. >>>You hardly need a zillion warnings. A couple examples will suffice. > > >>I'd rather have the warnings. It's much better than me saying "How >>funny, this shouldn't do this..." later. Why? Because you can't >>predict what people will actually do. Pretending that most people >>will act like you is insane. > > > If the day comes where Python starts telling me that I used reduce() > incorrectly (for code that I have that currently works fine), then > that is the last day that I would ever use Python. Very well. Your decision. >>Two last things: > > >>1) Do you have any extensive experience with C/C++? (By extensive, I >>mean a small-medium to medium project) > > > Yes, quite extensive. On large projects, in fact. > > >>These languages taught me the value of -Wall. There are way too many >>bugs lurking in the warnings to just ignore them. > > > I don't use C when I can avoid it because I much prefer C++. C++'s > strong static type-checking is very helpful in eliminating many bugs > before the code will even compile. I find -Wall to be useless in the > C++ compiler I typically use because it will complain about all sorts > of perfectly okay things. But that's okay, because usually once I get > a progam I write in C++ to compile, it typically has very few bugs. Strange. In my case, the -Wall saved me from a *lot* of mistakes in that otherwise would have taken me a lot of time to discover. >>2) Do you have any experience in the design process? > > > Yes, I design and implement software for a living. I was under the impression you didn't had any. And I still do. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- Strike when the enemy isn't looking. -- Skywarp (G1) From max at alcyone.com Thu Dec 25 23:21:09 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 25 Dec 2003 20:21:09 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: <3FEBB735.D7CCE6A@alcyone.com> "Brandon J. Van Every" wrote: > "Tom Plunket" wrote: > > > Good luck. You haven't made any money yet, right? It's been > > five years? > > Almost six. And I'm still doing what I want to do, so that should > tell you > something. In those six years you haven't managed to produce anything, so I'm not exactly sure what that's supposed to tell us. (Plus, it's useful information to know that, by your own admission, before those five years started when you left your first and only job ever in the computer industry, which lasted only two years.) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I'm sharing the joy / I'm glowing like sunshine -- Chante Moore From exarkun at intarweb.us Sun Dec 21 23:26:57 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 21 Dec 2003 23:26:57 -0500 Subject: memory overhead using from-import? In-Reply-To: <20031221201600.58a92a9a.wtrenker@shaw.ca> References: <20031221102848.4f901801.wtrenker@shaw.ca> <3FE62032.619D0D46@alcyone.com> <20031221201600.58a92a9a.wtrenker@shaw.ca> Message-ID: <20031222042657.GA20640@intarweb.us> On Sun, Dec 21, 2003 at 08:16:00PM +0000, William Trenker wrote: > Bengt Richter wrote: > > > I think to extract an > > "independent" function or class etc. without all the entanglements would > > require source processing, and extracting only what was necessary to support > > the thing to be extracted. > > Yes, it looks like you're right. There was talk, at one time, of being > able to import modules from a zip file. If that was possible then maybe > it would be more efficient if all the independent utility functions in the > python library were grouped together as a collection of little modules > distributed in such a zip file. Then only the overhead of each small, > independent function would be incurred when such a utility function was > imported. Err... This was implemented. I definitely don't see the point of giving every function its own module. I think you should step back for a moment and consider exactly what and why you want to optimize. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rmunn at pobox.com Fri Dec 26 17:58:08 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 26 Dec 2003 22:58:08 GMT Subject: dynamic typing question References: <8ef9bea6.0312261227.56ade9a9@posting.google.com> Message-ID: <423Hb.15499$aw2.8655963@newssrv26.news.prodigy.com> Hung Jung Lu wrote: > claird at lairds.com (Cameron Laird) wrote in message news:... >> 1. Why, in your mind or your teammate's, >> is dynamic typing a "lack"? What, pre- >> cisely, is the benefit of static typing? >> There are a number of legitimate >> answers. It occurs to me that, without >> precision on which interest you, we >> might be missing an opportunity to >> clarify "The Python Way" significantly. > > One static typing advantage I've run into: > > When you change the name of a variable in a class, and re-compile the > program, the compiler shows you ALL places where compilation fails. > These could be hundreds of places in dozens of files. In dynamically > typed language like Python, you have to rely on text search, which > often yields many false positives, especially for common/overloaded > names like .count, .name, .type, etc. In statically-typed languages, > making name changes is not very painful, since the compiler will tell > you where exactly you need to follow up with the changes. In > dynamically typed language, you will have to manually write unit test > codes to ensure name consistency. > > I am sure Python people have come up with strategies to deal with this > problem. That's what I'd like to hear. (Unit test is one route.) But > this is one place where I've found statically-typed compilers useful. > I mean, I have seen this discussion many times, but most responses > from Python users have not been realistic (often simply shrugging off > the problem and saying something like "compilers don't detect all the > bugs, blah blah blah".) I would like to hear more real-life experience > rather than academic conjectures. That sounds like exactly the sort of problem that the Bicycle Repair Man project (http://sourceforge.net/projects/bicyclerepair/) is intended to solve. It's a refactoring browser for Python code. Caveat: I've not actually used Bicycle Repair Man myself, so I don't know if there are any hidden gotchas. But I've heard very good things about it from other people. The name "Bicycle Repair Man", BTW, is a reference to a Monty Python skit involving a superhero whose special power was repairing bicycles. -- Robin Munn rmunn at pobox.com From xnews2 at fredp.lautre.net Wed Dec 24 05:41:59 2003 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 24 Dec 2003 10:41:59 GMT Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> <7xr7yvjle5.fsf@ruckus.brouhaha.com> <21bb8d55.0312240144.4eb9caab@posting.google.com> <7xk74mik64.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin said : >> Even if it was limited i/o traffic I am not sure how to do profiling > > A crude but maybe useful thing you can do is just observe the CPU load > while the program is running. If the CPU load is low but you hear the > disk banging around, you're i/o bound. I love this one. It would make a great intro quote for the next DrDobbs weekly summary ! ;-) -- YAFAP : http://www.multimania.com/fredp/ From jepler at unpythonic.net Mon Dec 29 14:17:44 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Dec 2003 13:17:44 -0600 Subject: Results from os.system() different from execution at prompt In-Reply-To: <1t16c1-b37.ln1@valpo.de> References: <1t16c1-b37.ln1@valpo.de> Message-ID: <20031229191744.GJ6171@unpythonic.net> On Mon, Dec 29, 2003 at 05:38:25PM +0100, Mathias Waack wrote: > Enno Middelberg wrote: > > So, the Python-executed mpeg_encode reports fewer input files. Any > > clues why this could happen? Is there a limit on the command length > > or so? > > Why do you think the reason for this behaviour could be truncated > command line? You just call 'mpeg_encode mpeg.par', this line > shouldn't be too long neither for python nor for the shell. ... and a commandline that is too long should cause a non-zero return status, not run the program with an incorrect argument list: >>> os.system("true x") 0 >>> os.system("true " + "x" * 320000) 32512 From sombDELETE at pobox.ru Thu Dec 25 15:11:11 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Thu, 25 Dec 2003 23:11:11 +0300 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> <3014031e.0312242351.d2604c2@posting.google.com> Message-ID: "Ahmad" wrote in message news:3014031e.0312242351.d2604c2 at posting.google.com... > Hi all, > > I just wanted to tell everyone here, that none of the tips really > worked. The RTLstreamer class seemed so messed up, and printing > "\u200F" before my text didn't make any difference!! I can't beleive > that after all this time, unicode and bidi support still isn't working > nicely :( > > OTOH, I tried pyGtk, the text is automatically RTL, (nice) but still > the first character in the scentence isn't showing. > > Any other tricks? You can try to make a web application if it's possible. I bet major browsers support bidi well. You can also look at Mozilla as your cross platform display and input engine. -- Serge. From Greg.Lindstrom at acxiom.com Wed Dec 17 12:02:56 2003 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Wed, 17 Dec 2003 11:02:56 -0600 Subject: Microsoft SQL Server & python Message-ID: Is it possible to connect my python to Microsoft's SQL server? Can anyone point me in the right direction? I'm on a windows 2000 "professional" box connection to SQL Server 6.0. Thanks! ********************************************************************** The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not 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 re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From paulpaterson at users.sourceforge.net Tue Dec 23 00:52:27 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Tue, 23 Dec 2003 05:52:27 GMT Subject: Problem mapping VB com code to Python References: <4f55e45a.0312191451.73b8f84b@posting.google.com> Message-ID: > "max" wrote in message > news:4f55e45a.0312191451.73b8f84b at posting.google.com... > > I am trying to use a sdk to access quickbooks, the sdk provided a COM > > interface and I think it installed the com server files/dlls. A VB > > code example is provided, but I can't figure out how to map "Dim > > sessionManager As New QBFC2_1Lib.QBSessionManager" > > into a corresponding Python statement, when I try > > obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get > > traceback Shown below. > > > > I have been able to run makepy and it generates a lovely file. I can > > find a Type Library, but need a little help mapping this to be able to > > access the com object and call its methods. > > > > I have included a snipit of the sample VB code and the traceback from > > my attempt to create a client com object ? > > > > Any help much appreciated, > > > > max > > > > > > > > =======Traceback ============= > > >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > > line 95, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 84, in _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 72, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147221005, 'Invalid class string', None, None) > I had a similar problem with a different library that would early bind in VB but wouldn't work with win32com.client.Dispatch. IIRC I got around it by hunting in the registry with regedit for likely looking class ID's ("SomeLibrary.SomeObject"). It is also possible that the VBP file will contain the GUID which you can then use in a registry search to find a class ID. It may be a shot in the dark but in my case when the VB code was, Dim S As MYLIB.Server Set S = MYLIB.DefaultServer the corresponding Python ended up being, c = win32com.client.Dispatch("MYLIB.MYLIB") s = c.DefaultServer I'm not sure if this will work in your case but I think if you search the registry for "QBFC" you might turn something up. Paul From peter at engcorp.com Wed Dec 10 09:30:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Dec 2003 09:30:13 -0500 Subject: About the use of **args References: Message-ID: <3FD72DF5.E5DD071C@engcorp.com> Jacek Generowicz wrote: > > Duncan Booth writes: > > > Mark McEahern wrote in > > news:mailman.27.1071059861.9307.python-list at python.org: > > > > > # We can still access the "private" member variable. In Python, > > > # private is merely a convention. > > > print s._size > > > > Except that in Python the convention for private variables is to begin them > > with two underscore characters, and then it is more than just a convention: > > Now, I always believed that "private" in Python is spelt "_", while > "mangle this name for me because I want to avoid name clashes in > multiple inheritance scenarios" is spelt "__". > > However, I've heard _so_ many people make the (in my opinion > incorrect) claim that "private" is spelt "__", that I'm beginning to > question my sanity. Distinguish "private" and "protected", as in C++ and perhaps wider usage. "private" is spelled __ in Python and is supported in a limited fashion by the language, while *protected* is spelled _ and is by convention. -Peter From castor at snafu.de Wed Dec 31 10:16:43 2003 From: castor at snafu.de (wolf) Date: 31 Dec 2003 07:16:43 -0800 Subject: position in a for loop? References: Message-ID: <6fa5f178.0312310716.15b0f061@posting.google.com> you may want to have a look @ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297, where it is said that 'the interpreter creates a secret name that only exists while the list is being built. That name is (usually) "_[1]", and it refers to the bound method "append" of the list.'. for your specific problem, the enumerate() solution is probably all that you need; for other cases (such as checking whether a certain value is already a member of the list), this solution may come in handy. for example, in order to get a non-repetitive string with all the characters found in a given text, you could say print ''.join( [ x for x in 'my words are repetitive' if x not in locals()['_[1]'].__self__ ] ) hope that helps, _wolf From max at cNvOiSsiPoAnMtech.com Wed Dec 31 14:27:41 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Wed, 31 Dec 2003 19:27:41 GMT Subject: Python Job Market In-Reply-To: References: Message-ID: > It's funny to sit in on a sales call because now even our sales guys "brag" > that Python-based technology is part of our competitive advantage as if it's > our secret sauce or something, whereas initially it was more "Shh, lest people > find our we're using some weird scripting language". :) > > HTH, > Dave Paul Graham has a parallel article proclaiming that LISP was his competitive advantage (building viaweb ant selling it to Yahoo). http://www.paulgraham.com/avg.html nice plug for python there, 2 From eppstein at ics.uci.edu Fri Dec 5 00:45:23 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 04 Dec 2003 21:45:23 -0800 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: In article <7x7k1b4yqn.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Try this with a list: > > a = [1, 2, 3, 4, 5] > a[3] = 27 > print a > > Then try it with a tuple. That's true, but another answer is: you should use tuples for short sequences of diverse items (like the arguments to a function). You should use lists for longer sequences of similar items. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From zunbeltz at wm.lc.ehu.es.XXX Wed Dec 3 07:35:30 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 03 Dec 2003 13:35:30 +0100 Subject: SUSPECT: Re: Python, xml, databases, ... References: Message-ID: Pieter Claerhout writes: > SQLite is easier to embed since you don't need to install anything > seperately. Include the neccesary Python modules and shared libraries, and > you can create databases. With Firebird, MySQL and PostgreSQL, you need to > install separate software. If I'm not mistaking, performance wise, SQLite > will be faster, but I'm not sure how it handles large databases (let's say > 100 MB or more). > Thanks for the coment. I think my db will no be as large as 100MB, so i would try SQLite (at less read some documenteation :-) Zunbeltz -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From reply.in.the.newsgroup at my.address.is.invalid Thu Dec 25 15:06:38 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 25 Dec 2003 21:06:38 +0100 Subject: How does "delegation" work as per the FAQ? References: Message-ID: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> Ville Vainio: >Rene Pijlman: >> __getattr__: "Called when an attribute lookup has not found the attribute >> in the usual places". There is no mention of method calls. > >A method is an attribute. I see. But how are the arguments of a method call passed on, when delegation is implemented this way? -- Ren? Pijlman From ajsiegel at optonline.com Mon Dec 8 09:04:52 2003 From: ajsiegel at optonline.com (Arthur) Date: Mon, 08 Dec 2003 14:04:52 GMT Subject: Humpty Dumpty (was Re: Lists and Tuples) References: Message-ID: <2t09tv0skr1i52c53frt1ali3qj8cg906b@4ax.com> On 7 Dec 2003 11:02:38 -0500, aahz at pythoncraft.com (Aahz) wrote: >In article , >Fredrik Lundh wrote: >>Arthur wrote: >>> >>> "Type" is not normally an ambiguous word. >> >>really? in my experience, "type" and "object" are about as ambiguous >>as words can get, especially when you're talking about Python. I actually see the point also, with direct relevance to Lists and Tuple tutorial semantics, to the extent that I am confused whether instances of different classes are of the same "type". I have considered no. By inheriting from object and creating something new from it I am creating a custom type. I thought. I think this impression comes from my little experinece with other languages. And since the way I use lists are to group instances of different classes, which may have nothing in common other than a single method of the same name, I have considered my lists to be of heterogenous type. Which is why I have been confused by the language to describe the prototypical use of lists. Art > >Hrm. I see your point, but I also think it's fairly easy to get people >to agree on definitions for "type" and "object" within the context of a >discussion. From my POV, the ambiguity comes from layering on additional >meanings beyond that supported by the C API. From duncan-news at grisby.org Mon Dec 1 05:22:01 2003 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 01 Dec 2003 10:22:01 +0000 Subject: omniORB 4.0.3 and omniORBpy 2.3 available References: <466c2$3fc32080$51604868$12088@nf2.news-service.com> <15235$3fc7292f$51604868$25838@nf2.news-service.com> Message-ID: In article , RCS wrote: >> First, as another poster suggested, make sure you have nothing to do >> with omniORB on your path before you try the new compile. > >I did that, and tough luck, the same unresolved 632 external symbols. Just to check, are you using the source tarball, or the pre-compiled Win32 binary .zip file? You should not use the binary .zip since that is compiled with VC++ 6, and will conflict with VC++ 7. >> If that still fails, please subscribe to the omniORB mailing list, and >> post details of the missing symbols to there. > >Well, I have tried earlier to post to the mailing lists, but what I always >get as a response is this: > >"Your mail to 'omniORB-list' with the subject > >Is being held until the list moderator can review it for approval. >The reason it is being held: > Post by non-member to a members-only list" > >and some time later I recieve an email that the message was not accepted due >to my not being a member, even if I have registered as a member (and recieve >mails every day from the list). I see you have sorted it out now, but for anyone else, the cause of this is always that you have subscribed from one email address but are trying to post from another address. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From jjl at pobox.com Mon Dec 29 18:45:56 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Dec 2003 23:45:56 +0000 Subject: argument list References: Message-ID: <87pte7i3wr.fsf@pobox.com> "Phil Hornby" writes: [...] > and would rather avoid having to call a script to check a script. [...] Why? Unless you plan on messing up calling of Python code from C, there's no problem calling inspect from C. The risks you're trying to mitigate aren't to do with Python itself, but with the particular handlers you're dealing with (though I don't know enough about your application to know exactly what you need to do in response to your inspect-ions). John From max at alcyone.com Wed Dec 24 18:23:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 24 Dec 2003 15:23:51 -0800 Subject: ungetch in Python References: Message-ID: <3FEA2007.363FCAC5@alcyone.com> Scott Fenton wrote: > I'm writing a small parser for a minilanguage in Python, > and I was wondering --- is there any equiv. of C's ungetch > or Scheme's peek-char in python? That is, is there a way to > look at a character without taking it off of the input stream > or is there a way to put it back on the input stream afterwards? > I googled around and didn't come up with anything that didn't > involve curses, which I don't want to use. Any help? Not internally but it's awfully easy to write a wrapper around a file class which does this. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Conversation is the enemy of good wine and food. -- Alfred Hitchcock From adsl5lcq at tpg.com.au Fri Dec 19 02:26:22 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Fri, 19 Dec 2003 18:26:22 +1100 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: <4h95uvg1jpbt1psdon9m4ov7tbc79d586g@4ax.com> On Fri, 19 Dec 2003 06:27:59 GMT, "Rainer Deyke" wrote: >Glen Wheeler wrote: >> I have one constantly changing dict with many millions of keys >> (tuples of ints) which in turn associates itself with a tuple of ints >> and two more dicts. > >That makes things a bit harder. I expect that the big dict itself requires >at least sixteen bytes per entry. How big are your tuples? The key tuples, for the final calculation will range from 1 element to 64 elements, with the majority at around 40-50 elements in size. > How big are the dicts in the data tuples? What data do they contain? For the first dict: Increasingly smaller as the calculation continues (i.e. as the key for that entry increases). Initially they will have 64 keys (integers) with each integer having a 6-element tuple of integers as it's data type. All integers are from 0-63. For the second dict: Trivially small, with a maximum of 32 elements, starts at 0 and an average of around 7. Keys are kept as integers from 0-63 and data ranges from -1-30, but the average case will see the data at 7, as a single integer. > Are any of the tuples or dicts shared? > Unfortunately, no. This would be a major speedup for my program as copying the dictionaries and tuples takes not only alot of memory but alot of time too. But the truth is that I need these to be unique on a key-by-key basis (context from the big dict) so I can't see any way around it. >Encoding the key tuples as strings is easy (''.join([chr(x) for x in >the_tuple]). Encoding the ints in the data tuples is just as easy. I'm not >sure if those are enough to solve your problem. I'll be sure to do this. Will it increase the hash speed for the big dictionary significantly? Will lookup times or memory storage requirements decrease? Thanks, Glen From jan at jandecaluwe.com Wed Dec 10 13:11:54 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 10 Dec 2003 19:11:54 +0100 Subject: cell object dereferencing In-Reply-To: References: <3FD5FD4A.9060406@jandecaluwe.com> <3FD6EA60.2000905@jandecaluwe.com> Message-ID: <3FD761EA.6070407@jandecaluwe.com> Terry Reedy wrote: > "Jan Decaluwe" wrote in message > news:3FD6EA60.2000905 at jandecaluwe.com... > >>Jan Decaluwe wrote: >> >>>Is there a way to dereference a cell object (that is, get >>>the object that it references to) in Python? >> >>I got the following response from Samuele Pedroni.: > > >>well you can ... use this hack (it's a huge hack but it is safe and does > > the trick): > > >>def proto_acc(v=None): >> def acc(): >> return v >> return acc >>acc0 = proto_acc() > > >>import new >>make_acc = lambda cell: (new.function > > (acc0.func_code,acc0.func_globals,'#cell_acc',acc0.func_defaults,(cell,))) > >>def cell_deref(cell): >> return make_acc(cell)() > > > Cute, Samuele. If function.func_closure were writable (which it is not) > then I believe the last four lines could be condensed as the more readable > > def cell_deref(cell): > acc0.func_closure = (cell,) > return acc0() > > but since it is not, you instead make a new function that is a near copy of > acc0 but with (cell,) substituted as *its* func_closure. Aha, *that's* what the last argument is: func_closure. For those interested, this is not yet in the documentation of module new, but it is documented in new.function.__doc__. Thanks a lot for this hack, it looks just what I need. I even start to understand it, I believe. (Next thing I would like to understand is how the hell you came up with this!) Regards, Jan -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From dwelch91.nospam at comcast.net Mon Dec 22 15:00:08 2003 From: dwelch91.nospam at comcast.net (djw) Date: Mon, 22 Dec 2003 20:00:08 GMT Subject: HTML data extraction? In-Reply-To: References: Message-ID: I don't know if there is anything at a higher level (I guess a Google session would tell you that), but doing what you describe with the HTMLParser module is very straightforward. All you have to do is keep some state flags in the derived HTMLParser class that indicate the found/not-found state of what you are looking for and have that control the collection of data between the flags. Starting with the example in the docs, and adding some (untested) additions: from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def __init__( self ): HTMLParser.__init__( self ) self.in_bold_tag = False self.in_list_tag = False self.data_in_bold_list = '' def handle_starttag(self, tag, attrs): print "Encountered the beginning of a %s tag" % tag if tag == 'b': self.in_bold_tag = True if tag == 'li' : self.in_list_tag = True def handle_endtag(self, tag): print "Encountered the end of a %s tag" % tag if tag == 'b': self.in_bold_tag = False if tag == 'li' : self.in_list_tag = False def handle_data( self, data ): if self.in_bold_tag and self.in_list_tag: self.data_in_bold_list = ''.join( [ self.data_in_bold_list, data ] ) This is just an outline, but you get the idea... -Don Dave Kuhlman wrote: > I recently read an article by Jon Udell about extracting data from > Web pages as a poor person's Web services. So, I have a question: > > Is there any Python support for finding and extracting information > from HTML documents. > > I'd like something that would do things like the following: > > - return the data which is inside a tag which is inside a >
  • tag. > > - return the data which is inside a tag that has attribute > href="http://www.python.org". > > - Etc. > > It would be a sort of structured grep for HTML. > > I've found the HTMLParser and htmllib modules in the Python > standard library, but I'm wondering if there is anything at a > higher level. > > Web searches did not turn up anything interesting. > > Thanks for help. > > Dave > From birdiepageANTI at SPAMciudad.FILTERcom.ar Sun Dec 7 13:20:16 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Sun, 07 Dec 2003 15:20:16 -0300 Subject: Why Python won't work on .net In-Reply-To: <20031207112217.14343.00000306@mb-m14.aol.com> References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: Allenabethea wrote: > I am a new python tinkerer. I love the language. But what is its future but as > a legacy tool? > > allen As far as I've learned so far, .net is good for client server but not that great for standalone because of the need for the .net runtime to run things, which creates a large overhead. Performance is an issue too, as everything compiles JIT. I think that's why although .net is a great idea, a lot of languages will remain language of choice for standalone/no runtimes/speed critical/cross platform aplications. I could be wrong, but I don't think I'm far from the truth. Gustavo Campanelli From hans at zephyrfalcon.org Wed Dec 17 19:27:35 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 17 Dec 2003 19:27:35 -0500 Subject: Save the pythons. In-Reply-To: References: Message-ID: <3FE0F477.3000601@zephyrfalcon.org> f29 wrote: > I don't believe that noone has yet spotted that python is becoming > java. Each new version is fully equipped with more garbage than > before. A bit harsh to put it that way, but yeah, the language is growing, as most languages tend to do. It would be nice to see it shrink sometime, although that would have its own set of drawbacks, like breaking backward compatibility. Maybe in Python 3.0... > Classes are great, but once there are 1000 of them, inheriting > from each other, I cannot avoid comparing this unpleasant situation to > java. Python's standard library hasn't quite reached the size of Java's, though. > Python power is in it's syntax, not addons. Hmm, everything else being equal, I'd much rather see a new module than yet another addition to the syntax. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From paul at boddie.net Wed Dec 17 06:16:43 2003 From: paul at boddie.net (Paul Boddie) Date: 17 Dec 2003 03:16:43 -0800 Subject: A GUI toolkit for Python that is NOT x-windows dependent References: <88f9e356.0312162305.58718893@posting.google.com> Message-ID: <23891c90.0312170316.6f4958ce@posting.google.com> andreb at warpmail.net (Andre Brightway) wrote in message news:<88f9e356.0312162305.58718893 at posting.google.com>... > Does anybody know of a GUI toolkit (or a way to draw to the screen) that can be > used from Python script in Linux without having to run X-Windows? If SDL has good enough support for framebuffers, you might be able to use Pygame to do what you want. See http://www.pygame.org and http://www.libsdl.org for details. Paul From mesteve_b at hotmail.com Sat Dec 6 19:54:06 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 07 Dec 2003 00:54:06 GMT Subject: finding python modules Message-ID: Guys, Very beginner question. I'm importing xml.dom.minidom at the top of my file. I'm trying to figure out where the heck this is. According to Quick Python, there should be folders on my drive (using XP), under c:\python23, named xml, then underneath: dom, etc. But there isn't. I know that xml.dom.minidom is not built into sys.built_module_names, cuz I viewed this variable under IDLE. Could you tell me how Python finds this hierarchy? ( the reason for this knowledge is to figure out how to add XML_Objectify to my path, but I'm trying to do it myself) Thank you Steve From jay at jaydorsey.com Mon Dec 22 13:17:31 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Mon, 22 Dec 2003 12:17:31 -0600 Subject: Count Files in a Directory In-Reply-To: References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: <20031222181731.GA25813@gentoo.Earthlink.net> On Mon, Dec 22, 2003 at 12:41:03PM -0500, hokieghal99 wrote: > Woops... I spoke too soon. Just caught this difference on 4.4GB of data. > The os thinks there are 12,204 objects in the path while Python > thinks there are 12,205 objects. What command are you using to find out how many objects are in the path? Also, what order to you run the commands in--maybe there *are* 12,205 objects in the path when you run the Python script. Maybe a tmp file is being created, or processes are occuring that add and remove files on the system. If you could check a non-system path (one where the OS wont' read/write to) with large amounts of data that would probably be best. What OS is this, and whats the path that you pass in to your function? -- Jay Dorsey jay at jaydorsey dot com From http Mon Dec 22 20:35:24 2003 From: http (Paul Rubin) Date: 22 Dec 2003 17:35:24 -0800 Subject: return statement in functions References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: <7x3cbcpb8j.fsf@ruckus.brouhaha.com> hokiegal99 at hotmail.com (hokiegal99) writes: > I was told earlier (w/o explanation) that functions should return > something. I was under the impression that it was OK with Python to > leave the return statement off. Could someone enlighten me on why or > why not to use a return statement when defining functions? Below is > the bit of code I was told should return something: It will return None. From newsgroups at jhrothjr.com Tue Dec 23 07:02:23 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Dec 2003 07:02:23 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Francis Avila" wrote in message news:vufdk79q4g4i8a at corp.supernews.com... > > Of course, the typical Ruby accusation against Python is that it (Ruby) is > "purer OO". I don't know what they mean by "purer". I suspect they are objecting to the use of built-in functions, and the use of functions in modules. Ruby uses methods for everything, and everything inherits from a base object that has a huge number of methods. Python is simply not going to go down that path. Personally, I don't have any opinion about which is better, both styles work. The other possibility is the pervasive use of the visitor pattern rather than Python's use of for statements for iterations. This, combined with the ease of creating anonymous functions, does seem to make a significant difference - at least it's what most Ruby afficianados talk about when they say what they like about the language. > If they mean the > fundamental types not being subclassable, that's an old wart that's very > nearly gone. Otherwise, I don't know what they could possibly mean, > considering absolutely everything in Python is an objects upon objects upon > objects. A class is an object, the methods of an instantiated class are > objects, the function a method wraps is an objects, the code of the function > is an object.... I think about the only thing that is not an object in > Python is a name, and I can't think how *that* would work. Interesting question, especially since it does seem to come up every few months. Technically, since names are simply keys in dictionaries, they *are* objects. I think the descriptor facility is a start on addressing that question, though. Rather than asking how it would work (the obvious answer is a different dictionary implementation for use in objects) it might be better to ask what you would use it for. John Roth > > -- > Francis Avila > From gerrit at nl.linux.org Mon Dec 29 04:19:02 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 29 Dec 2003 10:19:02 +0100 Subject: ftplib storbinary with timeout on windows Message-ID: <20031229091902.GA2715@nl.linux.org> Hello, I am trying to upload a set of files to a ftp server from Windows. Unfortunately, the ftp server is not very reliable, and sometimes the connection seems to hang. A possible solution would be using a timeout, specified before I try to upload the file. Under Windows, this can't be done with signal.alarm, because it is unavailable. Am I looking for ayncore or asynchat? Or is there a different, easier solution? How would I use it in combination with FTPlib? Using an external library is fine, but I am not very much of a windows guy, so a crossplatform solution would be much preferred. kind regards, Gerrit Holl. -- 267. If the herdsman overlook something, and an accident happen in the stable, then the herdsman is at fault for the accident which he has caused in the stable, and he must compensate the owner for the cattle or sheep. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From noemail at noemail4u.com Tue Dec 23 09:49:41 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Tue, 23 Dec 2003 14:49:41 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: <3fe7554d$0$1156$636a55ce@news.free.fr> Message-ID: On Mon, 22 Dec 2003 16:20:09 -0500, "John Roth" wrote: > >"Bruno Desthuilliers" wrote in message >news:3fe7554d$0$1156$636a55ce at news.free.fr... >> John Roth wrote: >> (snip) >> > >> > If a language makes opportunities for errors, then there is >> > something wrong with the language that needs to be corrected. >> >> Lol ! Tell us when you'll find a language that do not "make >> opportunities for errors". > >The non-existance of an example doesn't mean it isn't a >goal worth striving for. > >John Roth >> > I think Niklaus Wirth owes you a lollipop. --dang From andrew at exit66.com Thu Dec 11 13:36:11 2003 From: andrew at exit66.com (Andrew Barilla) Date: 11 Dec 2003 10:36:11 -0800 Subject: python vs php for web programming References: <425cc8d1.0312110636.56be9ecf@posting.google.com> Message-ID: mir4uu at yahoo.com (mir nazim) wrote in message news:<425cc8d1.0312110636.56be9ecf at posting.google.com>... > i m currently using PHP with Apache (a.k.a 'mod_php') for my web > development work. i came to know that python can also be used to do > web programming using 'mod_python' for Apache. i wanted to know the > difference between th two 'mod_php' and 'mod_python' in terms of: > > 1. speed of execution. > 2. productivity > 3. maintainance > (i know python is most productive and maintainable language in the > world, but is it same for web programming with Apache). > 4. availability of features e.g, cookies and session hadling, > databases, protocols, etc. > > I also wanted to know about Zope and comparison of its proformance, > features, etc. with Apache. I think mod_python is more comparable to mod_perl from what I've seen in terms of how you interact with the webserver. Instead of mod_python though, I'm doing my web programming with Webware (http://webware.sourceforge.net/), SQLObject (http://www.sqlobject.org/) and FormKit (http://dalchemy.com/python/formkit/). Compared to php I can code in about 1/4 of the time. And I've actually been programming longer in php than I have been in python. This combination is extremely powerful and most importantly I can take advantage of existing python code I have from a desktop application. Both mod_python and webware have cookies and session handling. Database access is through any available Python library such as mysqldb (http://sourceforge.net/projects/mysql-python). Not sure what protocols you're looking for but since you can use any python code that's out there, I'm sure you'll find everything you'll need. I played around with Zope until I tried to utilize Python code that I've already written and then moved on. From hwlgw at hotmail.com Wed Dec 31 03:51:48 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 31 Dec 2003 00:51:48 -0800 Subject: Project dream References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> Message-ID: > [Paul Rubin] > > [Christian Tismer] > > I would like to provide some ideas which I'm carrying around since > > quite some time. My reluctance is about the fact that I almost never > > saw an announcement like this being a serious offer. Most of the > > time it was just some sugar spread around to make people excited, > > creating lengthy threads with no result. How serious are you about > > spending a reasonable amount for a really innovative application in > > Python. I'm a bit curious since none of my google hits reach beyond 2003. > > I don't see any bad consequences of posting interesting ideas for projects, > even if nobody takes them up. I was not looking for a job! I was just thinking about a project to work on in my spare time, to sharpen my Python skills and because it is fun. I already have a job (with some Python programming). But um, Christian: what is that "really innovative application" you mention? Something stackless? Or can't you share the idea because you don't want others to start working on it? From fredrik at pythonware.com Thu Dec 18 04:29:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Dec 2003 10:29:07 +0100 Subject: is file open? References: Message-ID: Maxim Khesin wrote: > I have a script that processes a file generated by another program. I > need an unumbiguous way to know that the file has been written and > closed by the other program, at least on Windoze. I am thinking of doing > > def CanOpen(fname): > try: > f = open(fname, 'a') > f.close() > return True > except IOError: > return False > > should this work OK? why not try it out: >>> f = open("foo", "w") >>> g = open("foo", "a") >>> # do you see an exception? many Windows programs lock the file, but it's no requirement. As usual, the only unambigous way to make sure that another program are done writing to the file is to have the other program use a temporary name and rename when done. A reasonable workaround is to check the mtime, and only read the file if the mtime is old enough. if time.time() - os.path.getmtime(filename) >= LIMIT: ... From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 30 12:30:56 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Dec 2003 18:30:56 +0100 Subject: 'inverting' a dict Message-ID: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Hi I have this dict that maps a name to a sequence of other names. I want to have it reversed, i.e., map the other names each to the key they belong to (yes, the other names are unique and they only occur once). Like this: { "key1": ("value1", "value2"), "key2": ("value3,) } --> { "value1": "key1", "value2": "key1", "value3": "key2" } What I'm doing is using a nested loop: dict2={} for (key,value) in dict1.items(): for name in value: dict2[name] = key which is simple enough, but I'm hearing this little voice in the back of my head saying "there's a simpler solution". Is there? What is it? ;-) Thanks --Irmen. From jeffplus at comcast.net Tue Dec 16 20:51:31 2003 From: jeffplus at comcast.net (Jeff Schwab) Date: Tue, 16 Dec 2003 20:51:31 -0500 Subject: I see advice on how to debug a python module that hangs up the process In-Reply-To: References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: Bengt Richter wrote: >>Then, we have to do a "kill -9" the process. Did you try it without -9? From exarkun at intarweb.us Tue Dec 30 22:57:18 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 30 Dec 2003 22:57:18 -0500 Subject: selecting a random item from a set In-Reply-To: References: <3FF20AA3.7080603@v.loewis.de> Message-ID: <20031231035718.GA16141@intarweb.us> On Wed, Dec 31, 2003 at 02:40:17AM +0000, Alexander Schmolck wrote: > "Martin v. Loewis" writes: > > > Alexander Schmolck wrote: > > > > > Is there a better way? If not, how about something like Set.randompop()? > > > > In principle, random.choice "ought to" work. > > It doesn't, as it expects the set to be indexable. > > Maybe not insensibly -- the fairly generic approach outlined above that will > work for any iterable with len is clearly not desirable as default (because of > its time complexity), and just using it as a fallback won't work either, > because AFACT there is no way for `choice` to find out whether its argument is > a sequence or not. def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: return seq[int(self.random() * len(seq))] except TypeError: # Fallback algorithm Alternatively (not as nice, imho): def choice(self, seq): """Choose a random element from a non-empty sequence.""" typeOrClass = getattr(seq, '__class__', type(seq)) if hasattr(typeOrClass, '__getitem__'): return seq[int(self.random() * len(seq))] else: # Fallback algorithm Jp From claird at lairds.com Mon Dec 15 06:08:41 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 15 Dec 2003 11:08:41 -0000 Subject: run Fortran from python References: <31e18870.0312142131.5cf4d329@posting.google.com> Message-ID: In article <31e18870.0312142131.5cf4d329 at posting.google.com>, SamX wrote: >I know Tcl can run Fortran excutables. Can python do the same? >Thank you Yes. Read up on such facilities as os.system and os.popen* . -- Cameron Laird Business: http://www.Phaseit.net From ville.spammehardvainio at spamtut.fi Sun Dec 21 13:57:32 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 21 Dec 2003 20:57:32 +0200 Subject: web programming: experiences with non-zope frameworks? References: <7xu13u7gko.fsf@ruckus.brouhaha.com> Message-ID: Brendan O'Connor writes: > > I'll give some heretical advice: if > > you're doing a big project, set aside some of the development time to > > evaluate what's out there and adopt or develop something that's best > > for your specific needs, with the understanding that you're going to > > have to maintain it yourself. If you're doing a small project and > That's certainly a shame to hear. I'm very concerned that any given > python framework I'd choose might not be around a few years from now; it Umm... I guess that's not what he meant. It's the framework you developy yourself you would have to maintain. > seems that none of them have the popularity needed to sustain a large > community to test and achieve maturity, write books and top-quality > documentation, etc. If having these qualities is so important, why not just bite the bullet and go Zope? -- Ville Vainio http://www.students.tut.fi/~vainio24 From donn at u.washington.edu Fri Dec 26 12:44:02 2003 From: donn at u.washington.edu (Donn Cave) Date: Fri, 26 Dec 2003 09:44:02 -0800 Subject: 2.3 list reverse() bug? References: <26vmuvooh62ko48t7m8n2cumg0se7dd7v5@4ax.com> Message-ID: In article <26vmuvooh62ko48t7m8n2cumg0se7dd7v5 at 4ax.com>, Arthur wrote: ... ... > But the response: > > """ > Almost needless to say, it was the poster's intuition that was at > fault, but he is (was) far from unique in having this sort of > misconception. > """ > > frankly bothers me a bit, though it is understandable somewhat in the > context of the phrasing of the posters question. > > Generally speaking, it is hard to understand how someone's intutition > can be flawed. It's just an "is". Hm, made sense to me. But you have to take "intuition" in the the operational sense, not the primitive, innate ability to build on experience but the result, the ability plus the experience. When introduced to a system that follows different rules, our intuition will occasionally be at fault when it contributes to an invalid assumption. Seems to me it couldn't be otherwise (though honestly if I had much trouble with it, I don't recall now - likely I just tend to be more interested in such things and therefore less likely to find out about them by accident.) > That the programming language might do slight damage to one's naive > intution is not either the fault of the programming language. > Something perhaps simply needs to be learned. Once learned, one's > intuition is happly overridden - no hard feelings. Or better informed. If you mean that in cases like the one that started this thread, one would just have to learn to ignore one's intuition, that doesn't sound like a happy state to me! Donn Cave, donn at u.washington.edu From aahz at pythoncraft.com Mon Dec 8 15:48:45 2003 From: aahz at pythoncraft.com (Aahz) Date: 8 Dec 2003 15:48:45 -0500 Subject: from spam import eggs, spam at runtime, how? References: <7xhe0bf5id.fsf@ruckus.brouhaha.com> Message-ID: In article <7xhe0bf5id.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >Another way: > > exec 'import spam' That's precisely what we were trying to avoid. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From john.abel at pa.press.net Thu Dec 18 07:32:46 2003 From: john.abel at pa.press.net (John Abel) Date: Thu, 18 Dec 2003 12:32:46 +0000 Subject: Logging In-Reply-To: References: Message-ID: <3FE19E6E.1010308@pa.press.net> Try this. It records anything Warning and above. logFacility = logging.getLogger( "MyApp" ) logFile = logging.FileHandler( "LogFile.log" ) logFormat = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' ) logFile.setFormatter( logFormat ) logFacility.addHandler( logFile ) logFacility.setLevel( logging.WARNING ) logFacility.info( "Starting Up" ) ** HTH John Kamus of Kadizhar wrote: > Does anyone have a working example or a recipe of a simple logging > system using the logging module? Any FM I can refer to? > > I can't seem to get it right - I can't even make sense of the standard > library docs. What do I have to do to log records to a file? > > (Newbie Q, as you might guess...) > > -Kamus > From rganesan at myrealbox.com Fri Dec 19 23:03:18 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Sat, 20 Dec 2003 09:33:18 +0530 Subject: Anybody ever use Pippy? References: <3FE30E59.9010104@lawson.com> Message-ID: >>>>> "William" == William S Perrin writes: > I've just downloaded and installed Pippy > (http://pippy.sourceforge.net/) for my Palm. It's called 1.52+. I'm > not sure what the plus is. It seems to run ok. Anyone else have any > experience? I have it loaded on my Treo 90. Haven't seriously played around with it. I don't remember if Pippy has an interface to the Palm UI, if it does that's certainly a plus. Unforunately it doesn't seem to be maintained any more. Personally, I find Plua, palm port of Lua 4.0 more promising. There is even an free desktop IDE for Plua written in Java (see http://www.sophonix.com/downloads/plural.asp). Ganesan -- Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/ 1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832 6798 15E0 02BA 5D8C 12EA From rainerd at eldwood.com Fri Dec 19 01:27:59 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 19 Dec 2003 06:27:59 GMT Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: Glen Wheeler wrote: > I have one constantly changing dict with many millions of keys > (tuples of ints) which in turn associates itself with a tuple of ints > and two more dicts. That makes things a bit harder. I expect that the big dict itself requires at least sixteen bytes per entry. How big are your tuples? How big are the dicts in the data tuples? What data do they contain? Are any of the tuples or dicts shared? Encoding the key tuples as strings is easy (''.join([chr(x) for x in the_tuple]). Encoding the ints in the data tuples is just as easy. I'm not sure if those are enough to solve your problem. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From http Fri Dec 5 00:31:12 2003 From: http (Paul Rubin) Date: 04 Dec 2003 21:31:12 -0800 Subject: Lists and Tuples References: Message-ID: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Jeff Wagner writes: > I've spent most of the day playing around with lists and tuples to > get a really good grasp on what you can do with them. I am still > left with a question and that is, when should you choose a list or a > tuple? I understand that a tuple is immutable and a list is mutable > but there has to be more to it than just that. Everything I tried > with a list worked the same with a tuple. So, what's the difference > and why choose one over the other? Try this with a list: a = [1, 2, 3, 4, 5] a[3] = 27 print a Then try it with a tuple. From newsgroups at jhrothjr.com Thu Dec 11 11:34:49 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 11 Dec 2003 11:34:49 -0500 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xekvb1koc.fsf@ruckus.brouhaha.com> <7x65gn1jk5.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x65gn1jk5.fsf at ruckus.brouhaha.com... > claird at lairds.com (Cameron Laird) writes: > > I persist at this out of concern that I'm not making things clear. > > My stake, incidentally, is that you be successful, not that you > > use any particular toolkit. > > > > The second URL gives working code that you can use immediately in > > your own applications to improve their appearance. This is not an > > extension or anything at all difficult or constraining; it's just > > a little prologue that refines the standard Tkinter appearance. > > It *is* in use, right now, in several applications that must have > > professional appearances. The first URL is about committee work, > > essentially, that will fold the enhancements of the second URL > > back into the standard Tk distribution. > > Oh cool. The second screen shot on that page ("after") does look a > lot better than the "before" shot. I guess I'll look at it more > carefully, but Tkinter has always made me cringe because of its use of > tcl (why does it need its own extension language if Python itself is > supposed to be such a good one)? Thanks. And that is what is called a "real good question." I believe that you're supposed to be able to use the Tk libraries without using TCL, but the people that wrote Tkinter weren't able to make it work. I don't, however, know this for a fact, it's just something that's bouncing around the old synapses... John Roth From __peter__ at web.de Tue Dec 9 05:55:58 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 11:55:58 +0100 Subject: need help on sublcass and scope References: Message-ID: Inyeol Lee wrote: > I'm an OOP newbie, and needs help on subclassing from different module. > > I made a base module a.py which contains two classes C1 and C2; [...] > but it looks like an ugly hack to me. > If there's common OOP idiom to handle this kind of problem, give me > some pointer. I think with all these a, b and Cs, you raised the abstraction level too high. To me - at least - it remains unclear what you are trying to achieve. I've made a bold guess and tweaked your example to output what you expected without having to mess with sys.modules. #a.py class C1(object): def m(self): print "method m in class C1 in module a" class C2(object): def __init__(self, a=None): print "class C2 in module a" if a is None: a = C1() self.a = a self.a.m() #b.py import a class C1(a.C1): def m(self): print "method m in class C1 in module b" a.C1.m(self) class C2(a.C2): def __init__(self): print "class C2 in module b" a.C2.__init__(self, C1()) If you want to modify a part of the C2 implementation independently of the C2 hierarchy, you could make C1 a Mixin: #a.py vs 2 class C1(object): def m(self): print "method m in class C1 in module a" class C2(object): def __init__(self, a=None): print "class C2 in module a" self.m() #b.py vs 2 import a class C1(a.C1): def m(self): print "method m in class C1 in module b" super(C1, self).m() class C2(a.C2, C1): def __init__(self): print "class C2 in module b" super(C2, self).__init__() The beauty of this approach becomes visible if you add further subclasses to C1: #c.py aka b.py vs 3 import a class C11(a.C1): def m(self): print "method m in class C11 in module c" super(C11, self).m() class C12(a.C1): def m(self): print "method m in class C12 in module c" super(C12, self).m() class C2(a.C2, C11, C12): def __init__(self): print "class C2 in module b" super(C2, self).__init__() a.C1 occurs twice in the hierarchy, so how often would you expect "method m in class C1 in module a" to be printed? I you anser 1, then which of the following messages will be omitted: "method m in class C11 in module c" or "method m in class C12 in module c" Let's try: >>> import c >>> c.C2() class C2 in module b class C2 in module a method m in class C11 in module c method m in class C12 in module c method m in class C1 in module a >>> Every m() was exactly called once! However, I'm not an OOP newbie and still have doubts if I've got the above right, so I would recommend the first approach. After all, Python is more about readability and ease of use than clever tricks to confuse the uninitiated. Peter PS: For more information, google for python and descrintro. From tjreedy at udel.edu Tue Dec 30 13:16:41 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 13:16:41 -0500 Subject: Is Python Mac Centric??? References: Message-ID: "hokieghal99" wrote in message news:bss8qn$mb7$1 at solaris.cc.vt.edu... > Also, I've noticed that OSX 10.3 comes with Python 2.3 installed, but > that Windows XP does not. My new HP Pavilion XP came with Python 2.2.1 loaded for use by HP's utilities. However, their docs say nothing about it and it was not completely installed in that there were no file associations for .py. That's fine since I will add 2.3.3 soon and leave HP's install alone for its use. Terry J. Reedy From mwh at python.net Thu Dec 25 06:40:36 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Dec 2003 11:40:36 GMT Subject: Is re thread-safe? References: Message-ID: Benjamin Han writes: > Just want to make sure before I start to change my code in major way - it'd > be nice to do regex matching in parallel. Um. I doubt the sre engine releases the GIL during matching -- might be wrong -- but unless you're on a multiprocessor I'm not quite sure what "in parallel" would mean. I don't think you'll encounter misbehaviour from using re in multiple threads. Cheers, mwh -- ... with these conditions cam the realisation that ... nothing turned a perfectly normal healthy individual into a great political or military leader better than irreversible brain damage. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From no.spam at no.smap.com Mon Dec 22 11:20:09 2003 From: no.spam at no.smap.com (Maciej Sobczak) Date: Mon, 22 Dec 2003 17:20:09 +0100 Subject: Default arguments, object sharing, name lookup and others Message-ID: Hi, Playing around with the Python Tutorial I found the following definition: def f(a,L=[]): L.append(a) return L then: f(1) f(2) f(3) will accumulate the values appending them to the *same* list. Now: def f(a,s=''): s = s + a return s f('hello') f('world') This will not cause value accumulation. Interestingly, this will neither: def f(a,L=[]): L = L + [a] return L which is most confusing for me. I do not understand how this works (the first one). I would like to ask you for some explanation, especially: - where is the object stored if it is shared between subsequent calls? how it is found? - why does it work for lists and not for strings? - why does it work for lists only when the append method is used? My "native" language is C++. Feel free to use analogies, where appropriate. Thank you very much for any light, -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From Benjamin.Riefenstahl at epost.de Mon Dec 22 07:44:33 2003 From: Benjamin.Riefenstahl at epost.de (Benjamin Riefenstahl) Date: Mon, 22 Dec 2003 13:44:33 +0100 Subject: no output of pyhton in emacs shell buffer References: Message-ID: Hi Leo, "leo" writes: > in an emacs shell buffer i get no output of python, even no > ">>>"-prompt. > > however, behind the scene python still works, i can type a command > blindly, and _after quitting python_ the associated output is > written to the shell buffer. > [...] > i work with ntemacs, the and the cygwin python 2.3.2 Native Windows doesn't have pseudo-ttys. The python interpreter sees that it is running in a pipe, and thinks that this is non-interactive environment, instead of an interactive terminal. You could try to force the python interpreter into interactive mode in some other way (command option, configuration item). Also, Cygwin Emacs would probably fix that problem, because Cygwin can simulate pseudo-ttys between Cygwin applications. benny From fredrik at pythonware.com Mon Dec 8 12:58:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 18:58:07 +0100 Subject: from spam import eggs, spam at runtime, how? References: Message-ID: Rene Pijlman wrote: > Hmm... my spam is a package and eggs is a module. This code gives me: > > AttributeError: 'spam' module has no attribute 'eggs' > > But it works like this: > > spam = __import__('spam',globals(),locals(),['eggs']) > eggs = spam.eggs or: spam = __import__('spam.eggs') eggs = spam.eggs From fredrik at pythonware.com Sun Dec 7 06:38:35 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 12:38:35 +0100 Subject: Lists and Tuples References: <16336.59925.934194.67341@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > >> list = [ x for x in tuple ] > > Roy> What's wrong with the even simplier: > > Roy> aList = list (aTuple) > > It doesn't use the language feature du jour. ;-) list comprehensions have been around for ages. to show off, you'll need to get itertools and generators into the mix. From js at cis.uni-muenchen.de Mon Dec 1 12:11:28 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 01 Dec 2003 18:11:28 +0100 Subject: leftmost longest match (of disjunctions) Message-ID: Hello, The program given below returns the lines: a ab Is there a way to use python regular expressions such that the program would return the following lines? ab ab ######################################################################## import re rx1 = re.compile("(a|ab)") rx2 = re.compile("(ab|a)") out1 = rx1.search("ab") out2 = rx2.search("ab") print out1.group(1) print out2.group(1) ######################################################################## J?rg From torsten.rueger at hiit.fi Fri Dec 19 03:51:44 2003 From: torsten.rueger at hiit.fi (Torsten Rueger) Date: Fri, 19 Dec 2003 10:51:44 +0200 Subject: udp broadcast example, please In-Reply-To: <20031218143113.GA6532@intarweb.us> References: <20031217152749.GA4432@intarweb.us> <99C41BAC-3133-11D8-BB2B-000A959C1BB0@hiit.fi> <20031218143113.GA6532@intarweb.us> Message-ID: <923A39C8-3200-11D8-B2B6-000A959C1BB0@hiit.fi> On Dec 18, 2003, at 4:31 PM, Jp Calderone wrote: >> Thanks for trying to help. But really this is very incomplete, missing >> all read or write calls to the socket. > > Huh? Sorry, maybe I was unclear: The code you post is not self contained, far from it. I have gone through twisted for a long time, and it's not so clear at all what parameters to the socket calls are being used. And that is really my question. > It works fine. If you run it, it will send and receive packats. No doubt. If you have twisted installed that is. But it doesn't get me closer to doing it myself in those ten lines that it really only is. Or would be if I knew them. Maybe you or someone can clear a conceptual question for me: Can several processes on the same machine receive udp packets on the same port ? Thanks Torsten From http Tue Dec 2 00:27:05 2003 From: http (Paul Rubin) Date: 01 Dec 2003 21:27:05 -0800 Subject: newbie - integer variable with leading zero for os.makedirs References: <278a833.0312012112.55912355@posting.google.com> Message-ID: <7xy8tvhjrq.fsf@ruckus.brouhaha.com> jtoher at cyllene.uwa.edu.au (james) writes: > I've tried: > > permission = int('750', 8) > mode = oct(permission) > > but this returns an octal string '0755' and os.makedirs barfs again. > It really wants an integer and it really wants that leading zero. How > can I assign a number with a leading zero to an integer variable? Just say permission = 0750 From vincent at visualtrans.de Mon Dec 22 01:26:54 2003 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 22 Dec 2003 07:26:54 +0100 Subject: calling the function police References: Message-ID: "EP" schrieb im Newsbeitrag news:mailman.28.1072071996.684.python-list at python.org... | Hi, | | "I'm new and confused" | "Hello 'New and Confused'" | | TypeError: function1() got multiple values for keyword argument 'first' | | >>> def function1 (first='Jimminy Cricket', end='suffix', *extras): | together, extra=' ',' ' | for each in extras: | try: | extra+=each | except TypeError: | extra+=`each` | together=first+extra+end | return together | | >>> parameter='something' | | >>> result=function1(first=parameter, end='noodles','Jim Beam', 'Poker') | | TypeError: function1() got multiple values for keyword argument 'first' I would expect you to get something like "SyntaxError: non-keyword arg after keyword arg" (at least in 2.3.x). Vincent Wehren | | What rule have I violated? I would expect you to get something like "SyntaxError: non-keyword arg after keyword arg" (at least in 2.3.x). Vincent Wehren | This seems to be associated with the assignment of a variable to a keyword | argument in the function call. Is this illegal? | If so, why is this a crime? The logic isn't popping out at me... | | Thanks.... | | | Eric | | [I resorted to relying on order rather than keywords in the call to make it | work] | | | From mwh at python.net Thu Dec 18 09:35:15 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Dec 2003 14:35:15 GMT Subject: New style classes and rich comparison References: Message-ID: stain at stud.ntnu.no (Stian S?iland) writes: > Could anyone explain to me why this does not work as intended? [snippo] > It seems that __eq__ is fetched directly from newbie's class, not from > newbie. Yup! One of the differences between new-style and old-style classes. To see why something has to be a bit like this, consider the difference between a unbound method for the instance and a bound method for the *type* of the instance... [biggo snippo] > Can I use __metaclass__ or something? I think that's what you want, yes. Cheers, mwh -- Ignoring the rules in the FAQ: 1" slice in spleen and prevention of immediate medical care. -- Mark C. Langston, asr From francisgavila at yahoo.com Mon Dec 15 23:37:53 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 15 Dec 2003 23:37:53 -0500 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> <1e963607.0312151857.186adaa8@posting.google.com> Message-ID: Matthew Sims wrote in message <1e963607.0312151857.186adaa8 at posting.google.com>... >"Francis Avila" wrote in message news:... >> Matthew Sims wrote in message >> <1e963607.0312151408.583221e6 at posting.google.com>... > >Here's how the program basically worked. It's for a Tape Library with >a robot arm in the middle. There are 40 slots and each is represented >as an element in the array. If a tape was in one of the slots, that >element # corresponds to the slot # and the tape ID would show in that >element. All other elements represented blank slots. This allowed me >to control the robot arm to the exact slot a tape resides since all I >had to do was look at any elements that had tape IDs assigned. Ah, I see. Well, that makes more sense. In this case it's *not* so clear-cut whether to use a list or a dict (or whatever). A list is a reasonable approach. Right off the bat, I can think of a few: - What you're doing now, but initializing an empty list to fixed length, eg, tapearray = [None]*40. Now just use it (no need to worry about magically extending the list as you add to random slots), but make sure you don't modify the list with insert, append, extend, pop, etc., etc.: only perform operations on its members. Python doesn't do the implicit thing, so you're often well off by preinitalizing data structures, as here. I simply say [None]*40 and your entire original question disappears, because you were looking at the problem in a perlish manner of "how do I use this array in a manner that doesn't require me to declare its total size before I use it." Explicit is better than implicit. - Using a dict with integer keys. Because your tape array won't change in size, and iterating over the whole thing looks to be the most common operation (as opposed to random access), dict might not be the obvious choice. But dicts are more flexable, and make explicit the importance of the index. You don't need to initalize your dict because it will add non-existent keys on assignment, but it's probably less of a hassle to do so anyway, because it *will* raise a KeyError if you try to read a key it doesn't have. To get around this, you need to subclass dict and make a (commonly reimplemented) DefaultDict subclass, or make sure you consistently use the setdefault method of your dict. I say just preinitalize the blasted thing: tapearray = dict([(i, None) for i in range(40)]). - Using a list of lists, with zeroth element of each sublist the slot number. Now you don't have to worry about preinitalizing the list or keeping the tape slots in order. I can't think of any advantage to this approach, unless you need faster iteration with variable total length, and don't need the slots to be ordered. Probably just use a dict. - Write a TapeSlot class, a TapeArray class, and a TapeArrayVisitor class. (I'm kidding! Don't do this.) Of course, you can mix-and-match as your requirements demand. If slots need more status information, you could use a dict of lists or a list of lists. If slots have a set of operations proper to them, you can use a list of TapeSlot objects; or you could wrap the interface to the tapearray in a TapeArray class, and make slot access a hidden implementation detail. >So far the only way I could get this to work in Python was to insert >"" to represent an empty slot. But Python counts "" when I want to see >how many tapes are currently taking up slots "len(SLOTS)". It would >always show 40. So I now know that I need to write code to tell Python >not to count "". Not too difficult. Not at all: len([tapeID for tapeID in tapearray if tapeID]) "If the item in tapearray is True (in a boolean context, '' is False) append that item to a new list, then find the length of this new list." > >I guess I'm realizing how I need to approach Python as my first OO. >I'm re-writing the script as sort of a training. The program works >flawlessly in Perl, I'm just doing it to learn. So far it has taken >less lines of code in Python to perform the same tasks in Perl...up >til this point. ;) Unless you're doing relatively complex things that require a rich set of data/semantics for tape slots and/or tape arrays, there's no reason to start using objects to represent them: "Simple is better than complex." Some people get drunk on OO. OO is useful, but can also add unnecessary complexity and obscure what you're doing behind too many layers of abstraction. Finally, don't do line-of-code comparisons between Python and perl. Python may be brief, but it is *not* terse, and will choose clarity over more-magic-per-line. List comprehensions excepted. ;) Ugh, I talk too much. Well, hope you like Python! -- Francis Avila From dpharris76 at msn.com Sun Dec 28 11:28:07 2003 From: dpharris76 at msn.com (David Harris) Date: Sun, 28 Dec 2003 10:28:07 -0600 Subject: sys.path[0] in IDLE Message-ID: On 2003-12-27, Gabriel Genellina wrote: > At 26/12/2003 22:25, you wrote: > >>Am I reading this correctly? >> >>http://python.org/doc/current/lib/module-sys.html >> >>""" >>As initialized upon program startup, the first item of this list, >>path[0], is the directory containing the script that was used to >>invoke the Python interpreter. >>""" >> >> >>So, sys.path[0] should be the directory that my script is in? Back in March 2003, I had the following exchange with Kurt Kaiser on the Idle-dev list. This may clear things up for you. http://mail.python.org/pipermail/idle-dev/2003-March/001672.html FWIW, Dave Harris -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at u.washington.edu Mon Dec 15 19:05:06 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 15 Dec 2003 16:05:06 -0800 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: In article <3fde309f$0$19285$626a54ce at news.free.fr>, Bruno Desthuilliers wrote: ... > (hint : it already *does* work like pointers in C[++] - at least for > mutable objects). For any and all objects, irrespective of mutability. Donn Cave, donn at u.washington.edu From faizan at jaredweb.com Mon Dec 15 14:21:05 2003 From: faizan at jaredweb.com (Fazer) Date: 15 Dec 2003 11:21:05 -0800 Subject: Strip HTML tags? References: <7b454334.0312131911.70647953@posting.google.com> <7b454334.0312141157.8383dd5@posting.google.com> Message-ID: <7b454334.0312151121.edae739@posting.google.com> BW Glitch wrote in message news:... > Fazer wrote: > > BW Glitch wrote in message news:... > > > >>Fazer wrote: > >> > >> > >>>Hello, > >>> > >>>I was wondering what would be the easiest way to strip away HTML tags from a string? > >>> > >>>Or how would I remove everything between < and > also the < , > as well using regex? > >> > >>You could use the SGMLparser for that also. Check the Python Cookbook at > >>ASPN ( http://aspn.activestate.com/ASPN/Python/Cookbook/ ) for a recipe > >>that uses it ( > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52281 ). > >> > > > > > > Thanks! The recipe works out fine! The problem is that I saved the > > class in a file and I want it to be included in my other script. How > > can that be done? My other script is in the same directory as the > > class and doing import doesn't work. > > You should import > > -- > Glitch > Thanks for the responce! I put the class and the final function in a tags.py file. I make another script and do : "import tags" It works, but when I try to make a new class instance, it can't seem to find it. From cantspellmyname at hotmail.com Tue Dec 9 09:50:32 2003 From: cantspellmyname at hotmail.com (CantSpellMyName) Date: 9 Dec 2003 06:50:32 -0800 Subject: moving from python1.5 to python2.2 Message-ID: <12481792.0312090650.7de1662@posting.google.com> Hi folks, i have to re-write an application that was using python scripts as configuration files (i.e. python embedded into c++) and it was using python1.5 (python15_d.dll). Now i would like to use python2.2 or even python2.3, but when i compile the application with ms visual c++, i get : error LNK2001: unresolved external symbol __imp__Py_InitModule4TraceRefs i think it might be coming from the fact that i don't have the debug dll for python2.2 . Can someone help? Thanks a lot, -Manu From gherron at islandtraining.com Tue Dec 23 23:45:48 2003 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 23 Dec 2003 20:45:48 -0800 Subject: A dictionary list? In-Reply-To: <3fe91593@clarion.carno.net.au> References: <3fe91593@clarion.carno.net.au> Message-ID: <200312232045.48936.gherron@islandtraining.com> On Tuesday 23 December 2003 08:27 pm, Steve wrote: > Hi, > > How can I create a list of a dictionary? (in other words, I need to > create an array of a dictionary). Please help! > > Steve That question is not very specific but perhaps dictionary methods "key", "values", or "items" might be what you want: >>> # Here is a sample dictionary >>> d = {1:'one', 2:'two', 3:'three'} >>> >>> # Get a list of its keys >>> d.keys() [1, 2, 3] >>> >>> # Get a list of its values >>> d.values() ['one', 'two', 'three'] >>> >>> # Get a list of (key,value) tuples >>> d.items() [(1, 'one'), (2, 'two'), (3, 'three')] Hope that helps, Gary Herron From barry at python.org Thu Dec 18 16:35:34 2003 From: barry at python.org (Barry Warsaw) Date: Thu, 18 Dec 2003 16:35:34 -0500 Subject: Scheduled downtime for mail.python.org / mail.zope.org Message-ID: <1071783334.31232.8.camel@anthem> BayMountain will be installing a new UPS on the circuit that runs mail.python.org/mail.zope.org. Downtime of approximately 30 minutes is scheduled between 2-4am Sunday December 21st EST. -Barry From mwh at python.net Thu Dec 4 08:53:24 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Dec 2003 13:53:24 GMT Subject: How to share 3rd-party modules between 2.2 and 2.3? References: Message-ID: Matthew Wilson writes: > I have Red Hat 9 installed, which uses python2.2 for lots of system > tasks. I also installed 2.3 using the rpms available from python.org. > > I want to write some CGI scripts that use pgdb. I want to write the > python scripts using python2.3, but the pgdb.py file is in > > /usr/lib/python2.2/site-packages > > which is not part of sys.path in python2.3. What is the best way of > sharing these modules? I'd recommend against it. The bytecode is different between 2.2 and 2.3, so the .pycs alongside the source files will only be useful for one install. And while binary compatibility of C extensions is fairly likely, it's not total. > Does anyone have a better idea? Just install pgdb again. Cheers, mwh -- It could be argued that since Suitespot is infinitely terrible, that anything else, by very definition of being anything else, is infinitely superior. -- ".", alt.sysadmin.recovery From noreply at gunnar.cc Sat Dec 20 15:57:21 2003 From: noreply at gunnar.cc (Gunnar Hjalmarsson) Date: Sat, 20 Dec 2003 21:57:21 +0100 Subject: replacing two EOL chars by one In-Reply-To: References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: Paul McGuire wrote: > I hope someone who knows the answer can respond, hopefully in more > civil language. I'm sure that quite a few people know the answer, but most of them have probably killfiled or decided to ignore him. I hope that nobody provides an answer. -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl From mark at diversiform.com Wed Dec 10 13:42:38 2003 From: mark at diversiform.com (mark) Date: Wed, 10 Dec 2003 10:42:38 -0800 Subject: Pmw.ComboBox In-Reply-To: Message-ID: <000001c3bf4d$6367f450$5501a8c0@markxp> Excellent! See, always something to learn around here. - Mark -----Original Message----- From: python-list-bounces+mark=diversiform.com at python.org [mailto:python-list-bounces+mark=diversiform.com at python.org] On Behalf Of Eric Brunel Sent: Wednesday, December 10, 2003 10:10 AM To: python-list at python.org Subject: Re: Pmw.ComboBox mark wrote: > I guess I would wonder why you'd use a ComboBox that you didn't want > someone to select anything from, but maybe you are disabling the widget > conditionally. At any rate: > > Nochoice = Pmw.ComboBox() > Nochoice._entryWidget['state'] = DISABLED You shouldn't do that: as indicated by the leading underscore, _entryWidget is an internal field and shouldn't be accessed directly. So upgrading your Pmw version may someday break your code. The portable way to do what you want is: NoChoice.configure(entry_state=DISABLED) or: NoChoice['entry_state'] = DISABLED if you prefer this syntax. > Now, this is effectively disabling the entire widget, since it won't put > anything in the entry box. I'm not certain if this is what you're > looking for, but it works for me. > > - Mark > > -----Original Message----- > From: python-list-bounces+mark=diversiform.com at python.org > [mailto:python-list-bounces+mark=diversiform.com at python.org] On Behalf > Of Gombos Katalin > Sent: Wednesday, December 10, 2003 8:14 AM > To: python-list at python.org > Subject: Pmw.ComboBox > > Hi, > > How could I make the ComboBox state disabled? > > I don't want to let anybody to scroll the listbox of the ComboBox. > > Thank You! > > Katux HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com -- http://mail.python.org/mailman/listinfo/python-list From jepler at unpythonic.net Mon Dec 29 08:46:03 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Dec 2003 07:46:03 -0600 Subject: strftime - %a is always Monday ? In-Reply-To: <20031229133913.GA3537@nl.linux.org> References: <282f826a.0312290503.398d72cd@posting.google.com> <20031229133913.GA3537@nl.linux.org> Message-ID: <20031229134603.GD6171@unpythonic.net> On Mon, Dec 29, 2003 at 02:39:13PM +0100, Gerrit Holl wrote: > time.strftime does not know about dates. Field number 6 specifies the > weekday: make it a 1 and it will say Tuesday, 2->Wednesday, etc. You may > want to use the new datetime module: > >>> datetime.date(2003,12,7).strftime("%A") > 'Sunday' Gerrit, Sounds like much better advice than mine! Jeff From alan.gauld at btinternet.com Tue Dec 30 04:06:28 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Dec 2003 09:06:28 GMT Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com><3fef7965.439576157@news.blueyonder.co.uk><3ff0a9cc.517502278@news.blueyonder.co.uk> <3ff0c45a.524300834@news.blueyonder.co.uk> Message-ID: <3ff13f2d.555743486@news.blueyonder.co.uk> On Mon, 29 Dec 2003 18:15:55 -0700, "Dave Brueck" wrote: > > So yes, you could use Python to write a full windows compliant > > program, OTOH I'm still not sure that I'd want to write C in > > Python! :-) > > Well, I guess that depends. I've been using ctypes almost daily for a year or > so and now I find it annoying to do Win32 programming in C! It's not that > you're writing C in Python as Win32 programming mostly populating structures, > calling functions, and checking error codes That's true, I guess I really meant that I don't want to program Win32, period! :-) > have just the tediousness of Win32 left. ;-) I'm happy to write slightly non compliant apps using the GUI toolkits and live a happier life... Even when my job involved writing "real Windows" stuff I used Delphi rather than C/C++ life is just too short! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 10 05:49:44 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 10 Dec 2003 11:49:44 +0100 Subject: mod_python and caching DB objects References: Message-ID: <6hudtvc2grkdvleqemv4rls8ec60068g0u@4ax.com> Paul Rudin: >>fowlertrainer: >>Can I create an persistent database connection/objects in mod_py > >There is an entry in the mod_python FAQ addressing this question IIRC. Indeed: http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.003.htp -- Ren? Pijlman From prana73-python at yahoo.com Mon Dec 8 11:22:28 2003 From: prana73-python at yahoo.com (Hugh) Date: 8 Dec 2003 08:22:28 -0800 Subject: raw_input / console I/O question Message-ID: <72ba696e.0312080822.21fb2396@posting.google.com> I am using python 2.3 through the PythonWin program on windows. I would like to create a console-based interactive session. The program raw_input is almost exactly what I'd like, except that whenever I call raw_input(), it pops up a window on my screen. I'd much rather have it read from the interactive window. Is there something out there, as easy as raw_input(), that I can use? Thanks for any clues! -Hugh From zunbeltz at wm.lc.ehu.es.XXX Wed Dec 10 03:38:55 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 10 Dec 2003 09:38:55 +0100 Subject: About the use of **args Message-ID: Hi I'm starting a new proyect and i'm in doubt about diferent interfaces for my clases. My clases will have a lot of attributes and i'm want to know what aproach could be the best 1) Define one SetAttribute/GetAttribute pair of method for each attribute. 2) Define one SetAttribute/GetAttribute which argument is a key=value format. Any advaice? Thanks in advance Zunbeltz Izaola -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From tzot at sil-tec.gr Fri Dec 12 11:22:55 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 12 Dec 2003 18:22:55 +0200 Subject: python-dev Summary for 2003-11-16 through 2003-11-30 References: Message-ID: <4mqjtvk3asbiot8uc5odl8el0ge6lsca3v@4ax.com> On Thu, 11 Dec 2003 14:53:39 -0800, rumours say that "Brett C." might have written: >First, an errata on the last summary. I said generator expressions were >Peter Norvig's idea. Turns out it was Raymond Hettinger, the man who >has so many new ideas that his flame retardant suit has his initials >embroidered on it, who came up with the original idea in `PEP 289`_. What about this? http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.996609059.27167.python-list%40python.org (this, by Paul Prescod, is the oldest one that I remember and could locate --I actually had it kept in Agent! :), but there could be older references. Of course, hadn't Raymond written the PEP, the whole idea wouldn't advance... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From bvdpoel at kootenay.com Tue Dec 30 16:03:28 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Tue, 30 Dec 2003 14:03:28 -0700 Subject: When to put my modules In-Reply-To: References: <3ff0e744_1@dns.sd54.bc.ca> <3ff1ab8c_1@dns.sd54.bc.ca> Message-ID: <3ff1e7fc_1@dns.sd54.bc.ca> Terry Reedy wrote: >>Okay...so I just need to add paths to the sys.path variable. Seems >>simple enough. Thanks. > > > If your modules are specific to an application, adding the application > module-dir to the front of sys.path is probably best. If your modules > constitute a library that other Python programmers might want to access > (such as pygame or numerical), then the package should go in > lib/site-packages. Yes, thanks. And I'll find out soon enuf when I try this, but I suppose that having a bunch of alternates in the path is not a problem. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From tzot at sil-tec.gr Tue Dec 30 21:04:47 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 31 Dec 2003 04:04:47 +0200 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: On 31 Dec 2003 00:08:47 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >The other way is to take advantage of functions' roles as decriptors and the mechanism that >makes bound methods with a self as the first arg, but the rest apparently normal. I.e, >we can put the r parameter in the place of self (not specifically tested) > > def uses_self(r, x): > pass > uses_self = uses_self.__get__(re.compile("...")) It's much more general to use new.instancemethod. See: def voodoo(function, *its_arguments): from new import instancemethod def child(function, first_argument, *rest_of_arguments): if rest_of_arguments: return child( instancemethod(function, first_argument, object), *rest_of_arguments ) else: return instancemethod(function, first_argument, object) return child(function, *its_arguments) The import statement is in the voodoo just for completeness including it here. The function above recurses in order to allow stuff like: getter = voodoo(getattr, my_object, "its_attribute") or the more modern getter = voodoo(operator.itemgetter("its_attribute"), my_object) and similarly setter = voodoo(operator, my_object, "its_attribute") allowing setter(value) at good speeds. I have a module predicates.py defining All and Any classes for iterables, and the trick above plus itertools allows *some* operations to run faster than correspondent python code... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From mwh at python.net Tue Dec 2 10:13:57 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Dec 2003 15:13:57 GMT Subject: Can Python be run off of a CD-ROM? References: <3FCC8C92.406@ghaering.de> Message-ID: Gerhard H?ring writes: > Fredrik Lundh wrote: > > Gerhard H?ring wrote: > > > >>Here's the HOWTO, in one sentence: > >> > >>Grab a Python directory, copy the python{major}{minor}.dll from > >> %SYSTEMROOT%\system32 into this Python directory. > > is the part after the comma really necessary? > > (all installers I've ever used or created install the core DLL in the > > Python directory as well. are there installers out there that don't > > do that?) > > The Pythonlabs (or should it be called python-dev installer by now?) > installer doesn't do this. At least not in the Windows 2000 and XP > installations I use. ISTR this is helpful for win32all. Cheers, mwh -- You're posting to a Scheme group. Around here, arguing that Java is better than C++ is like arguing that grasshoppers taste better than tree bark. -- Thant Tessman, comp.lang.scheme From http Tue Dec 9 16:40:02 2003 From: http (Paul Rubin) Date: 09 Dec 2003 13:40:02 -0800 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> <7xy8tln207.fsf@ruckus.brouhaha.com> <3FD63B25.DC412905@engcorp.com> Message-ID: <7x4qw9oekt.fsf@ruckus.brouhaha.com> Just writes: > > In this case, he's getting the actual string from the web, so I wouldn't > > be surprised if exec would be a real can of security worms. Yuch. Although, the string can be checked against the list of available modules before exec'ing. > Also, __import__ returns a module object, so you don't have to pull it > out of the globals you passed to exec. Compare: > > g = {} > exec "import %s" % modulename in d > m = g[modulename] I think I'd have used exec "import %s as mymod"% modulename > with > m = __import__(modulename) OK, that's not as ugly as some of the other stuff I've seen going by. I guess it's better than an exec, if you can now just say m.whatever. From buzzard at urubu.freeserve.co.uk Fri Dec 12 19:44:52 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 13 Dec 2003 00:44:52 -0000 Subject: Working with copies of a dictionary References: Message-ID: [snip] > > Not even the slightest connection is not quite right. > > >>> adict = {'a':[1,2,3], 'b':[3,4,5]} > >>> anotherdict = adict.copy() > >>> id(adict['a']) > 10410608 > >>> id(anotherdict['a']) > 10410608 > >>> > > adict['a'] and anotherdict['a'] reference the same list. Try a deep copy. > > >>> import copy > >>> a_third_dict = copy.deepcopy(adict) > >>> a_third_dict > {'a': [1, 2, 3], 'b': [3, 4, 5]} > >>> id(adict3['a']) > 10411984 > > Duncan > Of course I shouldn't edit output once I've pasted it. That should be, >>> id(a_third_dict['a']) 10411984 From nair_260 at hotmail.com Thu Dec 11 13:30:38 2003 From: nair_260 at hotmail.com (Daven Nair) Date: Thu, 11 Dec 2003 10:30:38 -0800 Subject: Python code to replace shell scripts Message-ID: Hi, I would like to know if Python supports codes similar to shell scripts: count=`ps -ef|grep "pattern"|wc -l` for count in `echo $count` do done fi Can I export a variable say var from os.system("var=`ps -ef|grep pattern|wc -l`") thanks _________________________________________________________________ Cell phone ?switch? rules are taking effect ? find out more here. http://special.msn.com/msnbc/consumeradvocate.armx From r.s at XXmindspring.com Fri Dec 5 17:54:09 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Fri, 05 Dec 2003 22:54:09 GMT Subject: min and max id numbers Message-ID: Just curious ... On a given machine, is it possible to create objects LO and HI, such that for all objects x, id(LO) <= id(x) <= id(HI) ? --r.e.s. From max at theslimmers.net Thu Dec 11 15:21:31 2003 From: max at theslimmers.net (Max Slimmer) Date: Thu, 11 Dec 2003 20:21:31 GMT Subject: What GUI toolkit looks the best? In-Reply-To: <7xad5z1jq5.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: I have been using wxPython and it performs well ... You should also look at Boa Constructor a GUI designer generates decent Python code, integrated debugger is cool, shows local varraibles... for some uses I find it better than winpython. Paul Rubin wrote: > Brian Kelley writes: > >>Why forget Tkinter? I've seen Tkinter applications that look >>incredibly fabulous. > > > Got any url's for screen shots? > > >>A lot depends on what you are trying to do. If >>you are making a graphics-heavy application then Tkinter's canvas is >>pretty sweet. I also think IDLE looks pretty good. > > > There will be some graphical icons and stuff like that which people > will click on, but no really heavy graphics or drawing tools in the > sense of a photo editor or anything like that. > > >>Glade isn't a GUI, it is a GUI builder that uses GTK. In my >>experience, GTK doesn't look quite right on windows boxes, especially >>the menus. Of course I have the same basic view of Qt and Swing so >>know you know my biases. > > > Oh ok, I understand a bit better now. > > >>I tend to use Tkinter for canvas heavy applications and wxPython for >>other stuff. > > > Is wxPython Windows specific? I guess it is, but can I port the > screen layouts to some comparable Linux toolkit or anything like that? > The screen shots for it do look really nice. > > >>Here is my humble opinions in a nutshell (missing a lot here): >>wxPython has a grid control to die for and many, many classes, good >>printer support and looks like a native GTK app on Linux and a native >>app on windows and macintosh. > > > Oh wow, yes I guess it's cross platform then. Hmm, what Micro$oft > tool do I need to build and run it? Is Visual C++ enough? I guess > I can get the client to pay for some stuff like that. Also, is there > a Glade-like drag and drop gui editor for it? > > >>Qt is better for developing - it has a better class structure and I >>tend not to have to look up docs as often and can look really, >>really nice. > > > The KDE apps that I've seen look good but not really top notch. Maybe > more attention could improve them. They're certainly good enough for > practical use. > > >>Tkinter has a killer canvas and great postscript output. GTK is >>really quite fast. > > > I think I don't care about heavy duty graphics or more than rudimentary > printing. > > >>but don't take my word for this, why don't you see what you like the best? >> >>http://www.wxpython.org/ >>http://www.gtk.org/ >>http://www.scriptics.com/ >>http://www.trolltech.com/ > > > I don't know what I can really tell from these without more experience > with them. In particular, which is the most solid and reliable across > a wide range of Windows versions (95, 98, ..., XP whatever)? That > matters too. > > Thanks! > > Paul From shuvit at 127.0.0.1 Mon Dec 1 23:32:09 2003 From: shuvit at 127.0.0.1 (David MacQuigg) Date: Mon, 01 Dec 2003 21:32:09 -0700 Subject: language learning vs. process References: Message-ID: On Mon, 01 Dec 2003 19:33:47 -0800, Bryan wrote: [...] >by step. i think there is a third option you should consider, and IMO it's the best. it's studying small fully working >recipes that concentrate on one issue at a time and gives you a good foundation to build upon. fortunately, there is a >book that does just this and it's called "Python Cookbook". i think if you try to go for the one big program, you will >miss out on a lot of important stuff. I think there are also free online tutorials that do much the same thing such as >"Dive into Python". anyways, just my opinion. Python Cookbook may be too advanced for a beginner. I would work through Learning Python first. The main problem with Learning Python is that it is out of date, and some of the language features, like scoping rules, have been significantly changed. There is a new edition due real soon. Also, you won't get too far off the path if you follow the tutorials from python.org at the same time you work through the book. Dive into Python is *Excelllent*, but it also focuses on the language, rather than the operational details, which the OP requested. Also, the author makes it clear, this is a fast ride through some cool features, not an introduction. -- Dave From nessus at mit.edu Fri Dec 5 03:50:35 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 05 Dec 2003 03:50:35 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: X-Draft-From: ("comp.lang.python" 285349) To: bokr at oz.net (Bengt Richter) Subject: Re: Lists and Tuples References: <7x7k1b4yqn.fsf at ruckus.brouhaha.com> Fcc: |rcvstore +articles From: Douglas Alan --text follows this line-- bokr at oz.net (Bengt Richter) writes: > On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein > wrote: >> That's true, but another answer is: you should use tuples for short >> sequences of diverse items (like the arguments to a function). You >> should use lists for longer sequences of similar items. > I'm curious what you're getting at. I.e., what does diversity or > similarity have to do with the choice? Nothing really, except by idiom. When people use "should" here, I think they are over-generalizing. Most of the time, records (short and heterogenious) are used in a read-only fashion, and long homogenous sequences are used in a read-write fashion. But when people characterize this tendency with a "should", I think they are making a thinko. There are times when you need to modify a record and consequently might use a dictionary or list, rather than a tuple, and there are also times when you will never want to modify a long, homogenous sequence, in which case many people would find it more elegant to use a tuple than to use a list. The reason for the "should" is probably because, I imagine, Guido had in mind mostly multiple return values from function, and the like, when he put tuples into the language. |>oug From jdhunter at ace.bsd.uchicago.edu Fri Dec 5 14:10:13 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 05 Dec 2003 13:10:13 -0600 Subject: memory leak - C API Message-ID: I have a function that is leaking memory; I have removed all the extraneous code just to focus on the leak. This function contains the leak static PyObject * pokereval_debug_leak(PyObject *self, PyObject *args) { int i, N; char* cardstr; PyObject* player0; PyObject* player1; if (!PyArg_ParseTuple(args, "OO", &player0, &player1)) { PyErr_SetString(PyExc_ValueError, "Usage compare_two_hands(player0, player1)"); return NULL; } N = PySequence_Length(player0); // init the pokereval vars from the python args for (i=0; i References: Message-ID: <3FE636CE.7010208@v.loewis.de> William Trenker wrote: > Am I doing something wrong with weakref, or is it even possible to use a weak reference dict with execfile? No. You currently must pass genuine dictionaries to execfile (and exec and eval). Regards, Martin From bdesth.tagada at tsoin-tsoin.free.fr Thu Dec 18 05:38:02 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Thu, 18 Dec 2003 11:38:02 +0100 Subject: documentation In-Reply-To: References: Message-ID: <3fe17f3d$0$1149$636a55ce@news.free.fr> km wrote: > Hi all, > i am coming from a Perl background. i am now learning python. > suppose in Perl, to look at the perdocumentation page for variables in perl one can get the info by invoking perldoc perlvar. how to search for same in Python ? > kindly enlighten, > thanks, > KM > Python 2.3.2 (#1, Oct 27 2003, 01:23:54) [GCC 3.2.2 (Mandrake Linux 9.1 3.2.2-3mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def myFun(): ... """ print 42 and return None """ ... print 42 ... >>> help(myFun) HTH Bruno From jdhunter at ace.bsd.uchicago.edu Tue Dec 9 14:34:32 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 Dec 2003 13:34:32 -0600 Subject: regex confusion In-Reply-To: <00c701c3be77$1f24d8c0$0102a8c0@xavim> ("Xavier Martinez"'s message of "Tue, 9 Dec 2003 18:08:50 +0100") References: <00c701c3be77$1f24d8c0$0102a8c0@xavim> Message-ID: >>>>> "Xavier" == Xavier Martinez writes: Xavier> Depending on what you are up to, it would also be wise to Xavier> consider if it is possible to do it using string methods. Xavier> They are quite easier to handle *and debug*. Yes, I am a firm believer in Jamie Zawinski's adage: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. It's just that I use them so infrequently now in favor of string methods that I have become rusty. Hence my forgetting about DOTALL. Xavier> If you need to do extensive text processing in Python, Xavier> there is a nice book by David Mertz, which discusses the Xavier> issue (from simple string methods up to regexes and Xavier> parsers) at: http://gnosis.cx/TPiP/ Own it. Thanks for the help, JDH From james.kew at btinternet.com Sun Dec 7 15:07:19 2003 From: james.kew at btinternet.com (James Kew) Date: Sun, 7 Dec 2003 20:07:19 -0000 Subject: finding files that have extensions References: <93f5c5e9.0312071154.4e7a1311@posting.google.com> Message-ID: "hokiegal99" wrote in message news:93f5c5e9.0312071154.4e7a1311 at posting.google.com... > How could I define it so that *any* file that already has a > '.xxx' extension (where x = 'abcdefghijklmnopqrstuvwxyz' upper and > lowercase) would be excluded from the rename? Take a look at os.path.splitext -- testing os.path.splitext(filename)[1] will tell you if the filename carries an extension or not. James From charles at steinkuehler.net Tue Dec 16 13:54:02 2003 From: charles at steinkuehler.net (Charles Steinkuehler) Date: Tue, 16 Dec 2003 12:54:02 -0600 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: <20031216165203.GA5285@burma.localdomain> References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> <20031216165203.GA5285@burma.localdomain> Message-ID: <3FDF54CA.4040304@steinkuehler.net> Oh...I forgot to mention: If you want a good example of how Forth is used to implement a powerful, low-level, processor independent environment, take a look at OpenFirmware ( IEEE-1275) and OpenBIOS: http://www.openfirmware.org/ http://openbios.org/ Forth code is used to implement processor and system independent boot code for Suns, Apple's PPC based Macs, and several other 'alternateive' (ie: not mainstream x86 PC) architectures. -- Charles Steinkuehler charles at steinkuehler.net From cmg at dok.org Thu Dec 18 12:27:17 2003 From: cmg at dok.org (Chris Green) Date: Thu, 18 Dec 2003 12:27:17 -0500 Subject: bug with exception handling or subtle bug on my end? Message-ID: I'm encountering a place where if I use a for loop I can't catch the error raised by a member. I've tested python 2.3 and 2.3.1 ( the only ones I had quickly around ) and it's still occuring. Any insight would be appreciated but I can't figure out why the stand alone call works but for i in doesn't. I can work around this for now but if someone could please explain this behavior, it's driving me crazy. I've tried catching everything I could think of.. Thanks! #!/bin/env python import sys, os, ConfigParser class UGHConfigParser(ConfigParser.ConfigParser): default_conf = '/tmp/ugh.conf' def __init__(self, filename=None): ConfigParser.ConfigParser.__init__(self) if not filename: filename = self.default_conf self.readfp(open(filename)) def getNetworkConfig(self): "test" try: # items = ConfigParser.ConfigParser.items(self,'Network') items = self.items('Network') except UGHConfigParser.NoSectionError: items = [] except self.NoSectionError: items = [] except ConfigParser.NoSectionError: items = [] except IGiveUp: items = [] except: items = [] return items parser = UGHConfigParser() print "this works!" parser.getNetworkConfig() print "this doesn't!" for i in parser.getNetworkConfig(): print i Output: % python ugh.py this works! this doesn't! Traceback (most recent call last): File "ugh.py", line 41, in ? for i in parser.getNetworkConfig(): File "/usr/lib/python2.3/ConfigParser.py", line 537, in items raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'Network' -- Chris Green "I'm beginning to think that my router may be confused." From PeterM at resmed.com.au Thu Dec 18 16:48:39 2003 From: PeterM at resmed.com.au (Peter Milliken) Date: Fri, 19 Dec 2003 08:48:39 +1100 Subject: Broken python-model.el Message-ID: <274A369893F5FB4099345F006439D987013876E2@bella.corp.resmed.org> Yep, restarted Emacs. Sorry, I mislead in the last message. Bit more info: import .... swimrecord is fine (now), but EMPTY = swimrecord.SwimRecord() still has the "ord" highlighted. So the change seems to have fixed the fontification of "ord" in swimrecord but not the fontification of "ord" in SwimRecord. Also, "ChildException" still has the "Exception" portion fontified differently. Peter -----Original Message----- From: Skip Montanaro [mailto:skip at pobox.com] Sent: Friday, December 19, 2003 8:43 AM To: Peter Milliken Cc: skip at pobox.com; python-list at python.org Subject: RE: Broken python-model.el Peter> I manually applied the patch to 4.40 - it doesn't seem to be any Peter> different. The "ord" in "swimrecord" (for instance) is still Peter> fontified differently from the rest of the variable name. Did you restart Emacs? Note that the main change is in a (defvar), which won't be reevaluated if all you do is reload python-mode. Skip Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From dpryde+usenet at cis.strath.ac.uk Mon Dec 8 14:09:59 2003 From: dpryde+usenet at cis.strath.ac.uk (Daniel Pryde) Date: Mon, 08 Dec 2003 19:09:59 +0000 Subject: Class problem In-Reply-To: References: Message-ID: <3fd4cc87$1@nntphost.cis.strath.ac.uk> Robert Brewer wrote: > Let's hope your home version had double underscores surrounding "init". > ;) > > class ImagePyramid: > def __init__(self, parameters): > do stuff :-) > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.og > > Double whoops! I'm definite the one at home had double underscores though. Thanks for the correction. Daniel From bud at comune.grosseto.it Tue Dec 16 13:11:22 2003 From: bud at comune.grosseto.it (Bud P. Bruegger) Date: Tue, 16 Dec 2003 19:11:22 +0100 Subject: range of characters? Message-ID: <5.2.1.1.0.20031216190836.0287b4c0@mail.comune.grosseto.it> Hello, I suppose there should be an elegant way of getting a range of characters as in range('A', 'Z') Anyone knows how to do that? The best I thought of so far is something like [chr(i) for i in range(ord('A'), ord('Z')+1)], but that seems overly verbose.. thanks -bud ------------------------------------------------------------------------------------------------- Ing. Bud P. Bruegger, Ph.D. bud at comune.grosseto.it Servizio Elaborazione Dati 0564-488 577 (voice) Comune di Grosseto 0564- 21139 (fax) Via Ginori, 43 58100 Grosseto Collaborazione Comuni per la CIE http://www.comune.grosseto.it/cie/ From nospam at freeworld.fr Sat Dec 13 04:40:52 2003 From: nospam at freeworld.fr (Lucas Branca) Date: Sat, 13 Dec 2003 09:40:52 GMT Subject: Zope import PythonScript.standard unauthorized References: Message-ID: "Evan Simpson" wrote in message news:mailman.105.1071248121.9307.python-list at python.org... > > now I removed debian zope package ( :( sigh sigh ) , > > and I 'm using > > http://zope.org/Products/Zope/2.6.2/Zope-2.6.2-linux2-x86.tgz > > As a fellow Debian user I feel your pain, but Zope is a prime example of > software that you're really better off installing from the source > tarball. The Zope Corp. folks have worked *very* hard to make > installing and running Zope as easy as they can, and version 2.6 is more > stable than the 2.5.1 in Debian "stable". That's good to know. Actually, installing Zope from the tar is a quick and clean operation. At the end, I have all in one directory and I can have a happy life with it, too ;) Great work! Regards Lucas From skip at pobox.com Thu Dec 18 15:48:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 14:48:13 -0600 Subject: Broken python-model.el In-Reply-To: <274A369893F5FB4099345F006439D987013876D8@bella.corp.resmed.org> References: <274A369893F5FB4099345F006439D987013876D8@bella.corp.resmed.org> Message-ID: <16354.4749.867000.103119@montanaro.dyndns.org> Peter> So I don't even know what the "trailing builtin" problem is :-) Peter> All I know is that I don't like the way python-mode.el Peter> (currently) tries to find shadowed builtins. I would hardly call Peter> highlighting the "ord" in "swimrecord" as showing a shadowed Peter> builtin :-) I found the current mechanism highly annoying to be The "ord" in "swimrecord" is the "trailing builtin" problem I referred to. Peter> honest as it distracts rather than enhances. Should be fixed in CVS. Let me know if it's not. Skip From jjl at pobox.com Tue Dec 23 14:43:00 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 19:43:00 +0000 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> Message-ID: <8765g7jp6j.fsf@pobox.com> Fran?ois Pinard writes: [...] > [1] I mean, nearly French, as the necessary diacritics may not be > used in Python identifiers, which is a common and constant source of > displeasure to those of us who especially like working in French. Oh, > Python does not differ on this aspect than most other programming > languages. However, as Python is so satisfying in many other areas, we > had some vague hope that he might become better in this particular one. > Especially given that, for a tiny moment, it once worked correctly for > French -- but sadly, this was the consequence of a Python bug which has > been corrected since. I don't feel qualified, or morally righteous enough to have a hard opinion on whether this would be a good thing, as an English monoglot, but I don't see what the problem is with adding this feature. It seems only fair and symmetrical to allow unicode identifiers. Yes, it'd confuse the hell out of people like me to have to read a Python program written in Korean characters. But it'd confuse me just as much if it were written in Korean but transliterated into Roman characters in plain old ASCII. Has this been a problem Java, in practice? Or is the problem simply that it's considered that there's not good enough unicode support in editors and other tools yet? Again, I'm surprised if that's the case with all this Java code floating around. Has it been PEPed? Or is GvR's opinion on it obvious enough that nobody has bothered? John From darsie at gmx.at Mon Dec 29 12:55:38 2003 From: darsie at gmx.at (Bernhard Kuemel) Date: Mon, 29 Dec 2003 18:55:38 +0100 Subject: [Mailman-Developers] python is slow References: <3FE20578.7060402@gmx.at> <1072458360.4458.13.camel@anthem> Message-ID: <3FF06A9A.7030701@gmx.at> Barry Warsaw wrote: > On Thu, 2003-12-18 at 14:52, Bernhard Kuemel wrote: > >>You name the reasons why I will not produce the 'convincing >>evidence' Richard Barret is interested in. I do however believe >>ESR is called authority rightly and assume he is has sufficient >>knowledge of and communication with experts in the languages he >>writes about so his opinion adds to my experience that python is >>slow. Some complex things are hard to prove so I thought you >>might be interested in the opinion of a neural network trained in >>the subject. > > Saying "Python is slow" is pretty much a value-less statement. Ohh, I think it makes a good subject header as it describes well what this thread is about. > Slower than what? Slow when doing what? Too slow? Which version of Python? It seems you lost track of the thread. Ok ... I said, I did't like python, because it burnt up so much CPU time on our old P60 server. Mailman was started via cron once a minute and took about 15 s CPU time each time. 25% average CPU usage just to find out that there is nothing to do appears much to me. There was also a flat mate who used python and i noticed the processor load of that, too. Someone on mailman-developers at python.org then was interested in "convincing evidence" that python is slower than perl. But as we agree that such evidence is difficult to produce and does not mean much I cited Eric Stephen Raymond's book "The art of unix programming" where he says ... "In fact it's generally thought to be the least efficient and slowest of the major scripting languages, a price it pays for runtime type polymorphism." I originally quoted the whole paragraph to be fair. > Besides that, this thread is more appropriate on python-list at python.org > or some other advocacy list. Ok, I post this message there. > I firmly believe Python is both fast enough and the right > choice for Mailman, and that's not going to change. Allright. I trust you know what you are saying. > -Barry Bernhard -- Webspace; Low end Serverhousing ab 15 e, etc.: http://www.bksys.at Linux Admin/Programmierer: http://bksys.at/bernhard/services.html From theller at python.net Tue Dec 16 08:53:53 2003 From: theller at python.net (Thomas Heller) Date: Tue, 16 Dec 2003 14:53:53 +0100 Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> <93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: hokiegal99 at hotmail.com (hokiegal99) writes: >> On 15 Dec 2003 13:28:01 -0800, hokiegal99 wrote: >> > How can I make this script run w/o seeing a cmd popup window on the >> > screen? The script works well, but each hour (when the task scheduler >> > runs it) a brief cmd window appears and then goes away. It's only on >> > the screen for a second or two, but it's noticable. >> >> Use a better OS? <0.5 wink> >> >> Run it with pythonw.exe instead of python.exe. > > How can I specify pythonw.exe over python.exe? The task scheduler has > no place for this sort of thing. Name the script 'myscript.pyw' instead of 'myscript.py'. Thomas From jdhunter at ace.bsd.uchicago.edu Tue Dec 23 09:22:51 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Dec 2003 08:22:51 -0600 Subject: Storing pairs of (int, int) in a database : which db to choose ? In-Reply-To: <21bb8d55.0312230435.49cad73c@posting.google.com> (andreif@mail.dntis.ro's message of "23 Dec 2003 04:35:50 -0800") References: <21bb8d55.0312230435.49cad73c@posting.google.com> Message-ID: >>>>> "Stormbringer" == Stormbringer writes: Stormbringer> Hi, I want to implement a fulltext search for Stormbringer> messages in a forum. More exactly for each message I Stormbringer> store pairs (wordId, msgId) for each identified word Stormbringer> and when I search something I want to be able to Stormbringer> retrieve very quickly all msgId for a given wordId. Stormbringer> For starters I used PySqLite, using a table with Stormbringer> index on wordId. It works fine but it consumes way Stormbringer> too much space on the disk. For example for 19103 Stormbringer> pairs it takes 1686528 bytes, which amounts to Stormbringer> around 88 bytes per pair of integers, way too much Stormbringer> in my opinion (especially considering the range of Stormbringer> those integers - one is in the range 1..100000 and Stormbringer> the other in the range 1..500000). What about using a binary file of unsigned ints which you load into a python dictionary and do everything in memory? There would be no extra overhead in the file and it would be very fast, if you are able to hold the 100,000 ints in memory. JDH From __peter__ at web.de Wed Dec 3 12:48:41 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Dec 2003 18:48:41 +0100 Subject: Turning f(callback) into a generator Message-ID: It's easy to write a function that wraps a generator and provides a callback. E. g.: import os, sys def walk(path, visit): """ Emulate os.path.walk() (simplified) using os.walk()""" for dir, folders, files in os.walk(path): visit(dir, folders + files) if __name__ == "__main__": walk(".", lambda d, f: sys.stdout.write(d + "\n")) However, I did not succeed in turning the old os.path.walk(), i. e. a function taking a callback, into a generator. Is there a general way to do it without having to store all intermediate results first? Peter PS. No, I don't have a use case. Threads welcome if all else fails :-) From bokr at oz.net Tue Dec 30 19:08:47 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Dec 2003 00:08:47 GMT Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: On 30 Dec 2003 06:55:27 -0800, dw-google.com at botanicus.net (David M. Wilson) wrote: >Further to my last post here, I was playing some more with building a >regex object and storing it somewhere for use internally by a >function. I'm not happy with any of my solutions: > > ># I don't like this, but the fact that you can modify the procedure's ># function via a named argument seems neat in a hacky sort of way. > >def uses_default_parm_yuck(x, r = re.compile("...")): > pass > There is another way, but IMO it would be nice to be able to have an optional second parenthesized list to make bindings the same way which wouldn't be part of the call signature. I.e., def uses_default_parm_yuck(x)(r = re.compile("...")): pass or, same thing more prominently: def uses_default_parm_yuck(x)( # pre-bound locals r = re.compile("...") ): pass ISTM most of the implementation pieces for that should already be there. The other way is to take advantage of functions' roles as decriptors and the mechanism that makes bound methods with a self as the first arg, but the rest apparently normal. I.e, we can put the r parameter in the place of self (not specifically tested) def uses_self(r, x): pass uses_self = uses_self.__get__(re.compile("...")) then (the rebound) uses_self will look like a bound method and want exactly one parameter x (or whatever signature you program) and be able to refer to r like self. > >g = re.compile('...') > >def uses_global_yuck(x): > global g > pass > > ># This is horrible and probably slow. > >class is_hex: > def __init__(self): > self.r = re.compile('...') > > def __call__(self, x): > r = self.r > pass > >is_hex = is_hex() > > ># This mucks up scoping so that your procedure can't access it's ># parent scope like it could normally. Since I never do this, ># it's my favourite. > >def is_hex(): > r = re.compile('...') > def is_hex(s): > return r.match(s) is not None > return is_hex > >is_hex = is_hex() > > > >Am I missing something? Is there a nicer way of doing this? On a day >to day basis I find myself in this situation quite regularly, and now >I come to think of it today, it is something that I would like to >improve. > >It is funny that in private it has never bothered me much, but when >posting on comp.lang.python I find that the code is unacceptable. >Maybe I have two modes of programming, idealist and practical? *shrug* >:) > > >David. Regards, Bengt Richter From jdhunter at ace.bsd.uchicago.edu Tue Dec 23 15:27:17 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Dec 2003 14:27:17 -0600 Subject: creating EPS with Python In-Reply-To: (hwlgw@hotmail.com's message of "23 Dec 2003 08:34:25 -0800") References: Message-ID: >>>>> "Will" == Will Stuyvesant writes: Will> >> [Jamie] Now all I need to do is create vector eps files. Can >> you tell me where I should start for that? PyX is a very nice python postscript generator http://pyx.sourceforge.net/ JDH From nospam at freeworld.fr Thu Dec 11 14:13:57 2003 From: nospam at freeworld.fr (Lucas Branca) Date: Thu, 11 Dec 2003 19:13:57 GMT Subject: Zope import PythonScript.standard unauthorized References: Message-ID: > You're more likely to get help with Zope problems from one of the Zope > mailing lists. > > > # Example code: > > from Products.PythonScripts.standard import html_quote, urlencode > > return 1 > > Works for me -- what version of Zope and Python are you using? > on Debian woody I installed : Zope version = Zope 2.5.1 Python version = 2.1.3 and I'm not having "a really good time" with it .... :( Ok..... let's look at Zope site then ........ Thx Lucas From joconnor at cybermesa.com Mon Dec 1 11:20:26 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Mon, 01 Dec 2003 09:20:26 -0700 Subject: Python for web ? In-Reply-To: <3FCB65B8.36E9AF19@engcorp.com> References: <3FCB65B8.36E9AF19@engcorp.com> Message-ID: Peter Hansen wrote: >Jay O'Connor wrote: > > >>black wrote: >> >> >> >>>Howdy everyone~ >>> >>>i heard Python could be used in web programming and aftering searching >>>many docs just found something on Python and CGI. the fact is i know >>>nothing about CGI and most of my projects(both of company and myself) >>>are established with PHP and ASP. now the questions come: >>> >>>1. Could Python be used in web programming ? (i guess yes ?) >>>2. If the answer of above is yes, then can we programms with Python in >>>both server and client side or either ? >>> >>> >>If by 'client side' you mean 'Python embedded in the HTML page' like >>PHP, I think it's possible but I tend to avoid it. >> >> > >Isn't that quite clearly *server-side*, not client side? AFAIK, all >PHP pages have the server doing the page generation, not the client. > > Yeah, it's still server side as far as where the processing is done. Since the OP point of reference was ASP and PHP, neither of which are true client-side technologies either, I made the assumption that by 'client-side' he was thinking in terms of the client presentation >Client-side would be like Java or Javascript is typically used. The >answer is still "yes", but it's really not a workable solution in >general because (a) the client machine needs Python installed and >registered for COM stuff, and (b) there are serious security concerns >doing this since Python doesn't have the security restrictions that >Javascript and Java do. > > Correct, my other fav language is Smalltalk and there are a few plugins for client side Smalltalk as well, but since they require users to download a plugin, I really don't see them as valid development models other than for internal usage for a paricular business or something, not general internet usage. >>First off, for any >>such HTML embedded scripting you have to have a server that while parse >>and execute the script. A lot of ISPs offer that for PHP but I'm not >>sure about for Python. More importantly, though, I'm not a big fan of >>the architecture of having HTML code interspersed with script coding. I >>think you'd end up with a better software design with a normal >>CGI-template approach >> >> > >Agreed on all that... > Back in the early 90s it seemed people were starting to take good software design, OOA and OOD, seperation of "Human Interface" from "Business Domain" etc...seriously. Then the web got big and all that seemed to go out the window.. From deets_noospaam at web.de Sat Dec 13 09:52:46 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2003 15:52:46 +0100 Subject: Quickcam and various platforms References: Message-ID: Hi > I am in the process of writing a few tools for various astronomers > who use quckcams and webcams for star imaging. I wish to be able to > write up packages for generic linux, windows and Max panther. I have > found for windows the VideoCapture module, which I have had some > remote success with. I have seen much for Video4Linux for which I > have no experience (yet). SO my question is this: > > Does anyone know how to access the cameras (USB specifically) in any > of these operating systems? I don't mind writing a new interface if > that's what it takes! I just had a very pleasant encounter with webcams on linux - I tried to use gnomemeeting from a knoppix distribution, and while gnomeeting itself made some trouble, the camera was detected correctly and e.g. gqcam can be used to get images. I even wrote a simple python-script to search for attached video-devices using some translated C-code with ioctl-calls. Worked like a charm. For the QuickCam I had to patch and recompile the kernel, as the module is not in the tree, but then it worked as expected. Diez From fredrik at pythonware.com Wed Dec 3 16:36:47 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Dec 2003 22:36:47 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> Message-ID: Peter Hansen wrote: > Wait a sec... are you telling me that my code, which has strings containing > binary data (which I believe has *always* been permitted), and which from > time to time might, say, produce an error traceback containing the content > from one such string and write it to a log file, then continue processing > safely, will now fail with an ugly crash because I haven't changed it to > specify a default encoding? (!!!) 8-bit strings can still contain 8-bit data. The only way you'll get a warning is if you use non-ASCII characters in source code, without specifying a source code encoding. The warning is issued by the compiler, not the runtime. (if you've used non-ASCII characters to embed *binary* string literals in your program, you deserve to be punished). The only way you'll get the "crash" the original poster had, is if you're trying to print Unicode strings containing non-ASCII data to an ASCII- only output stream. (if you print 8-bit strings to an ASCII stream, Python assumes you know what you're doing). From jjl at pobox.com Tue Dec 23 14:43:38 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 19:43:38 +0000 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> Message-ID: <871xqvjp5h.fsf@pobox.com> Jp Calderone writes: > On Tue, Dec 23, 2003 at 01:14:19PM +0000, John J Lee wrote: > > [snip] > > > > I just realised some of these methods of mine don't actually return > > iterators, but merely objects supporting the iterator protocol. In other [...] > > returns a lazy iterator). Would that surprise people from a method named > > .iter_foo()? > > Yes. return "iter(something)" instead of just "something". Good idea, thanks. John From zunbeltz at wm.lc.ehu.es.XXX Thu Dec 11 04:58:36 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 11 Dec 2003 10:58:36 +0100 Subject: About the use of **args References: Message-ID: "Fredrik Lundh" writes: I want to sum up some ideas in the thread: 1) setters and getters are not mandatory. 2) The usual way in Python is the direct access > [=] ... b.width # is get > b.width = # is set > del b.width # is del 3) If when setting some attribute there is necesary to have side effects, it can be achive defining __setattr__ and doing the right thing depend on the attribute. (It is possible to raise an exception when the attribute is not in a list/dictionary of usable attributes, to prevent typos and such kind of errors) 4) __getattr__ can be defined to deal with undefined attributes. For example it can handle in different way the attributes in a list of permited attributes (see point 3) 5) attributes that are computed in the fly, can be get like normal attributes using "property" (property is new in 2.3 or 2.2?) 6) attributes and methods that are no part of the user interface are named with and _ in the front. (This is a convention) Are those ideas correct? We can continue with the discussion!! Zunbeltz -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From mwh at python.net Tue Dec 16 05:45:50 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 16 Dec 2003 10:45:50 GMT Subject: [Python-Dev] rexec.py unuseable References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> Message-ID: "John Roth" writes: > I've also seen comments that none of the developers > was interested in fixing it, I think this is a little unfair. I think some of the developers are /interested/ in a fix, just noone has the time to provide one. Maybe that's all you meant. Of course, the nasty thing about security issues is that a 90% solution isn't a whole lot of use. > For myself, I'd prefer to see a facility where > the system would build an object structure > consisting *only* of standard objects, > including dicts, lists, tuples, strings, ints > and floats, and would reject anything else. > That is to say, no built-ins, no operators, > no object methods, no classes other than > the general use fundamental objects. > That's use case 2 above. How about http://www.livejournal.com/users/moshez/4120.html or similar? Cheers, mwh -- ARTHUR: Ford, you're turning into a penguin, stop it. -- The Hitch-Hikers Guide to the Galaxy, Episode 2 From aahz at pythoncraft.com Tue Dec 2 20:27:52 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2003 20:27:52 -0500 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: Message-ID: In article , Brett C. wrote: > >This is the twenty-eighth and twenty-ninth summaries written by Brett >Cannon (does anyone even read this?). Hey, I've sent you enough corrections on your drafts, do I need to read the final copy, too? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From sandorlevi at yahoo.com Sun Dec 7 03:45:41 2003 From: sandorlevi at yahoo.com (Levente Sandor) Date: 7 Dec 2003 00:45:41 -0800 Subject: finding python modules References: Message-ID: <8b5e42a6.0312070045.2b29a8a9@posting.google.com> >>> import xml.dom.minidom >>> xml.dom.minidom.__file__ '/usr/local/lib/python2.3/xml/dom/minidom.pyc' ---- levi Jay Dorsey wrote in message news:... > On Sun, Dec 07, 2003 at 12:54:06AM +0000, python newbie wrote: > > Guys, > > Very beginner question. > > I'm importing xml.dom.minidom at the top of my file. > > > > I'm trying to figure out where the heck this is. According to Quick Python, > > there should be folders on my drive > > (using XP), under c:\python23, named xml, then underneath: dom, etc. But > > there isn't. > > You missed one folder under the python folder: Lib. Full path should > resemble something like: > > C:\Python23\Lib\xml > > Sometimes you can also find modules installed in the site-packages directory > underneath the lib folder. From vivek at cs.unipune.ernet.in Sun Dec 7 23:03:36 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Mon, 8 Dec 2003 09:33:36 +0530 Subject: Some problems for exercises In-Reply-To: <6250403b.0312071222.3bfc53e0@posting.google.com>; from mikit@zoran.co.il on Sun, Dec 07, 2003 at 12:22:46PM -0800 References: <6250403b.0312071222.3bfc53e0@posting.google.com> Message-ID: <20031208093336.A15490@cs.unipune.ernet.in> On Sun, Dec 07, 2003 at 12:22:46PM -0800, Miki Tebeka wrote: > Hello Vivek, > > > 1. Basic Language facilities : (Data structures, control structures, > > input/output, object oriented programming etc.) > > > > 2. A brief (rather very brief) Introduction to GUI programming with Tkinter > > > > 3. CGI programming in Python > > > > 4. Database programming with PostgreSQL > > So, as usual I have turned to you u people for help :). Please suggest me some > > such problems and where to look for it. > > I suggest an electronic phonebook. The 1'st command line version > should be enough for 1 (open file, go over lines, use regexps, people > as classes and save them using pickle ...). Then add GUI for 2, web > interface for 3 and database for 4. > It is also nice to see a program evolving and you don't have to > explain too much time describing the problem when moving from one area > to the other. > It seems to me a good idea. Actually first I thought of a HRIS type of application. But soon I realized that it will be quite big for such a short time span, and after that I was unable to think of anything easier :(. But I think that an electronic phonebook will be good enough to cover the topics and also will be easier to implement. Thanks Miki, Vivek Kumar > HTH. > Miki. > -- > http://mail.python.org/mailman/listinfo/python-list From gumuz at looze.net Fri Dec 5 11:13:07 2003 From: gumuz at looze.net (Guyon Morée) Date: Fri, 5 Dec 2003 17:13:07 +0100 Subject: xml-rpc/twisted question Message-ID: <3fd0ae8c$0$245$4d4ebb8e@news.nl.uu.net> Hi all, Below this message you can see my code. It is a modified version of the twisted xml-rpc server examples. I am trying to figure out how to implement non-blocking methods. I found out that I have to use 'defer' to do that, but I have no clue how to do this. Unfortunately the documentation could not make this clear to(unless I am missing some docs). I have already added a function called xmlrpc_block to represent a actual 'blocking function'. I hope someone can show me how to modify this so the server does not block any other clients when xmlrpc_block is called. thanx, Guyon ==================================================================== #TestServer.py from twisted.web import xmlrpc, server from twisted.internet import reactor class Example(xmlrpc.XMLRPC): """An example object to be published.""" def xmlrpc_echo(self, x): """Return all passed args.""" return x def xmlrpc_block(self, duration=10): """block the instance for a specified duration""" import time time.sleep(duration) return "i slept %s seconds!" % (str(duration)) # this only runs if the module was *not* imported if __name__ == '__main__': r = Example() reactor.listenTCP(7080, server.Site(r)) reactor.run() From mwilson at the-wire.com Fri Dec 5 11:13:19 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 05 Dec 2003 11:13:19 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: In article , bokr at oz.net (Bengt Richter) wrote: >On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein wrote: >>That's true, but another answer is: you should use tuples for short >>sequences of diverse items (like the arguments to a function). You >>should use lists for longer sequences of similar items. >> >I'm curious what you're getting at. I.e., what does diversity or >similarity have to do with the choice? Is that an aesthetic thing? >(In which case 'should' should be qualified a bit, IWT ;-) >Or what am I missing? To me, it's a distinction without a difference. Tuples *act* like immutable sequences, and I use them that way. I don't know, though, that I won't get caught some day. Python 3.3 (#22, Jul 29 2013, 14:34:42) [MSC v.9200 96 bit (Intel)] on win96 Type "help", "copyright", "credits" or "license" for more information. >>> t = (1,4,7,34,789) Traceback (most recent call last): File "", line 1, in ? HomogeneityError: tuple elements are not diverse >>> Regards. Mel. From marks.pryorSHRUB at CHENEYverizon.net Sun Dec 7 16:39:13 2003 From: marks.pryorSHRUB at CHENEYverizon.net (Mark S Pryor) Date: Sun, 07 Dec 2003 21:39:13 GMT Subject: win32: tile desktop windows References: Message-ID: <56NAb.2359$nz.1406@nwrddc01.gnilink.net> "Mark S Pryor" wrote in message news:FmMAb.2211$nz.1624 at nwrddc01.gnilink.net... > > "Mark S Pryor" wrote in message > news:UaMAb.2170$nz.1129 at nwrddc01.gnilink.net... > > hello c.l.p., > > > I run my desktop at 2560 x 1024. When I get > > involved manually resizing and moving windows about, > > I keep thinking that I should be able to > > automate this with a Python script. > > oops, Win2k supports this from the taskbar! Rt. click and "Tile Windows Vertically" have a good weekend, msp From francisgavila at yahoo.com Mon Dec 22 20:56:28 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 20:56:28 -0500 Subject: return statement in functions References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: hokiegal99 wrote in message <93f5c5e9.0312221718.23e42dac at posting.google.com>... >I was told earlier (w/o explanation) that functions should return >something. I was under the impression that it was OK with Python to >leave the return statement off. Functions return something in Python, by definition. If you leave the return statement off, Python inserts an implicit 'return None' to the end of the text of your function. > Could someone enlighten me on why or >why not to use a return statement when defining functions? This is a philosophic question. The final end of a function is to take input and return output which is somehow based upon that input. The functional *construct* can be abused every which way (often validly) to violate any part of that statement: it can take arguments which don't matter; it can return things which are unrelated to the arguments; it can have all sorts of side effects that the caller isn't interested in, etc. >Below is >the bit of code I was told should return something: > >def fs_object_count(path): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > file_count += len(files) > dir_count += len(dirs) > print "Number of Files Examined: ", file_count > print "Number of Folders Examined: ", dir_count > print "Total Number of FS Objects:", file_count + dir_count The code is in poor style simply because it does multiple things at once in a way that is not terribly modular: namely, it does file/dir counts, and it prints results. Better would be this: def fs_object_count(path): """Return (numdirs, numfiles) in path and its subdirectories.""" file_count = 0 dir_count = 0 for root, dirs, files in os.walk(path): file_count += len(files) dir_count += len(dirs) return dir_count, file_count dn, fn = fs_object_count('mypath') print "Number of Files:", fn print "Number of Directories:", dn print "Total:", fn+dn You can have more complex/prettier output logic if you want, but the point is to make your functions as general as possible, while doing only one thing. (And that's not a contradiction!) -- Francis Avila From hwlgw at hotmail.com Sat Dec 27 06:24:14 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 03:24:14 -0800 Subject: Project dream References: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Message-ID: > [Rene Pijlman] > Aahz: > >You mean something like Chandler? > >http://osafoundation.org/Chandler_Compelling_Vision.htm > > Yes, that's what I meant. Although Chandler seems much more ambitious. > Very interesting project. I wonder how healty it is: their wiki is empty, the Mitch Kapor blog is stopped, there is not much recent news. But interesting certainly. From newsgroups at jhrothjr.com Sun Dec 21 17:46:50 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 17:46:50 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Terry Reedy" wrote in message news:x-idnT1qO-aKaniiRVn-iw at comcast.com... > > "John Roth" wrote in > message news:vu8dii9mh30bf9 at news.supernews.com... > > > > It doesn't matter. As you can see by my reply to > Bengt, > > the crux of the issue is that, in Ruby, the > function call > > syntax is *optional.* There is no way to make it > optional > > in Python, and it is not clear whether it should > be. > > > Just so you know, your adding as conclusion the > line > > > It's a non-starter for Python, though. > > did change how I read (and responded to) that (and > other) posts. Since there is no serious proposal > to change Python, there is no proposal to resist. It wasn't a serious proposal in the first place. The proposal was to take a look at some of the things in some other languages, and think about them. Somehow that got lost in the discussion. And I was quite serious about that. I have the feeling that there is a good deal of fossilization of the brain cells setting in. I could be wrong about that, but I begin to worry when I see Larry Wall ripping Perl apart and redesigning it, and I get the impression that the only reason for Python 3.0 (which seems to be the same distance in the future, regardless of when we talk about it) is to make a few relatively minor incompatible changes. John Roth > > Terry J. Reedy > > From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 23 10:50:01 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 23 Dec 2003 16:50:01 +0100 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: <3fe86429$0$186$e4fe514c@news.xs4all.nl> hokieghal99 wrote: > Here's how I call the report function: > > report(fs_object_count,clean_dir_names,etc., etc.) > You're forgetting to actually *call* the other functions too, (you just pass the functions themselves, as you see in your output, Python prints the function objects that you pass to the report function). So try this: report(fs_object_count(),clean_dir_names(),...) these you forgot: ^^ ^^ --Irmen From has.temp at virgin.net Tue Dec 2 17:32:50 2003 From: has.temp at virgin.net (has) Date: 2 Dec 2003 14:32:50 -0800 Subject: Separation of content and code for web (was Re: Python for web ?) References: <3FCB8535.F8F89132@engcorp.com> <915a998f.0312020325.7edb7fa@posting.google.com> Message-ID: <73c38014.0312021432.ee1ad1@posting.google.com> Peter Hansen wrote: > Anyone know of a Python-based approach using the same core concept? HTMLTemplate From fredrik at pythonware.com Thu Dec 11 01:14:47 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 07:14:47 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> <_DNBb.430596$0v4.20515253@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Spiffy" wrote: > Meanwhile, Fredo has provided a nice answer that WORKS... > along with an explanation of why my code didn't work. for the benefit of others, maybe you could tell us why your code didn't work? From mwh at python.net Sat Dec 27 06:10:54 2003 From: mwh at python.net (Michael Hudson) Date: Sat, 27 Dec 2003 11:10:54 GMT Subject: Project dream References: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > hwlgw at hotmail.com (Will Stuyvesant) writes: > > What would your favorite be? > > A CVS-like system for email. You'd receive all your messages on a > server somewhere. You'd then be able to connect your laptop to the > internet, download ("check out") your mail, and read and reply to it > offline (not necessarily all of it). When you dial up again, the > replies get sent out and stored ("checked in") on the server, the > messages that you read get marked as read, the ones you didn't read > don't get marked, etc. The CVS-like aspect is that you can do the > same thing from your office computer, your friend's computer, etc., so > you have the same messages checked out on multiple clients at the same > time. Up to here, this sounds like the idealized IMAP experience. Using Apple's mail.app offline isn't so different from this -- there are some bogosities in the implementation (in Jaguar), but the intent is clearly there. > The server automatically merges the "change sets" when you check any > in. Finally, the server shouldn't need any special protocol to > check messages in or out. It should be able to create a single > tarball or zipfile that you download, and accept a single tarball or > zipfile when you upload Mail.app can import from most formats and will upload on sync... of course, I like to have my mail on a machine where I have a shell too, which makes all this a little bit trival (it also means that when I'm online -- as now -- I use ssh + screen to acheive something a litle bit like what you describe). Cheers, mwh -- It's an especially annoying American buzzword for "business use, as opposed to consumer, research, or educational use". -- Tim Peters defines "enterprise" From tjreedy at udel.edu Fri Dec 26 00:14:46 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Dec 2003 00:14:46 -0500 Subject: indendation question References: Message-ID: "km" wrote in message news:mailman.115.1072408950.684.python-list at python.org... > Hi all, > > What is the standard and recommended way of indendation one should get to use in python programming ? is it a tab or 2 spaces or 4 spaces ? i am confused. kindly enlighten The recommendation in the early numbered PEP on style is 4 spaces. This is the standard for the standard library. TJR From exarkun at intarweb.us Tue Dec 23 14:50:11 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 23 Dec 2003 14:50:11 -0500 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> <3fe86429$0$186$e4fe514c@news.xs4all.nl> Message-ID: <20031223195011.GA25803@intarweb.us> On Tue, Dec 23, 2003 at 02:05:25PM -0500, hokieghal99 wrote: > Jp Calderone wrote: > [snip] > > > > No. "return new_dname" terminates execution of the function. If you > > want many results, you need to collect them in a list and return the > > list, or use a generator. > > > > Jp > > That's odd, it seems silly to terminate something that should be > recursive (os.walk) before it's finished being recursive. What's the > logic behind that idea? > That is what "return" does. Always. :) With no regard for context, recursive or not (the implementation of os.walk itself may be recursive, or it may not be, but I don't think it has any bearing on what "return" should do, since the return isn't even inside the definition of os.walk!) If this is surprising, you should probably take some time to review the fundamentals of the language. I would recommend either the official tutorial or the book "How to Think Like a Computer Scientist": http://www.python.org/doc/tut/ http://www.ibiblio.org/obp/thinkCSpy/ Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rmunn at pobox.com Fri Dec 26 15:21:04 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 26 Dec 2003 20:21:04 GMT Subject: hex array to array of 16 bit numbers? References: <9b849915.0312250206.61d89841@posting.google.com> Message-ID: Todd Gardner wrote: > Hello everyone, > > I would really appreciate some of your expertise or even just > pointers. How do I convert this hex array variable "buffer" to array > of 16 bit numbers? > >>>> >>>> from ctypes import * >>>> buffer = c_buffer(8) >>>> status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, > sampleRate) >>>> print "repr(buffer.raw) =", repr(buffer.raw) > > repr(buffer.raw)= '\xcd\x00\xce\x00\xce\x00\xce\x00' >>>> > > Any ideas would be greatly appreciated! I think the struct.unpack() method is what you're looking for here: http://www.python.org/doc/current/lib/module-struct.html If you've got four 16-bit numbers, then: import struct status_tuple = struct.unpack('4h', buffer.raw) should give you what you want. Read the documentation for the meaning of the various format characters. -- Robin Munn rmunn at pobox.com From aaron at reportlab.com Thu Dec 11 19:10:05 2003 From: aaron at reportlab.com (Aaron Watters) Date: 11 Dec 2003 16:10:05 -0800 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312110538.568014ef@posting.google.com> Message-ID: <9a6d7d9d.0312111610.30614ae0@posting.google.com> Duncan Booth wrote in message news:... > aaron at reportlab.com (Aaron Watters) wrote in > news:9a6d7d9d.0312110538.568014ef at posting.google.com: > > > regarding the use of stackless in > > http://xsdb.sourceforge.net > > "Fredrik Lundh" wrote in message > > news:... > >> Aaron Watters wrote: > >> > 5) use an event loop and use a generator for the relevant code; > >> when you discover that you need to pause, yield to the framework. > > > > Please tell me I'm missing something, but I don't think > > this will really help. ... > > The generator solution may not be appropriate for your task, but it isn't > entirely accurate to say that you can only go one level deep.... > > The rule to follow is simply: any function which wants to yield, or which > calls a function that wants to yield has to be a generator and has to be > called from a 'for' loop which itself yields.... Yes. I see this would work. But this would then have to be pervasive throughout my code -- and even in client code that uses the xsdb code directly (but not from a remote client).... yuck. No thanks :(. The acceptible options still are threads, stackless, or punt. -- Aaron Watters === How do zen masters walk through walls? Doors. From nospam at freeworld.fr Thu Dec 11 11:46:20 2003 From: nospam at freeworld.fr (Lucas Branca) Date: Thu, 11 Dec 2003 16:46:20 GMT Subject: Zope import PythonScript.standard unauthorized Message-ID: Hi, I've just insalled Zope to test a web application by thirdy part .... well .... it's very embarrassing cause I'm not able to see it at work because of Zope ..... (yeah... I'm really newbie :( ) I found out that the problem is in Products/PythonScript permission. To test them, in the ZMI, I created this script and then I tested it ============================================== SCRIPT ============================================== # Example code: from Products.PythonScripts.standard import html_quote, urlencode return 1 ============================================== OUTPUT DU TEST ============================================== Zope has encountered an error while publishing this resource. Error Type: ImportError Error Value: import of "urlencode" from "Products.PythonScripts.standard" is unauthorized In Zope Bible they say there is a trick to escape this control using "External Methods", but it should be another way because the application I have to test doesn't use them at all ... any useful suggestion ..........? Thank you very Lucas btw: Zope = Zope 2.5.1 Python= 2.1.3 From edcjones at erols.com Wed Dec 24 09:00:30 2003 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 24 Dec 2003 09:00:30 -0500 Subject: Using revised tempfile module Message-ID: <3fe99ce2$0$4744$61fed72c@news.rcn.com> #! /usr/bin/env python import os, tempfile # I have written code like this several times. It uses the deprecated # function tempfile.mktemp. How do I write this with the new tempfile # functions? def do_something(filename1, filename2): os.system('cat %s > %s' % (filename1, filename2)) filename1 = tempfile.mktemp() filename2 = tempfile.mktemp() try: f = file(filename1, 'w') f.write('abcd') f.close() do_something(filename1, filename2) g = file(filename2, 'r') print g.read() g.close() finally: if os.path.exists(filename1): os.remove(filename1) if os.path.exists(filename2): os.remove(filename2) From no.spam at no.spam.com Wed Dec 31 04:03:21 2003 From: no.spam at no.spam.com (Maciej Sobczak) Date: Wed, 31 Dec 2003 10:03:21 +0100 Subject: Uplevel functionality Message-ID: Hello, I would like to know if there is any possibility in Python to execute arbitrary scripts in the context higher in the stack frame. In essence, I would like to have the equivalent of the following Tcl code: proc repeat {n script} { for {set i 0} {$i < $n} {incr i} { uplevel $script } } This allows me to do: repeat 5 {puts "hello"} prints: hello hello hello hello hello Or this: set i 10 repeat 5 {incr i} puts $i prints: 15 That second example shows that the script provided as a second parameter to the "repeat" procedure (the script is "incr i") is executed in the context where the procedure was called, not locally in the procedure itself. The strongest analogy to the above repeat procedure in Tcl would be a hypothetical Python function: def repeat(n, script): for i in xrange(n): EVALUATE script HIGHER IN THE STACK #??? Thank you very much, -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ From torsten.rueger at hiit.fi Wed Dec 17 06:22:25 2003 From: torsten.rueger at hiit.fi (Torsten Rueger) Date: Wed, 17 Dec 2003 13:22:25 +0200 Subject: udp broadcast example, please Message-ID: <4A2A5910-3083-11D8-BB2B-000A959C1BB0@hiit.fi> Moi, sorry, but I've searched and searched to find exact information on how to do a simple udp broadcast client/server, but can find it: I want to have a thread pinging (very small message) and possibly the same thread receiving maybe with a 1 second timeout. And the same code should be able to run as multiple instances on the same machine. Could someone with experience please post the 10 lines to make this happen. Please no general comments or things that "should" work. I've tried for hours with various socket options and addresses, so I would very much appreciate working code. Thanks Torsten From fnord at u.washington.edu Mon Dec 22 16:25:55 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 22 Dec 2003 13:25:55 -0800 Subject: How do I test if an object is a sequence? References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: > Is there a common idiom for testing if an object is a sequence? Try iterators... def is_sequence(thing): try: iter(thing) return True except TypeError: return False Of course, this will return True for strings, but I suspect most people would say that strings are sequences. You will have to special-case them. From ryan.walker5 at verizon.net Mon Dec 1 21:09:31 2003 From: ryan.walker5 at verizon.net (Ryan Walker) Date: Mon, 1 Dec 2003 21:09:31 -0500 Subject: language learning vs. process Message-ID: Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that tell you all about the language. That is, what are the methods, functions, modules, syntax, punctuation, etc. No problem there! Meanwhile, I'm finding that there is very little (that I can find) about how to do basic logistical things related to using python and implementing programs. For example: how to run a program. That's pretty basic, but I don't see anything in the tutorials about it. With IDLE, it's easy enough: just hit F5. But working on my server via Putty, trying to get a concrete, meaningful result, it's hit and miss. For example, I find that sometimes a program will run if I import it. I typed "import smtpmail" and it ran -- it asked me to input From, To, Subj, Message. Other times, I type in "import smtpmail" and it imports but doesn't run. My server is Unix. Typing "python smtpmail.py" doesn't do it. That seems to be what a few websites say to do to run a program. Doesn't work for me. It returns 'File "", line 1' and a little carrot pointing up at the 'l' in smtpmail. I know it's on the path since I can import it. And the permissions are 755. Another example of a very basic problem I can't find a solution to in any tutorial: how to log in to an SMTP server (authentication). My web searches have turned up only a few snippets of listserv conversations between people who already know enough about the subject that I'm not able to divine anything from the code they pass back and forth. A search on Python.org doesn't turn up anything that would help newcomers. So basically, what I'm saying is, there is a wealth of information about how to concatenate strings and stuff like that, but I'm finding it very difficult to get started with basic processes and logistical things. For example, it took me longer than I care to admit to figure out how to append the sys.path (that's actually in the tutorial but it's somewhat inconspicuous.) My ideal beginner resource would be a complete, step-by-step explanation of how to implement a simple program -- starting with typing "python" at the command prompt and ending with some kind of concrete result. Then, with a complete understanding of the process of writing and implementing (emphasis on the latter) a program, my efforts to learn the content and syntax of the language itself will be a lot more meaningful. That is, I can learn things like what a string is and have some confidence that I'll actually be doing something (other than playing with a calculator) that can provide something of value to end users in far flung places. Might seem weird to start with learning process and implementation, since it's all dependent to a large extent on using the language properly, but I do think it's possible to learn implementation first (with a bare minimum of language learning) and then go back and learn more about the language. Just something to think about for the excellent people who teach ingrates like me how to program. If anyone has any pointers on where to get more how-to information more oriented towards process/logistics please let me know. Thanks! Ryan From newsgroups at jhrothjr.com Sun Dec 21 07:44:59 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 07:44:59 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Skip Montanaro" wrote in message news:mailman.386.1071964951.9307.python-list at python.org... > > John> The world changes, and ideas that seemed to be perfectly > John> appropriate five or ten years ago may no longer be such. Small > John> languages with a limited audience have a perfect right to be as > John> quirky or as "pure" as their authors want. Once they get beyond > John> that point, there's a bit of social responsibility involved in > John> addressing common problems. > > So fork Python and show how it could be done better. If that's the case, > people will either drift over to Python-JR, or (some of) your ideas will > find their way back into Python-GvR. I'm not likely to do that for two reasons. One is that, at this point in my life, I'm not a C programmer. I don't even have a functional C compiler on my machine. The other is that I don't particularly like the notion of adding more and more options to the mix. I'm much more concerned with the social issue of how software development is done, and another variation on a good idea simply isn't my way of approaching the issue. > > Or, as in the Emacs/XEmacs split, darts may be thrown across the void for > the forseeable future. ;-) John Roth > > Skip > From admin at ferger.de Tue Dec 16 07:35:08 2003 From: admin at ferger.de (Olaf Ferger) Date: Tue, 16 Dec 2003 13:35:08 +0100 Subject: Advice for PostgreSQL References: <3fde873c$1@clarion.carno.net.au> Message-ID: On Tue, 16 Dec 2003 15:17:38 +1100, Steve wrote: >Can someone please point me out to some module/library for using >PostgreSQL from python? Perhaps a tutorial as wel? Thanks! Try module 'psycopg' from www.initd.org ! Regards, Olaf -- EOP From peter at engcorp.com Tue Dec 23 10:39:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Dec 2003 10:39:59 -0500 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: <3FDDC8FE.AED055CB@engcorp.com> Message-ID: <3FE861CF.FCE33746@engcorp.com> Lonnie Princehouse wrote: > > Peter Hansen wrote in message news:<3FDDC8FE.AED055CB at engcorp.com>... > > > ... > > Perhaps Photoshop "transparently" (no pun intended) saves the alpha data > > to some other location, but magically restores it when you reload the .jpg? > > > > That pun was _clearly_ intentional. ?? Actually it was not, but I'm unclear why you bother saying otherwise without a smiley... were you trying to be funny, or do you somehow have better knowledge of what I intended than I did? (It was *unclearly* not intentional, perhaps, but it was not clearly intentional.) -Peter From gerold.penz at aon.at Mon Dec 29 02:28:29 2003 From: gerold.penz at aon.at (Gerold Penz) Date: Mon, 29 Dec 2003 08:28:29 +0100 Subject: Python deutsch In-Reply-To: References: Message-ID: <3fefd79d$0$11368$91cee783@newsreader02.highway.telekom.at> Werner.Warweg schrieb: > Kann mir einer der deutsprachigen Group-Teilnehmer empfehlen: > - welche deutschen B?cher? > - welche Newsgroup ist die beste? Es gibt so viele! Hallo Werner! Habe soeben eine deutsche Newsgroup zum Thema Python entdeckt: Newsserver: news.gmane.org Gruppe: gmane.comp.python.general.german Habe gelesen, dass man lesen darf. Zum Schreiben muss man sich anmelden. mfg Gerold Penz -- ______________________________________________________________________ Gerold Penz | Erlasse niemals ein Gesetz, Email: gerold.penz at aon.at | das mehr Freiheiten einschr?nkt SW3: http://www.sw3.at | als es Freiheiten sch?tzt. Bcom: http://www.bcom.at | From swalters_usenet at yahoo.com Tue Dec 30 17:33:39 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Tue, 30 Dec 2003 22:33:39 GMT Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> Message-ID: On Tue, 23 Dec 2003 17:54:13 -0500, Jp Calderone wrote: > Yea, I hear that. Work is being done on speeding it up (pretty much the > only development on it now is optimization). I don't know how it will end > up, but things look promising so far. On the other hand, if you don't > want to wait for that to be finished... Ye olde time mantra: Make it work Make it right Make it fast From fBechmann at web.de Mon Dec 29 04:33:59 2003 From: fBechmann at web.de (Frank Bechmann) Date: 29 Dec 2003 01:33:59 -0800 Subject: just another default argument value gotcha Message-ID: Eventually most of you will not learn much from this because it's just another event in the 'default argument value gotcha' series, but because it cost me some hours yesterday to spot this 'error' in a famous python tool I thought it might still help other people to save some time. I tried to use some method which was documented to write to 'sys.stdout' per default so that changing 'sys.stdout' to bind to another object should allow to get grip on the method's output. but that didn't work - reason was that that 'sys.stdout' was used as default argument value for the method. The following code describes it better then my english can do, so as it seems for me, one should make sure to use the 'f2' variant. import StringIO, sys def f1(msg, out=sys.stdout): out.write("%s\n" % msg) def f2(msg, out=None): if not out: out = sys.stdout out.write("%s\n" % msg) if __name__ == "__main__": buf = sys.stdout = StringIO.StringIO() f1("calling f1") f2("calling f2") data = buf.getvalue() buf.close() sys.stdout = sys.__stdout__ print "=========\n", data results in: calling f1 <-- written directly by 'f1' ========== => redirection didn't work calling f2 <-- written from data stored in 'buf' running the following greps on this machine brought only 2 possible spots, but that doesn't mean too much since this is our gaming computer with only a very basic python installation; eventually someone with a real huge package list would bring up more hits: $ find . -name '*.py' -exec grep -H '\bdef\b.*\(.*\=sys.stdout.*\)[ \t]*:' \{} \; >> ./test/test_grammar.py:def tellme(file=sys.stdout): $ find . -name '*.py' -exec grep -H '\bdef\b.*\(.*\=sys.stderr.*\)[ \t]*:' \{} \; >> ./unittest.py: def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1): From michele.simionato at poste.it Fri Dec 12 01:44:15 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 11 Dec 2003 22:44:15 -0800 Subject: Generator state/parameters References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> <7xisknr9nm.fsf@ruckus.brouhaha.com> Message-ID: <95aa1afa.0312112244.3baf7883@posting.google.com> mertz at gnosis.cx (David Mertz, Ph.D.) wrote in message news:... > But the state need not be global, just a mutable object yielded by a > generator. As I thought about this fact, I have come to find Raymond > Hettinger's proposals for enhancing simple generators less urgent (but I > probably still vote +1, though now moot). > > >>> def echo(): > ... message = [None] > ... while message[0] != "EXIT": > ... yield message > ... > >>> for mess in echo(): > ... if mess[0] is not None: print mess[0] > ... mess[0] = raw_input("Word: ") > ... > Word: foo > foo > Word: bar > bar > Word: EXIT > > This is a toy example, but the point is that we are perfectly able to > pass data back into a generator without using global state. A more verbose but arguably more elegant way would be to wrap the generator in a class. Let me repost some code I wrote some time ago. """An object-oriented interface to iterators-generators""" class Iterator(object): """__gen__ is automatically called by __init__, so must have signature compatibile with __init__. Subclasses should not need to override __init__: you can do it, but you must do it cooperatively or, at least, ensure that __gen__ is called correctly and its value assigned to self.iterator. """ def __init__(self,*args,**kw): super(Iterator,self).__init__(*args,**kw) self.iterator=self.__gen__(*args,**kw) def __gen__(self,*args,**kw): "Trivial generator, to be overridden in subclasses" yield None def __iter__(self): return self def next(self): return self.iterator.next() class MyIterator(Iterator): def __gen__(self): self.x=1 yield self.x # will be changed outside the class yield self.x iterator=MyIterator() print iterator.next() iterator.x=5 print iterator.next() Wrapping the generator in the class, I can pass parameters to it (in this case x). IOW, here the generator has an explicit "self" rather than an implicit "__self__" as in the PEP. I am not sure if I like the PEP, wouldn't be easier to have a built-in iterator class? Michele From jay at jaydorsey.com Sun Dec 7 12:31:09 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sun, 7 Dec 2003 11:31:09 -0600 Subject: OT: Spell checker In-Reply-To: References: Message-ID: <20031207173109.GA21428@gentoo.Earthlink.net> On Sun, Dec 07, 2003 at 06:24:08PM +0100, Patrick Useldinger wrote: > Hi all, > > Therefore, I am looking for a spell-checker that works on pure text > files. Not the kind where you can enter *one* word at a time, and not > the kind that will work only with an online connection. > > I have spend a lot of time googling, but to no avail. Can anybody point > me into the right direction? Assuming ispell and aspell aren't viable for you, you could download the 12dicts wordlist from sf (http://wordlist.sourceforge.net/12dicts-readme.html) and write your own. I believe there are also python wrappers for aspell and ispell if either of those meet your needs. -- Jay Dorsey jay at jaydorsey dot com From anton at vredegoor.doge.nl Tue Dec 2 08:38:33 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 02 Dec 2003 14:38:33 +0100 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> Message-ID: <3fcc9577$0$7676$3a628fcd@reader1.nntp.hccnet.nl> lutz at rmi.net (Mark Lutz) wrote: >I'm using Python on a Sharp Zaurus C760 these days, >one of the Japan models that you can get converted >to English from a number of importers. It comes >with a full VGA (640x480) swivel screen, and a nice >keyboard. The keyboard isn't full size, but it's >much better than the thumbs-key input of most PDAs. > >Python runs well on this machine too, with the Sharp >ROM; you can code and run both console and Qtopia >GUI applications. You can also run vim, gcc, mySql, >SQLite, Apache, and so on. With gcc, you can even >code and compile Python C extensions right on the PDA. >There's a new X11 ROM as well (haven't tried it yet). This machine is very interesting for me too. But three things have kept me from acquiring it. First it's a bit pricey, probably about 700 euros or so? Prices tend to get better so maybe it will become possible in a few months. Secondly it's not really possible to have a look at it before buying, because one has to mail order it, but maybe this will change too in the near future. Third and most important point for me is that I have some application I want to use it for, it's my own little pygobo freeware script that "nobody" wants to download but which is in my opinion the best sgf-file viewer for baduk there is (at least for someone that can program Python). However this viewer is written using TKinter and there seems to be no such thing as Tkinter on any pda. Could you please comment on any of these points and give some guesstimate of the time frame in which such a machine will become feasible for me. I'd *really* like to review go-files while lying in bed or while walking in the woods or whatever and my script is already ideally suited for use on such a machine with its full-screen mode and rotatable go-board (sorry for the plugging) Anton From bapeters at terastat.com Tue Dec 9 14:24:50 2003 From: bapeters at terastat.com (bapeterson) Date: Tue, 09 Dec 2003 19:24:50 GMT Subject: PY2EXE problem with VPYTHON Message-ID: <6kpBb.5398$8y1.26724@attbi_s52> I'd like to use PY2EXE to "compile" a program using the VPYTHON module (www.vpython.org). I have an example where this was previously done to the demo script: Hanoi.py (a towers of Hanoi demo) a couple of years back. When I try and duplicate this I get the following warnings of missing modules: warning: py2exe: ********************************** warning: py2exe: * The following modules were not found: warning: py2exe: * Carbon.Folder warning: py2exe: * Carbon.Folders warning: py2exe: * dotblas warning: py2exe: * fcntl warning: py2exe: * readline I have no idea what Carbon* is, nor dotblas. fcntl was internalized in Python23 and readline is certainly around. I'm using Active state Python 2.3.2 and PY2EXE 0.4.0 on Win XL Anyone have an idea as to what to change to get this to work? From gh at ghaering.de Thu Dec 18 19:29:22 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 19 Dec 2003 01:29:22 +0100 Subject: Standalone client database for Python? In-Reply-To: <9a6d7d9d.0312181224.2af62021@posting.google.com> References: <9a6d7d9d.0312181224.2af62021@posting.google.com> Message-ID: <3FE24662.1050501@ghaering.de> Aaron Watters wrote: > I've also heard good things about pySQLLite and metakit although > they both require installing extension modules and supporting > libraries. Well, just for clarification: PySQLite does indeed depend on SQLite, but the Windows binaries are completely standalone - they're statically linked against SQLite. Also, SQLite is pretty damn fast and scales to multi-gigabyte databases, on disk or in-memory. -- Gerhard From try_vanevery_at_mycompanyname at yahoo.com Thu Dec 25 17:13:52 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 25 Dec 2003 14:13:52 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "Ville Vainio" wrote in message news:du73cb8k1kg.fsf at lehtori.cc.tut.fi... > > It's just Usenet - people use the bandwidth for much less interesting > stuff anyway. Also, I think mentioning a project one is about to > embark on in Usenet is a good idea, for finding the possible prior art > or like-minded individuals if nothing else. Yes, that is indeed a peripheral consideration. What if someone in comp.lang.python had *already* started porting Freeciv to Python? Or was contemplating it? -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Desperation is the motherfucker of Invention." - Robert Prestridge From logistix at cathoderaymission.net Fri Dec 19 22:30:36 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 19 Dec 2003 19:30:36 -0800 Subject: SQL Server Questions References: Message-ID: <3c91a864.0312191930.fb8d02c@posting.google.com> > Also, I'm connecting to a Microsoft Exchange Mail server using the methods > described in Mark Hammond and Andy Robinson's Book "Python Programming on > Win 32". My problem is that when I connect to the Exchange Server, a dialog > box pops up to verify the connection. Since I'm writing a utility script, > I'd just like to connect without a user having to get involved. Is this > possible? > A little off topic for python, but I'm guessing your connection uses an outlook profile to connect to the server. Starting with Outlook 2000 SP 2, you start getting warning dialogs about automated processes trying to access your email system. This was done to stop some .vbs worms from going crazy. Fix 1: Install a version of Outlook before 2000 SP 2. Fix 2: Track down the registry hack to disable the dialog. From rmunn at pobox.com Fri Dec 26 14:49:24 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 26 Dec 2003 19:49:24 GMT Subject: dynamic typing question References: Message-ID: <8h0Hb.15473$aw2.8625724@newssrv26.news.prodigy.com> Jason Tesser wrote: > Hi, > > > >> Along with everything others have already written--that >> you want to focus on test-driven development, that Python >> is a proven success in Serious Applications, and so on-- >> your description raises a few concerns in my mind: >> 1. Why, in your mind or your teammate's, >> is dynamic typing a "lack"? What, pre- >> cisely, is the benefit of static typing? >> There are a number of legitimate >> answers. It occurs to me that, without >> precision on which interest you, we >> might be missing an opportunity to >> clarify "The Python Way" significantly. > > The typing errors that would not be found until runtime. I've found pychecker to be very useful in catching those: http://pychecker.sourceforge.net/ -- Robin Munn rmunn at pobox.com From mwh at python.net Mon Dec 8 06:02:57 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Dec 2003 11:02:57 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: "Martin v. L?wis" writes: > Ville Vainio wrote: > > > What, has .NET suddenly turned out to be popular while I wasn't > > watching? > > Where I work, .NET is pretty popular. People are fascinated of > introspection/reflection, (relative) platform-independence, > ubiquitous serialization, powerful development tools, ... > and the back-up of a large company. Oh :-) More sponsorship for the PSF, please! Cheers, mwh -- I have a feeling that any simple problem can be made arbitrarily difficult by imposing a suitably heavy administrative process around the development. -- Joe Armstrong, comp.lang.functional From evanda at remingtons.org Thu Dec 18 18:22:54 2003 From: evanda at remingtons.org (Evanda Remington) Date: Thu, 18 Dec 2003 17:22:54 -0600 Subject: re troubles Message-ID: <20031218232254.GA22440@remingtons.org> I'm trying to filter some rows of an html table out, based on their contents. For input like: """ << want to filter << this out. <<
    Lasers17
    kittens8
    robots8
    """ I would like to completely remove the (3 line) table row that makes mention of kittens. The regexp I have tried to use is: r".*?kittens.*?". When compiled and used with subs("",data), strangely removes everything from the first "" to the first "" after kittens. That is, the ".*?" notation works in the second half, but not in the first half. It behaves the same as ".*" should. Any advice? -e -- Evanda Remington evanda at wreck.org From kmneilso at yahoo.com Sun Dec 14 13:50:29 2003 From: kmneilso at yahoo.com (Kerry Neilson) Date: 14 Dec 2003 10:50:29 -0800 Subject: Idle won't start Message-ID: For the past couple of months, Idle won't start when I invoke it. I am at a complete loss for why this is. When this happens, they python command line still starts, and python works fine otherwise. Most interesting to me is that a reboot won't fix the problem. But if I just try it again sometime later it will work. Anyone have any ideas? I'm running python 2.3 on windows 2000 professional. From gumuz at looze.net Tue Dec 2 11:03:50 2003 From: gumuz at looze.net (Guyon Morée) Date: Tue, 2 Dec 2003 17:03:50 +0100 Subject: slightly OT: how do you do that? References: Message-ID: <3fccb7e6$0$257$4d4ebb8e@news.nl.uu.net> And mailman is written in Pythoon too! "Gerhard H?ring" wrote in message news:mailman.48.1070376629.16879.python-list at python.org... > dan wrote: > > I recall reading somewhere that posts to c.l.p are crossposted to a > > python mailing list. Does anyone have a pointer to the technical > > information on how this is set up? I'm involved in a newsgroup > > proposal and this issue has come up. > > python-list is managed by Mailman, so I suppose the Mailman docs will describe how > to set up the mail-news gateway. > > -- Gerhard > > From ville.spammehardvainio at spamtut.fi Sat Dec 27 05:27:47 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 27 Dec 2003 12:27:47 +0200 Subject: Version controlled mailing (was Re: Project dream References: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > > What would your favorite be? > > A CVS-like system for email. You'd receive all your messages on a [..] This sounded quite fascinating. It also sounded quite doable w/ Subversion, w/ its "Properties" (metadata) and Python API. > check any in. Finally, the server shouldn't need any special protocol > to check messages in or out. It should be able to create a single > tarball or zipfile that you download, and accept a single tarball or > zipfile when you upload No biggie, but it might still be useful for the system to be 100% accessible from a normal Subversion client. OT: Subversion (http://subversion.tigris.org) is finally going to hit Beta and 1.0 Real Soon Now (tm). I read that it might be even during this year, but that's probably not going to happen. -- Ville Vainio http://www.students.tut.fi/~vainio24 From james.kew at btinternet.com Wed Dec 31 04:51:20 2003 From: james.kew at btinternet.com (James Kew) Date: Wed, 31 Dec 2003 09:51:20 -0000 Subject: Is Python Mac Centric??? References: Message-ID: "hokieghal99" wrote in message news:bss8qn$mb7$1 at solaris.cc.vt.edu... > Python installation is much more cumbersome on > Windows. The user has to dl Python and then Mr. Hammond's extensions to > get up to speed with the new Macs out of the box. Or install the ActiveState distro, which has pythonwin pre-installed. One install and off you go. To be honest, too, I'm not sure how useful the pythonwin extensions are for new Python users -- if you're not interested in banging around with the Windows API, then base Python has all you need. Although I do very much like the pythonwin IDE. James From exarkun at intarweb.us Thu Dec 18 10:37:30 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 18 Dec 2003 10:37:30 -0500 Subject: Compiling an *.exe from Python script In-Reply-To: <9b849915.0312172345.628fd9d5@posting.google.com> References: <9b849915.0312172345.628fd9d5@posting.google.com> Message-ID: <20031218153730.GA8158@intarweb.us> On Wed, Dec 17, 2003 at 11:45:51PM -0800, Todd Gardner wrote: > > To actually compile I guess one can use... > psyco-1.1.1-win-2.3.zip > psyco does compilation. It does not produce stand-alone executables. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From lkcl at lkcl.net Tue Dec 16 14:58:56 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 19:58:56 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> Message-ID: <20031216195856.GK17021@lkcl.net> On Tue, Dec 16, 2003 at 08:39:37PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > i think the only really sensible way forward is to begin from a > > sound basis - one that is going to be a big job to add retrospectively, > > but a simple beginning can be made. > > > > proposal: how about building ACLs into the python codebase? > > I fail to see how ACLs are a sound basis to solve the problem that in the initial message to the list, i confused the concept of acls with "capabilities". sorry about that. l. From Dick.Zantow at lexisnexis.com Wed Dec 10 13:31:44 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Wed, 10 Dec 2003 13:31:44 -0500 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > "rzed" writes: > [...] > >> The reason people chose to mix their cases is that one-case code is >> difficult to read. > > no it isn't. it isn't even difficult to read one-case english. > so you say, and you illustrate by showing one line. but if instead you have a block of a lot of text, or if you have code that is placed in close proximity for line after line you may have reason to think otherwise. i know i did in the monocase pl/i world and i was not alone in that; everyone else in the shop complained about it from time to time. it is never an issue that a single identifier is easier or more difficult to read in a single case; it is an issue when the context is broader. a secondary issue is that underscores require the use of the shift key on a standard typewriter so they are no easier to enter than upper case letters and they add no information that the interspersed capitals do not. whether they make text easier to read than camelcase stuff is a matter of opinion and is based on what people are used to. i went from one form to the other and had no trouble adjusting; it took very little time for me to come to prefer camelcase. judging by its prevalence in a big chunk of the coding world, others have managed to make the same adjustment, and i would guess at least many of them have the same preference. -- rzed From barry at python.org Wed Dec 31 13:22:35 2003 From: barry at python.org (Barry A. Warsaw) Date: Wed, 31 Dec 2003 13:22:35 -0500 Subject: RELEASED Mailman 2.1.4 Message-ID: <16371.5099.61671.387868@gargle.gargle.HOWL> I have released Mailman 2.1.4, a bug fix release that also contains support for four new languages: Catalan, Croatian, Romanian, and Slovenian. This release also contains a fix for a cross-site scripting vulnerability in the 'admin' cgi script (see CAN-2003-0965). There is also an expanded ability to filter message headers, nominally to provide better support when Mailman is used in conjunction with upstream spam and virus filters. The full source tarball has been made available from the usual sites. Sorry, there is no patch available yet, but you should be able to install Mailman 2.1.4 over your existing 2.1.x installation. See http://sourceforge.net/project/showfiles.php?group_id=103 for links to the downloadable files. After installing, be sure you restart your Mailman daemon by doing a "mailmanctl restart". IMPORTANT: You will want to re-run configure before doing a make install. See also: http://www.list.org http://mailman.sf.net http://www.gnu.org/software/mailman Enjoy, and have a Happy New Year. -Barry -------------------- snip snip -------------------- 2.1.4 (31-Dec-2003) - Close some cross-site scripting vulnerabilities in the admin pages (CAN-2003-0965). - New languages: Catalan, Croatian, Romanian, Slovenian. - New mm_cfg.py/Defaults.py variable PUBLIC_MBOX which allows the site administrator to disable public access to all the raw list mbox files (this is not a per-list configuration). - Expanded header filter rules under Privacy -> Spam Filters. Now you can specify regular expression matches against any header, with specific actions tied to those matches. - Rework the SMTP error handling in SMTPDirect.py to avoid scoring bounces for all recipients when a permanent error code is returned by the mail server (e.g. because of content restrictions). - Promoted SYNC_AFTER_WRITE to a Default.py/mm_cfg.py variable and make it control syncing on the config.pck file. Also, we always flush and sync message files. - Reduce archive bloat by not storing the HTML body of Article objects in the Pipermail database. A new script bin/rb-archfix was added to clean up older archives. - Proper RFC quoting for List-ID descriptions. - PKGDIR can be passed to the make command in order to specify a different directory to unpack the distutils packages in misc. (SF bug 784700). - Improved logging of the origin of subscription requests. - Bugs and patches: 832748 (unsubscribe_policy ignored for unsub button on member login page), 846681 (bounce disabled cookie was always out of date), 835870 (check VIRTUAL_HOST_OVERVIEW on through the web list creation), 835036 (global address change when the new address is already a member of one of the lists), 833384 (incorrect admin password on a hold message confirmation attachment would discard the message), 835012 (fix permission on empty archive index), 816410 (confirmation page consistency), 834486 (catch empty charsets in the scrubber), 777444 (set the process's supplemental groups if possible), 860135 (ignore DiscardMessage exceptions during digest scrubbing), 828811 (reduce process size for list and admin overviews), 864674/864676 (problems accessing private archives and rosters with admin password), 865661 (Tokio Kikuchi's i18n patches), 862906 (unicode prefix leak in admindb), 841445 (setting new_member_options via config_list), n/a (fixed email command 'set delivery') From martin at v.loewis.de Thu Dec 18 16:18:12 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Dec 2003 22:18:12 +0100 Subject: C API HowTo ? accessing objects described by dotted string from a (PyObject * ) References: Message-ID: mhoegeman at ixiacom.com (Mike Hoegeman) writes: > -- i have a PyObject * that is a instance of an object > -- i need to access a subobject of that (PyObject *) that is > described to me as a dotted string, e.g.: > > > "subobject1.listsubobject2[-1].subobject3" > > In other words, I need to get > > self.subobject1.listsubobject2[0].subobject3 > > where 'self' is the (PyObject *) I have in my C Program > > do i have to parse the string and do the C API getattr calls myself > or is there some easier way to do it? You could evaluate the string. As this is relative to an object, you would first rephrase this as self.subobject1.listsubobject2[-1].subobject3 Then you build a dictionary where 'self' refers to that object (PyDict_New, PyDict_SetItemString), then you evaluate the expression in the context of the dictionary. This, in turn, is done by invoking Py_CompileString and PyEval_EvalCode. Notice that executing arbitrary untrusted code is a security risk. HTH, Martin From rovitotv at rovitotv.org Thu Dec 18 20:32:08 2003 From: rovitotv at rovitotv.org (Todd V. Rovito) Date: Thu, 18 Dec 2003 20:32:08 -0500 Subject: executables In-Reply-To: <20031218091605.GB3296@mrna.tn.nic.in> References: <20031218091605.GB3296@mrna.tn.nic.in> Message-ID: <20031219013208.GA7063@rovitotv@rovitotv.org> Thus spoke km (km at mrna.tn.nic.in): > how do i create a linux executable from a python script. is that possible > ? if so is it a real executable or its just a clever executable packaging > system which makes its size huge as in Perl. kindly enlighten, thanks, AFAIK there are two options. (1) py2exe which I think is a clever executable packaging system which makes its size huge as in Perl. (2) psyco which is like the JIT compiler for java, as I understand it this option requires lots of memory and is just starting to become popular. It is possible other solutions are known by more experienced people since I just started using Python last week. -- Todd V. Rovito rovitotv at rovitotv dot org Carpe Aptenodytes! ================ "Seize the Penguins!" Running GNU/LFS 4.1 Linux 2.4.21 From fumanchu at amor.org Sat Dec 20 13:50:09 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 20 Dec 2003 10:50:09 -0800 Subject: dynamic typing questions Message-ID: I wrote: > > Zuh? Unit testing doesn't replace a good debugger; they > work together. > > Unit testing can only show you THAT a test has failed--it can't show > > you where, how, or why. Think of exception handling (and especially > > tracebacks) as a mini-debugger. Then Dennis Lee Bieber wrote: > Your "units" are too big then... > > To my mind... At the, possibly extreme level, the > unit under test > should be small enough that testing proves you /can not/ cause a > failure in that unit -- any condition that can not be trapped and > corrected while inside that unit should raise/return a documented > exception/error code meant to be handled by the next level > up. With the > bottom "proved", any failures in the next level up in > integration have > to belong within the "unit" of that level and should not require any > changes to the "proven" sub-units. Baloney. Your own quotes betray you: "units", "proved", and the word "extreme". Here's a sample I ran into recently (snippet of a much larger ADO abstraction module): import datetime import win32com.client import pywintypes from win32com.client import gencache gencache.EnsureModule('{EF53050B-882E-4776-B643-EDA472E8E3F2}', 0, 2, 7) def cast_date(self, dbfield): if dbfield.Value is None: return None if dbfield.Type == win32com.client.adDate: return datetime.date.fromordinal(dbfield.Value) else: # It's a string, not a Date. return datefromstring(dbfield.Value) The cast_date "unit" was not producing errors--the entire MVC application would simply stop running; its process would disappear. So please, devise unit tests to isolate this without using a step-through debugger. What, are you going to write a unit test for each line of code? As it happens, the failure occurred upon calling dbfield.Value when it was a date value before the epoch. (IIRC I was originally converting it to a float, before the datetime module came along). The point is, you can't always trap errors. I needed to know exactly which line of code, which call, was crashing the app. So not only did I need a stepping debugger to isolate which statement in cast_date was failing, I had to use a debugger to find out which line of code in the unit test was calling the failing code! Unit tests are wonderful, _IF_ you pre-conceive all the corner cases. This is, of course, impossible in any sufficiently powerful system to be worthwhile. Unit test are the greatest thing since sliced bread. No argument from me. But Mr. Roth's hyperbole regarding the usefulness of debuggers is out of place. IF you only use code you write, and IF you fully understand your problem domain and range, then you MIGHT not need a debugger. The rest of us mortals use them when they're needed. Robert Brewer MIS Amor Ministries fumanchu at amor.org From kmneilso at yahoo.com Mon Dec 15 10:56:52 2003 From: kmneilso at yahoo.com (Kerry Neilson) Date: 15 Dec 2003 07:56:52 -0800 Subject: Idle won't start References: Message-ID: "python newbie" wrote in message news:... > You didn't by any chance create a batch routine that sometimes creates a > file by > the name of "\Lib\idlelib\idle.pyw" did you. > > "Kerry Neilson" wrote in message > news:ecebe16b.0312141050.4a10fbba at posting.google.com... > > For the past couple of months, Idle won't start when I invoke it. I > > am at a complete loss for why this is. When this happens, they python > > command line still starts, and python works fine otherwise. > > Most interesting to me is that a reboot won't fix the problem. But if > > I just try it again sometime later it will work. Anyone have any > > ideas? I'm running python 2.3 on windows 2000 professional. Not that I am aware of, but I do have this file. Is it a problem? From just at xs4all.nl Fri Dec 12 11:50:46 2003 From: just at xs4all.nl (Just) Date: Fri, 12 Dec 2003 17:50:46 +0100 Subject: Compiling a CPython library on Mac OSX References: Message-ID: In article , "Boris Boutillier" wrote: > I'm trying to make a port of a python library written in C to Mac OsX, > is there some documentation to help in the process ? I m having trouble > with the creation of the shared library, and I'm not sure this is the way > it should be done. Does it come with a setup.py file? In that case: just follow the regular instructions. Make sure you have the Apple developer tools installed. Just From mjackson at alumni.caltech.edu Thu Dec 11 07:38:30 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 11 Dec 2003 12:38:30 GMT Subject: Case sensitive and ludicrous statements References: <3fd43984$0$7158$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Mark Jackson wrote: > > Re. CamelCase and SmallTalk: ISTR that the Alto keyboard lacked an > > underscore character (I believe the character code was used for > > left-arrow, which I vaguely recall was used for assignment in BCPL > > and/or Mesa). As constructions like foo_bar are the obvious > > alternative to FooBar, could this lack have been a factor at PARC? > > > > I don't know about the Alto keyboard (I've heard of alto saxophone, but > I guess this is OT ?-) >From the tenor of your remarks I gather you may not be not familiar with http://www.computerhistory.org/exhibits/highlights/alto.page > but on a french keyboard, I have to type ctl + > alt + 8 for the underscore. Camel case notation only implies using the > shift key. GuessWhichOneHasMyPreference ? I feel your pain, once having been faced with programming on an Intel system on whose one terminal "backspace" was a shifted function. Since I don't type entirely without error. . . . (To bring this full circle: my solution was to use the Alto serial interface and hook one up as a second terminal!) -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Logic doesn't apply to the real world. - Marvin Minsky From db3l at fitlinxx.com Thu Dec 11 11:12:07 2003 From: db3l at fitlinxx.com (David Bolen) Date: 11 Dec 2003 11:12:07 -0500 Subject: wxPython - wx package (new style wxPython?) References: Message-ID: James Tanis writes: > Bah, I think they are just over-glorifying the change. In my > mind, it's the same exact thing. The only real different is when you > "from wxPython.wx import *" it reads everything into your local > namespace which is traditionally considered not the best thing to do. > I really have no idea if the "transition" when finished will remain > backwards compatible, but I'm guessing from the description of the > implementation that it is. To be honest, for a while now I've often been doing: from wxPython import wx and putting up with duplicated references to wx (e.g., wx.wxWindow). That avoids both the pollution of the local namespace and the overhead of pulling in the several thousand names (I got a noticeable performance speed up in an application with many plugins since each plugin no longer needed to make extra references for all the wx objects in the plugin's local namespace). One reason why I haven't moved to the new wx package yet is that it's implemented as a lazy evaluation approach (probably for performance), which means it doesn't play nice with interface tools that need introspection (e.g., IDE completion) which some of my other developers use. Once wx becomes a full fledged normal module I'd definitely consider moving to it for the same reasons that I use the above approach now. -- David From susi2000 at web.de Wed Dec 10 05:10:16 2003 From: susi2000 at web.de (Susanne) Date: 10 Dec 2003 02:10:16 -0800 Subject: How to Parse a Script before execution References: <188007e5.0312080805.10cf0056@posting.google.com> Message-ID: <188007e5.0312100210.36470a70@posting.google.com> Hello, i was looking for a solution in the groups, and someone did it with: struct _node * myNode = PyParser_SimpleParseFile(...); PyNode_Compile(myNode); PyEval_EvalCode(...); I am using Python 2.3 and there my Visual Compiler says, that there is no PyNode_Compile(). I also looked i different books, and in the html-help of Python 2.3, but found nothing usable. Perhaps anyone of you has an idea, how to solve my problem. Thanks Susanne From jdhunter at ace.bsd.uchicago.edu Thu Dec 4 13:14:34 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 04 Dec 2003 12:14:34 -0600 Subject: har har Message-ID: # my python wrapping of pokereval -- results are exact from pokereval import seven_cards, compare_two_hands p0 = ('Ac', 'Tc') p1 = ('Ah', '3h') common = ('8c', '6h', '7h') wins, losses, ties, ev = compare_two_hands( p0, p1, common) assert( wins==517 and losses==439 and ties==34) p0 = ('Qd', 'Kd') p1 = ('Ac', '3s') common = ('Kc', 'Jc', '4c') wins, losses, ties, ev = compare_two_hands( p0, p1, common) wins, losses, ties, ev = compare_two_hands( p0, p1, common) assert( wins==537 and losses==453 and ties==0) From tim.one at comcast.net Fri Dec 5 14:41:03 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 5 Dec 2003 14:41:03 -0500 Subject: memory leak - C API In-Reply-To: Message-ID: [John Hunter] > ... > My understanding is that PySequence_GetItem returns a borrowed ref so I > don't need to do any memory management. Where did that understanding come from? It's important to track it down, because whatever source you got it from is unreliable. This one is such a common misconception that the docs (Python C/API Reference Manual, section "Reference Count Details") point it out explicitly: It is important to realize that whether you own a reference returned by a function depends on which function you call only -- the plumage (the type of the object passed as an argument to the function) doesn't enter into it! Thus, if you extract an item from a list using PyList_GetItem(), you don't own the reference -- but if you obtain the same item from the same list using PySequence_GetItem() (which happens to take exactly the same arguments), you do own a reference to the returned object. From corrada at dandenong.cs.umass.edu Tue Dec 9 14:02:03 2003 From: corrada at dandenong.cs.umass.edu (Andres Corrada-Emmanuel) Date: Tue, 9 Dec 2003 14:02:03 -0500 (EST) Subject: Optimize flag on shebang line Message-ID: Hello, Does the optimize flag work on the shebang line of UNIX systems? I've tried to execute a script on a Solaris system with a shebang line of the form: #! /usr/bin/env python -O and it does not recognize the flag but python -O > > > > When opened in IE6 SP1, that does nothing (no error but no message box > / nothing written in the page). > > I ran win32comext\axscript\client\pyscript.py and pyscript_rexec.py to > register python as a scripting engine. No errors from those scripts. > > As I understand it and from what I have read in this forum and > elsewhere, it should work, but it doesn't: what am I doing wrong ? > > Note: I have installed the latest win32all extensions (163) / I'm > working on a W2K Server box (SP3). I doubt if it will work for a while. It doesn't work on my system either, and a quick check of the pyscript_rexec.py module says that it will enable Rexec support. Rexec support was removed from base Python in release 2.2.3 and later, so I doubt if this is ever going to work until ActiveState (or Mark Hammond) changes the base code to use Exec instead of RExec. John Roth From theller at python.net Thu Dec 18 15:16:12 2003 From: theller at python.net (Thomas Heller) Date: Thu, 18 Dec 2003 21:16:12 +0100 Subject: Broken python-model.el References: Message-ID: Skip Montanaro writes: > Brian> I just compiled Python 2.3.2 on my local machine as an upgrade > Brian> from 2.2. This appears to have broken my python-mode.el in > Brian> emacs. When I try to "Execute Buffer" Ctl-c Ctl-c I get: > > Brian> Wrong type argument: sequencep, cpython > > What version of python-mode and Emacs are you using? What is the value of > py-default-interpreter? I just tried C-c C-c in a Python buffer with > version 4.40 and XEmacs 21.5beta9 and it worked fine for me. I also get the above error when the file begins with #!/usr/bin/env on Windows. XEmacs 21.4 (patch 13), python-mode 4.29. Removing this line fixes it. Thomas From peter at engcorp.com Fri Dec 5 14:05:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 14:05:03 -0500 Subject: When is bare except: justified? References: <873cbzmbld.fsf@pobox.com> Message-ID: <3FD0D6DF.2F900D9D@engcorp.com> Dave Brueck wrote: > > > When *is* it justified to use except:, then? > The rule of thumb I use is that a bare except is bad if it hides the fact that > an exception occurred. So, for example, using a bare except in code like this > is okay: > > for worker in workers: > try: > worker.process() > except: > LogException() Ah, the sheer elegant beauty of that viewpoint. Thanks, Dave! It clearly covers all the use cases we have, with a much, much smaller rationalization than I've tried to use. -Peter From donn at drizzle.com Sat Dec 20 01:05:02 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 20 Dec 2003 06:05:02 -0000 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> <38ec68a6.0312181529.729b654@posting.google.com> Message-ID: <1071900300.434091@yasure> Quoth Jp Calderone : | On Thu, Dec 18, 2003 at 03:29:55PM -0800, Asun Friere wrote: ... |> What surprised me was that the facially equivalent: |> >>> def f (d=[]) : |> ... d += [0] |> ... print d |> did not do so. Apparently '+=' in regards to lists acts like |> list.apppend, rather than as the assignment operator it looks like. | | list.extend, to be more precise, or list.__iadd__ to be completely precise | :) The maybe-mutate-maybe-rebind semantics of += lead me to avoid its use | in most circumstances. This tacky feature certainly ought to be considered for the chopping block in version 3, for exactly that reason. Donn Cave, donn at drizzle.com PS. Good analysis, JR, I learned something from it. From dw-google.com at botanicus.net Sun Dec 28 09:59:54 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 28 Dec 2003 06:59:54 -0800 Subject: Using python to check the status of a program References: Message-ID: <99dce321.0312280659.19c3c730@posting.google.com> jetman516 at hotmail.com (The Jetman) wrote... > 1st, which OS are we talking about ? *IF* we're talking about > Linux/Unix/FreeBSD, then it only takes a few lines: > import os > import string > f = os.popen( 'ps -ax' ) > s = f.readlines() > if string.find( s, 'target_pgm' ) > -1: > #### we found it, so do something.... I don't understand why so many people do this, grepping the process list for strings is a terribly unreliable way of testing whether a program is alive, especially when you don't have control of the process list (eg. customer computers). Might I suggest a modification to the procedure in my last post? Give it an argument and pass that argument to ps' "-C" switch. Then test for process existance with something like: if len(get_process_ids('yourbin')) == 0: # check for repeated crashes. # restart the server. There are a multitude of programs for every imaginable OS to do this for you already. Have you looked at them? There's one at http://cr.yp.to/, and many more at http://freshmeat.net/. David. From http Sun Dec 21 00:11:17 2003 From: http (Paul Rubin) Date: 20 Dec 2003 21:11:17 -0800 Subject: UserLinux chooses Python as "interpretive language" of choice References: <279b566d.0312201935.38fb2156@posting.google.com> Message-ID: <7xpteibvre.fsf@ruckus.brouhaha.com> sulfugor at rocketmail.com (H.V) writes: > > reduce() > > nobody uses it, few understand it > > a for loop is clearer & (usually) faster > > > > I think no one even tries to understand the very concept of reducing > sequence to a single object using a rule . Sum is not a replacement of > this *concept*. > Just what is so wrong with having such a general tool available in a > programming language ? Doesn't it hurt to understand how to use it? The new sum function actually seems like a kludge around a misdesign of the operator module. operator.add(2,3,4) should return 9 instead of throwing an error because operator.add can only take two args. Then sum(some_list) can be replaced by operator.add(some_list). The other functions in the operator module should be extended the same way. From steve at ferg.org Sun Dec 21 21:58:49 2003 From: steve at ferg.org (Stephen Ferg) Date: 21 Dec 2003 18:58:49 -0800 Subject: dynamic typing question References: Message-ID: > How have you all overcome the lack of static typing? Is Python a bad decision here? + Python is a good decision. Fears about lack of static typing are largely unwarranted. The following page has a number of useful links to discussions of the merits of static vs. dynamic typing. http://www.ferg.org/projects/python_java_side-by-side.html From duncan at NOSPAMrcp.co.uk Wed Dec 10 09:11:07 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Dec 2003 14:11:07 +0000 (UTC) Subject: About the use of **args References: Message-ID: Jacek Generowicz wrote in news:tyfzne0yeqp.fsf at pcepsft001.cern.ch: >> Except that in Python the convention for private variables is to >> begin them with two underscore characters, and then it is more than >> just a convention: > > Now, I always believed that "private" in Python is spelt "_", while > "mangle this name for me because I want to avoid name clashes in > multiple inheritance scenarios" is spelt "__". > > However, I've heard _so_ many people make the (in my opinion > incorrect) claim that "private" is spelt "__", that I'm beginning to > question my sanity. > > Where is the Python spelling of "private" set in stone ? Section 5.2.1 of the Python reference manual in the paragraph headed 'Private name mangling'. > > I find the suggestion that a mangled name is somehow "more private" > than one with a single leading underscore, mildly insulting to the > clients of your code. The implcation is that they can neither work out > the (very complicated and cryptic[*]) mangling scheme, not use dir(). Not at all, the mangling is clearly documented. Its purpose is most emphatically NOT to prevent access to your clients. > > If a Python programmer wants to acces a private attribute, he can do > so, regardless of the number of leading underscores. Good points. I suppose it all depends on your definition of 'private'. To me, there are two reasons why someone might want to use 'private' variables. One is to prevent accidental nameclashes when someone subclasses one of your classes, the other is because you don't trust those poxy programmers who are going to use your class, so you want to burn their fingers if they try. The first of these, Python provides. Ok, it doesn't get it quite right (the name mangling should maybe include the module and package as well as the class), but it does a reasonable job of minimising accidental nameclashes. Python does not attempt to address the second of these issues, preferring to believe that all Python programmers are mature & responsible. C++ fails dismally on the first count, it doesn't hide the names so adding a 'private member' to a base class can break the derived classes. It also fails on the second count, since you can easily bypass private if you wish. To my mind, data hiding is a good reason for using private variables, but preventing knowledgeable users from bypassing the privacy is dubious at best. You are of course free to disagree. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From martin at v.loewis.de Mon Dec 8 17:10:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Dec 2003 23:10:25 +0100 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: jarrodhroberson at yahoo.com (Y2KYZFR1) writes: > only if you mean Windows 95, 98, ME, 2000, XP as "platform > independant" People enjoy running .NET applications on OS X, through Rotor. Regards, Martin From newsgroups at jhrothjr.com Wed Dec 31 15:59:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 31 Dec 2003 15:59:42 -0500 Subject: PYTHONPATH unnecessary with PythonWin? References: Message-ID: "r.e.s." wrote in message news:gpGIb.14334$lo3.1830 at newsread2.news.pas.earthlink.net... > I have no PYTHONPATH nor any other python-related environment > variables, yet everything seems fine. (I'm using PythonWin > with winxp.) As long as modules are loaded through PythonWin, > is PYTHONPATH unnecessary? Or am I missing something? sys.path is initialized to automatically provide access to the standard parts of the Python installation; it is not necessary to have a PYTHONPATH environment variable for this. You can also stick things in sys.path with a foo.pth file. It's only when you want to get outside of the standard libraries that you need the PYTHONPATH environment variable. Since I'm running Windows, I don't have "a" command line, I have one for each project, and I simply initialize PYTHONPATH in the command line startup for what I need for that project. John Roth From jjl at pobox.com Wed Dec 17 09:01:22 2003 From: jjl at pobox.com (John J. Lee) Date: 17 Dec 2003 14:01:22 +0000 Subject: Is anyone using Python for .NET? References: <6e07b825.0312162307.7e2d9306@posting.google.com> Message-ID: <87r7z3fsr1.fsf@pobox.com> yaipa at yahoo.com (yaipa h.) writes: > > In another year it is possible that Python compiled to IL will be faster > > than CPython in most cases. But it is really hard to say. > > It appears that it already does... > > http://www.python.org/~jeremy/weblog/031209a.html [...] I'm sure he was aware of that -- in fact, I presume that's what triggered his comment. one-benchmark-does-not-a-useful-implementation-make-ly y'rs, John From hst at empolis.co.uk Tue Dec 9 11:17:37 2003 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 9 Dec 2003 16:17:37 -0000 Subject: regex confusion Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB53BF55@hendrix.empolisuk.com> John Hunter wrote > In trying to sdebug why a certain regex wasn't working like I expected > it to, I came across this strange (to me) behavior. The file I am > trying to match definitely contains many instances of the letter 'a', > so I would expect the regex > > rgxPrev = re.compile('.*?a.*?') > > to match it the string contents of the file. But it doesn't. Here is > a complete example > > import re, urllib > rgxPrev = re.compile('.*?a.*?') > > url = > 'http://nitace.bsd.uchicago.edu:8080/files/share/showdown_exam > ple2.html' > s = urllib.urlopen(url).read() > m = rgxPrev.match(s) > print m > print s.find('a') > > m is None (no match) and the s.find('a') reports an 'a' at index 48. > > I read the regex to mean non-greedy match of anything up to an a, > followed by non-greedy match of anything following an a, which this > file should match. > > Or am I insane? > > John Hunter > You need rgxPrev = re.compile('.*?a.*?', re.DOTALL) to get newline characters matched by ".". Your URL content starts with a newline HTH Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From max at theslimmers.net Thu Dec 11 15:16:46 2003 From: max at theslimmers.net (Max Slimmer) Date: Thu, 11 Dec 2003 20:16:46 GMT Subject: What GUI toolkit looks the best? In-Reply-To: <7xad5z1jq5.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: <3FD8D0B5.7040401@theslimmers.net> I have been using wxPython and it performs well ... You should also look at Boa Constructor a GUI designer generates decent Python code, integrated debugger is cool, shows local varraibles... for some uses I find it better than winpython. Paul Rubin wrote: > Brian Kelley writes: > >>Why forget Tkinter? I've seen Tkinter applications that look >>incredibly fabulous. > > > Got any url's for screen shots? > > >>A lot depends on what you are trying to do. If >>you are making a graphics-heavy application then Tkinter's canvas is >>pretty sweet. I also think IDLE looks pretty good. > > > There will be some graphical icons and stuff like that which people > will click on, but no really heavy graphics or drawing tools in the > sense of a photo editor or anything like that. > > >>Glade isn't a GUI, it is a GUI builder that uses GTK. In my >>experience, GTK doesn't look quite right on windows boxes, especially >>the menus. Of course I have the same basic view of Qt and Swing so >>know you know my biases. > > > Oh ok, I understand a bit better now. > > >>I tend to use Tkinter for canvas heavy applications and wxPython for >>other stuff. > > > Is wxPython Windows specific? I guess it is, but can I port the > screen layouts to some comparable Linux toolkit or anything like that? > The screen shots for it do look really nice. > > >>Here is my humble opinions in a nutshell (missing a lot here): >>wxPython has a grid control to die for and many, many classes, good >>printer support and looks like a native GTK app on Linux and a native >>app on windows and macintosh. > > > Oh wow, yes I guess it's cross platform then. Hmm, what Micro$oft > tool do I need to build and run it? Is Visual C++ enough? I guess > I can get the client to pay for some stuff like that. Also, is there > a Glade-like drag and drop gui editor for it? > > >>Qt is better for developing - it has a better class structure and I >>tend not to have to look up docs as often and can look really, >>really nice. > > > The KDE apps that I've seen look good but not really top notch. Maybe > more attention could improve them. They're certainly good enough for > practical use. > > >>Tkinter has a killer canvas and great postscript output. GTK is >>really quite fast. > > > I think I don't care about heavy duty graphics or more than rudimentary > printing. > > >>but don't take my word for this, why don't you see what you like the best? >> >>http://www.wxpython.org/ >>http://www.gtk.org/ >>http://www.scriptics.com/ >>http://www.trolltech.com/ > > > I don't know what I can really tell from these without more experience > with them. In particular, which is the most solid and reliable across > a wide range of Windows versions (95, 98, ..., XP whatever)? That > matters too. > > Thanks! > > Paul From imbosol at aerojockey.invalid Thu Dec 18 06:26:49 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 18 Dec 2003 11:26:49 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: Terry Reedy wrote: > > > > "Stian S?iland" wrote in > message > news:slrnbtvte6.tnk.stain at ozelot.stud.ntnu.no... >> When is this issue going to be resolved? Enough > newbie-pythoners have >> made this mistake now. > > I am puzzled as to why. When I learned Python, I > read something to the effect that default value > expressions are evaluated at definition time. I > understood that the resulting objects were saved > for later use (parameter binding) when needed (as > default for value not given). I believed this and > that was that. I am puzzled as to why you're puzzled. Not everyone who reads the manual pays attention to the time of evaluation explanation, if the manual they're using even covers. Not everyone stops and says, "Oh my God, I don't know whether this is evaluated when the function is defined or called. I better find out." (And of course, not everyone reads the manual.) It seems that most people who haven't thought about time of evaluation tend to expect it to be evaluated when the function is called; I know I would expect this. (I think I even made the mistake.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From aaron at reportlab.com Tue Dec 23 11:29:39 2003 From: aaron at reportlab.com (Aaron Watters) Date: 23 Dec 2003 08:29:39 -0800 Subject: twisted request Message-ID: <9a6d7d9d.0312230829.29b014fa@posting.google.com> I have a "chat" protocol module called "Hollerith" which is appropriate for use with threads or stackless, but is not ready for "event loop" style programming. Can someone show me how to implement it (and use it) using Twisted? http://cvs.sourceforge.net/viewcvs.py/*checkout*/xsdb/xsdb/xsdb/Hollerith.py?content-type=text%2Fplain&rev=1.1 Of course the twisted version should never block, please. Thanks in advance, -- Aaron Watters === It does feel like the torch is passing to the next generation. http://www.usatoday.com/life/lifestyle/2003-12-23-holiday-healing-main_x.htm From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri Dec 26 02:52:01 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 26 Dec 2003 08:52:01 +0100 Subject: Socket Programming References: <3FEAC35F.C26A14B1@alcyone.com> <68adnfGlDo2bkHai4p2dnA@speakeasy.net> Message-ID: Good. From buzzard at urubu.freeserve.co.uk Mon Dec 29 11:02:50 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 29 Dec 2003 16:02:50 -0000 Subject: callable classes References: <_bydnV23friKY3CiRVn-gQ@comcast.com> Message-ID: "Terry Reedy" wrote in message news:_bydnV23friKY3CiRVn-gQ at comcast.com... > > "Duncan Smith" wrote in message > news:bskkig$sf6$1 at news7.svr.pol.co.uk... > > > What do you mean by 'callable class'? Classes are callables. Ot you > mean > > > a class that defines __call__ method? In this case it's really > useful. > > > > > > regards, > > > anton. > > > > Yes, I meant a class that defines a __call__ method. Cheers. > > Which makes the *instances* callable, so you meant 'class with callable > instances'. > > TJR > Yes. From what I can gather from reverse engineering other's code is that the approach I am investigating is to create a single (global) callable instance when the module is imported. Something like, pointwise_operation = pointwise_operation() Then in the class where I originally had the pointwise methods I need something like, e.g., def __mul__(self, other): return pointwise_operation.multiply(self, other) I'm just not clear what the advantages / disadvantages are over just leaving all the pointwise operation methods in the original class. BTW it first occurred to me to do this after reading Numeric's MA.py. Duncan From andymac at bullseye.apana.org.au Mon Dec 8 06:19:56 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 8 Dec 2003 22:19:56 +1100 (EST) Subject: Help: Uploading .zip to Python CGI In-Reply-To: References: Message-ID: <20031208221530.K83001@bullseye.apana.org.au> On Sun, 6 Dec 2003, Will Stuyvesant wrote: > The last part of the data that is received by the CGI script is: > > \xf2\xf1!0\xdbS\xa9 > > and the next one *should* be \x1a ISTR that \x1A is control-Z. Which is the EOF character on CP/M derived systems, and is still interpreted thusly in the most surprising places in software from Redmond. As another poster suggested, the -u option is the usual solution. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From mcherm at mcherm.com Wed Dec 17 08:56:37 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 17 Dec 2003 05:56:37 -0800 Subject: [Python-Dev] Re: rexec.py unuseable Message-ID: <1071669397.3fe06095c9f3c@mcherm.com> Luke: Seeing as you've now had time enough to read what I'd written, I was going to respond to some of the points that you made, but then I read Nick Coghlan's posting[1], and I really don't have anything else to add. [1] http://mail.python.org/pipermail/python-dev/2003-December/041105.html Well, that's not quite true... I guess I _do_ have something small to add. In designing a security policy for file systems, there are very few things that you can do with the protected items. Separate "read", "write", and "execute" permissions seem appropriate. Furthermore, there tends to be a clear idea of a "user", and in many situations we want all access to items (files) to depend only on who that "user" is (sandboxing an email program is an exception... are you listening MS?). Finally, we often want to provide centralized administration of access rights to file systems. ACLs are a good match for these design specs. However, controlling what arbitrary programs may do is a very different beast. First of all, the kinds of restrictions that we want are HIGHLY variable. Sometimes we want to prohibit all file access. Sometimes we want to allow read-only access to a certain file only. Sometimes we want access only to a certain directory. Sometimes we don't care at all about file system access, we're concerned instead with providing an object which can be queried but only in certain ways -- and the specifics of what is permitted and what isn't are completely dependent on the particular application. On top of that, there's rarely a clear concept of "users" that controls what actions we want to permit. Instead, we usually want to allow or deny certain capabilities to particular _sections of code_. (Sometimes that will be a module, sometimes a plug-in, sometimes a child program.) All of these things suggest that maintaining a list of who is permitted to access what is simply not the best model for providing security in a programming language. I think that capabilities ARE an excellent model. Sections of code already have the concept of "access" to certain objects and variables (at least since the invention of structured programming in the late 1960s). And _if_ unforgability and private data structures are provided as elemental building tools, then it is relatively straightforward to write code that enforces whatever set of access rules is required, regardless of how complex it may be. -- Michael Chermside From PPNTWIMBXFFC at spammotel.com Mon Dec 29 05:47:35 2003 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: 29 Dec 2003 02:47:35 -0800 Subject: xmlrpc / SimpleXMLRPCServer and multi-threading Message-ID: <15c2d03b.0312290247.6a0bc41d@posting.google.com> I would like to develop a server based on python's xmlrpc. But I realized that SimpleXMLRPCServer does not spawn a thread for each request. How could the SimpleXMLRPCServer be turned into a multi-threaded Server? Is there a reason why the SimpleXMLRPCServer is not multi-threaded? Is there a plan to make it multi-threaded? Thanks for any hints in advance, Cheers, Marco From edreamleo at charter.net Fri Dec 12 05:38:55 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 12 Dec 2003 04:38:55 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: > > > It's not clear that wxWindows really actually works. > > Isn't that last sentence a bit overly FUD-ish? > Umm. Maybe you are right. After sleeping on this question, I think not :-) True, my choice of words wasn't the best, but since you brought up FUD, I'm willing to discuss my fears, uncertainties and doubts about wxWindows. Motivation & experience The typical FUD campaign is driven by ulterior motives. I have no such motives--I am not the author of a product that competes with wxPython or Tkinter: I am a somewhat frustrated user of both products. Leo is about to come a rare beast: a gui-agnostic application. That is, Leo will soon be able to support other gui toolkits besides tkinter. Indeed, an experimental wxPython plugin already exists. This plugin replaces Leo's default tkinter gui with a wxPython gui. My remarks are based on experiences with a failed wxWindows project and the present wxPython plugin. Psychological responses In my case, I do have doubts that I can make wxPython projects as solid as the equivalent Tkinter projects. Related feelings include fear and uncertainty, and some others ;-) These feelings are real, and they are based on substantial experience. Objective responses In my experience, it is a _fact_ that wxPython (really wxWindows) seems to have many more bugs than Tkinter. It is a _rare_ bug that has no workaround, so this fact does _not_ mean that it is impossible to produce "working" apps with wxWindows/wxPython. What is probably _does_ mean is that it will be more expensive to create a solid wxPython app than one would hope. In my experience, the answer to the question "Why the hell hasn't wxPython become the standard GUI for Python yet?" is: "wxWindows is buggy." Conclusions All my comments have been intended to alert people to the complexities and difficulties in choosing one gui or another. I wish that Tkinter and wxPython were better, and I think people should have their eyes open when considering using these tools. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From lbray_103 at yahoo.com Wed Dec 24 07:24:55 2003 From: lbray_103 at yahoo.com (MComp) Date: 24 Dec 2003 04:24:55 -0800 Subject: Remembering References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> <87llp3i99m.fsf@pobox.com> Message-ID: <37c4fd7c.0312240424.1b651616@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87llp3i99m.fsf at pobox.com>... > lbray_103 at yahoo.com (MComp) writes: > > > Hey guys, I'm another new to programming guy. I have one quick > > question. How do you make a program not forget everything you input, > > once it shuts down? Thanks in advance. > Thank you guys for all of your help. It really does help me out a lot. Thx again. Monroe From gerrit at nl.linux.org Mon Dec 1 10:26:38 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 1 Dec 2003 16:26:38 +0100 Subject: Turning off warnings In-Reply-To: References: Message-ID: <20031201152638.GA4181@nl.linux.org> Paulo Pinto wrote: > I need to generate a temporary name for a > file and pass it as argument to a shell > script. > > Now when I use os.tempnam() or os.tmpnam() > I get a runtime warning about security issues. > > I am well aware of them, but in the context of > this application I really don't need to care > about it. > > Is there any way to turn the message off? You can either do so from the commandline, or use the warning module. You probably want to use the latter. The documentation for the warnings module can be found at: http://www.python.org/dev/doc/devel/lib/module-warnings.html You probably want to do: warnings.filterwarnings("ignore") Hope this helps! Gerrit. -- 12. If the witnesses be not at hand, then shall the judge set a limit, at the expiration of six months. If his witnesses have not appeared within the six months, he is an evil-doer, and shall bear the fine of the pending case. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From Pieter.Claerhout at Creo.com Thu Dec 18 04:10:47 2003 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 18 Dec 2003 10:10:47 +0100 Subject: executables Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D1D@cseexch01.cse.creoscitex.com> There are several options: - McMillan's installer: http://www.mcmillan-inc.com/install1.html - cx_Freeze: http://starship.python.net/crew/atuining/cx_Freeze/index.html You can find a lot more info on: http://wiki.wxpython.org/index.cgi/CreatingStandaloneExecutables Cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: km [mailto:km at mrna.tn.nic.in] Sent: 18 December 2003 10:16 To: python-list at python.org Subject: executables Hi all, how do i create a linux executable from a python script. is that possible ? if so is it a real executable or its just a clever executable packaging system which makes its size huge as in Perl. kindly enlighten, thanks, -- http://mail.python.org/mailman/listinfo/python-list From tismer at tismer.com Thu Dec 11 22:39:34 2003 From: tismer at tismer.com (Christian Tismer) Date: Fri, 12 Dec 2003 04:39:34 +0100 Subject: Stackless 3.0 can pickle generators, now Message-ID: <3FD93876.9010105@tismer.com> What else should I say? You can pickle generators. Try it by yourself. CVSROOT=:pserver:anonymous at centera.de/home/cvs cvs co stackless -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From tjreedy at udel.edu Mon Dec 1 16:33:35 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 1 Dec 2003 16:33:35 -0500 Subject: passing global data to a function References: <3064b51d.0312010855.66f4e2@posting.google.com> Message-ID: wrote in message news:3064b51d.0312010855.66f4e2 at posting.google.com... > How can I pass global data to function stored in a separate file? Since 'global data' (and more generally 'context data') is data that is *not* passed to a function (but is instead read from the function's context), your question is a contradiction;-). What you have run into is the difference between lexical context (where the function is defined) and dynamic context (where the function is called). Dynamic scoping, which you were expecting or at least hoping for has been tried in some languages (some dialects of Lisp, at least) but I believe that experience has shown lexical scoping is overall preferable. As others have said, your immediate solution is to push the 'global' value into the functions lexical context with 'funk.ipow = 3'. Terry J. Reedy From marcos at nordesia.org Mon Dec 22 13:49:26 2003 From: marcos at nordesia.org (Marcos Eimil Pardo) Date: Mon, 22 Dec 2003 19:49:26 +0100 Subject: Remembering In-Reply-To: <3FE73B49.4010401@nordesia.org> References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> <3FE73B49.4010401@nordesia.org> Message-ID: <3FE73CB6.7070508@nordesia.org> Marcos Eimil Pardo escribi?: > MComp escribi?: > >> Hey guys, I'm another new to programming guy. I have one quick >> question. How do you make a program not forget everything you input, >> once it shuts down? Thanks in advance. > > > you can save read data to a file: > > data=raw_input("type some data> ") > # open a file to write text > f=file("savedata","wt") > # save data to file > f.write(data) > # close file > f.close() > > and when you reload your program you can read data from file: > > # open a file to read text > f=file("savedata","rt") > # save data to file > data=f.read() > # close file > f.close() > > > well this is a very simplistic solution, if you want to save multiple > data, you must save it following some convention, for example if you > have read name and age, you can save it in a text file, with two lines, > the first with name and the second with age, and when you restart your > program you should read from file in the same order: > > #to write multiple data item on multiple lines > name=raw_input("name> ") > age=raw_input("age> ") > # open a file to write text > f=file("savedata","wt") > # save name to file > f.write(name) > # write newline character > f.write("\n") > # save age to file > f.write(age) > # close file > f.close() > > > #to read multiple data item on multiple lines > # open a file to read text > f=file("savedata","rt") > # read name from file (name is in first line) > # attention: we use readline to read one line, read() gets entire > # file (read manual for more information) > name = f.readline() > # read age from file (age is in second line) > age = f.readline() > # age and name are strings terminated with a new-line character, > # we may want to strip this last char, we can do it this way: > age = age[:-1] #oops too fast answer you can do better this way: (eliminating #trailing whitespace characters, if present) age=age.rstrip() > name = name[:-1] age=age.rstrip() > # close file > f.close() > > hope, gives some help. > greets, marcos. > > > From emile at fenx.com Tue Dec 2 08:33:12 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 2 Dec 2003 05:33:12 -0800 Subject: Equivalence of dictionary keys? References: <3FCC058C.6070205@irl.cri.nz> Message-ID: Duncan Booth: > Blair Hall: > > I am guessing that two dictionaries with the same keys > > will sort them in the same order but is this true? > > Here's a simple counter-example using not two but one dictionary. Just > manipulating a dictionary can change the order of the keys: > Borrowing your jumble keys example, you can also use sets d = {'a':1, 'b': 2, 'c': 3} c = {'a':1, 'b': 2, 'c': 3} for i in range(100): d[i] = i for i in range(100): del d[i] a = d.keys() b = c.keys() import sets print sets.Set(a) == sets.Set(b) -- Emile van Sebille emile at fenx.com From gagenellina at softlab.com.ar Fri Dec 19 02:07:27 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 19 Dec 2003 04:07:27 -0300 Subject: Default attribute in base class precludes delegation In-Reply-To: References: Message-ID: <5.2.1.1.0.20031219033555.01f3dec0@192.168.0.115> At 19/12/2003 05:41, you wrote: > >- a Derived class which must inherit from Base and is a wrapper around > >Worker: it contains a Worker instance and delegates almost anything to it. > >This class can be modified as needed too. >In what sense a "wrapper"? In fact it's an Adapter: it contains a reference to the Worker -and delegates most method calls to it- also providing the interfase expected from Base. > >For most attributes, as they are not found in the Derived instance's dict, > >__getattr__ is called and the attribute is retrieved from the Worker > instance. >Why do you (think you) need an explicit __getattr__ ? Usually there's >better ways. How? >class Derived(Worker, Base): > """dummy until something to do""" > >Or do you actually need to have different unknown types of workers so you >can't inherit? Oh, thanks but that won't work. There are many types of Workers, chosen at run time, that's why I can't simply inherit and have to use delegation. Gabriel Genellina Softlab SRL From skip at pobox.com Wed Dec 17 16:37:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Dec 2003 15:37:50 -0600 Subject: tuples and cartesian coordinates In-Reply-To: <20031217211930.GA6331@nl.linux.org> References: <20031217201815.GA5831@nl.linux.org> <16352.48717.970544.828159@montanaro.dyndns.org> <20031217211930.GA6331@nl.linux.org> Message-ID: <16352.52398.457844.219111@montanaro.dyndns.org> >> See the recent (long) thread on this subject: >> http://tinyurl.com/zoyt Gerrit> Hmm, the only message I see on the question whether tuples are Gerrit> useful for *coordinates* is: Well, the thread was more general (tuples vs. lists), but if you think of coordinates as immutable objects, then using tuples makes more sense (at least to me). If I have two objects, and one moves to be at the same location as the other, this seems natural: o2.location = o1.location I'd hate to see o2 suddenly move when o1 moves five clicks north: o1.location[1] += 5 If you use tuples, o2 stays put when o1 moves: o1.location = (o1.location[0], o1.location[1]+5) (That just demonstrates that I'd assign a new coordinate tuple to o1.location. I would probably hide the tuple surgery in a move_relative() method.) Skip From km at mrna.tn.nic.in Wed Dec 24 07:51:28 2003 From: km at mrna.tn.nic.in (km) Date: Wed, 24 Dec 2003 18:21:28 +0530 Subject: graphs Message-ID: <20031224125128.GA21418@mrna.tn.nic.in> Hi all, Is there any inbuilt python module which can draw 2-D or 3-D plot to a file (png/jpeg etc) or one which interfaces gnuplot on linux ? kindly enlighten, regards, KM From francisgavila at yahoo.com Mon Dec 15 18:29:57 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 15 Dec 2003 18:29:57 -0500 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: Matthew Sims wrote in message <1e963607.0312151408.583221e6 at posting.google.com>... >Python Newbie here. This is my first time learning object-oriented >programming and trying to break out of the usual Korn/Perl/PHP style >of programming. Having some difficulty understand some items. > >For lists, I understand this: >C=["need","some","help"] >print C[1] >some > >But I can't seem to do this: >C[3]="here" > >I know about C.append("here") but this brings me to my question... > >Is there anyway to assign to an element that wasn't defined in the >beginning? Like if I wanted element 5 assigned but not element 4 >without using "" or None? I assume you tried 'insert'? >>> C=["need","some","help"] >>> C.insert(10, 'here') >>> C ['need', 'some', 'help', 'here'] Ah, well that didn't work. Python has no (builtin) way to do what you want. The reason isn't technical, but that the list needs *something* in that intervening space, and Python isn't about to make rash presumptions about what you want there ("explicit is better than implicit"). In choosing between two behaviors for inserting to an index beyond the end of a list, appending was deemed less surprising, less violent, and less likely to introduce mysterious bugs than filling in the intermediate elements with who-knows-what. I can't even think of why one would want lists to have that sort of behavior. It seems to me that if we're assigning to arbitrary elements and we want the list to grow with it, that we should be using a different data structure, like a dictionary with integer keys. The index of a list generally has no semantic correlation to the data contained therein--it just specifies order, and the data doesn't care about its own index. If we want a semantic correlation, we make that correlation explicit by a dictionary's key-value pair. If you want to do this sort of thing (implicit assignment to intermediate elements in list insertions), write a function to do it, or subclass list. You can even modify the slice behavior itself (if you go the subclass route), so that C[3] will silently act like perl instead of Python, but this is *quite* unPythonic. (Other Python people reading your code will be confused.) If this sort of answer surprises you (coming from perl, it might...), do an "import this" at an interactive prompt and read. :) >I'm currently re-writing a Perl script into Python and with Perl I was >free to assign any element in the array without having to fill in the >previous elements. I can't seem to do that in Python...unless I'm >doing it wrong. Again, in general, Python has *no* implicit assignments/declarations/modifications/etc. If you don't *explicitly* ask a list to fill in its intermediate elements, Python won't do it. This is a conscious design decision, and a great part of what makes Python Python. For at least two senses of "great", IMO. I could never learn perl (despite many attempts), so I ask, what does perl do to the intermediate elements? Is a perl array more like a dictionary with implicit integer keys (so intermediate keys simply don't exist), or does it fill in the intermediate elements with 0 or something like that? In what perl idioms is this behavior useful? (I still mean to learn perl one of these days, for shell scripting.) -- Francis Avila From ma_mobius at hotmail.com Sat Dec 20 05:34:20 2003 From: ma_mobius at hotmail.com (Max DRUDI) Date: 20 Dec 2003 02:34:20 -0800 Subject: py2exe application crash Message-ID: <36fe33a9.0312200234.45e8a976@posting.google.com> I have build a simple exe using py2exe. I use it on 5 pc ( 1 Win2000 + 4 Win98). Why this exe go in crash immediately on 3 pc's (all Win98) ? ...at the moment the only Win98 where exe don't crash is pc where i develop the application...an the application must only view a window... From hokiegal99 at hotmail.com Tue Dec 16 18:06:16 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 16 Dec 2003 18:06:16 -0500 Subject: Stop popup cmd window In-Reply-To: References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> <93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: Thomas Heller wrote: > Name the script 'myscript.pyw' instead of 'myscript.py'. > > Thomas Thanks for the tip... that did it. I need to read up on the difference between python.exe and pythonw.exe. Thanks again!!! From timr at probo.com Fri Dec 12 00:57:22 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 11 Dec 2003 21:57:22 -0800 Subject: Reading and writing Mozilla-mail in python References: Message-ID: Uwe Grauer wrote: >After playing around with the mailbox an email modules i noticed some >strange behaviours: > >after the first message is parsed, i got some (kind of parsing errors). > >My code: > >def test_copy(infile, outfile): > from mailbox import UnixMailbox > from email import message_from_file as mff > try: > fd = open(infile, 'r') Ralf is correct. The UnixMailbox method uses tell and seek to remember file locations and return to them later. Tell and seek on Windows are only valid with binary files; the \r\n to \n translation screws it up. Change that to fd = open(infile, 'rb') and all will be well. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Tue Dec 9 02:43:40 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 08:43:40 +0100 Subject: running non-python progs from python References: Message-ID: "Spiffy" wrote: > The 'Learning Python' book talks about using the os.system call, but I > haven't been able to get this to work. "it doesn't work" is a really lousy way to describe a problem what did you do, what happened, and what did you expect would happen instead? also see: http://www.catb.org/~esr/faqs/smart-questions.html#intro > How can I run this other program from a python script and pass the filename > as a parameter? import os filename = "myfile" os.system("program %s" % filename) From aahz at pythoncraft.com Sun Dec 28 13:10:19 2003 From: aahz at pythoncraft.com (Aahz) Date: 28 Dec 2003 13:10:19 -0500 Subject: Threds and Control Window References: <104c369a.0312280731.7ad07a18@posting.google.com> Message-ID: In article <104c369a.0312280731.7ad07a18 at posting.google.com>, Askari <9974331 at cvm.qc.ca> wrote: > >Brienfly, how I can control a window (toplevel) with a thread other >that the main thread? You can't. Send a message to the main thread using Queue.Queue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bowwnz at telstra.com Tue Dec 23 21:25:06 2003 From: bowwnz at telstra.com (Simon B) Date: Wed, 24 Dec 2003 02:25:06 GMT Subject: Is anyone using Python for .NET? In-Reply-To: References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: <6O6Gb.63514$aT.33021@news-server.bigpond.net.au> Brandon J. Van Every wrote: >>My opinion on why MS did take the .NET path is based on the premise that >>they are only really interested in Operating Systems, which isn't too >>bigger a stretch. They want to sell operating systems, and part of the >>reason corporations don't upgrade to the lastest version until they >>absolutely have to (and even then, they often don't!) is because they >>have invested big money in software that will require considerable >>testing and/or modification and/or risk if the underlying OS changes. >> >>.NET solves that problem for Microsoft. > > > Does it? What if in so doing, only .NET has value, and OSes have no value! > W2K with .NET, XP with .NET, makes no difference. Stuff still runs. But > they do get to sell Visual Studio, and they can patent screw Linux. > There be the risk... And it is a big gamble unless, as you point out, they somehow screw the non-MS implementation users of .NET with patent calls. Also, they may feel that .NET + MS infrastructure (COM+, MSSQL, MSMQ) might create enough of a platform tie-in to protect them from the vast majority of migration paths to other OSes. They might even trully believe their own TCO marketing... :) .NET has seems to me like the most dangerous thing MS has ever done... but considering Emulation of the Win32API was just a matter of time (Wine, etc.) perhaps the laywers really do have everything in hand with .NET? From theller at python.net Tue Dec 2 13:26:15 2003 From: theller at python.net (Thomas Heller) Date: Tue, 02 Dec 2003 19:26:15 +0100 Subject: Can Python be run off of a CD-ROM? References: <3FCC8C92.406@ghaering.de> <3FCC9F83.7050405@ghaering.de> Message-ID: <8ylv6pq0.fsf@python.net> "Fredrik Lundh" writes: > Gerhard H?ring wrote: > >> >>Grab a Python directory, copy the python{major}{minor}.dll from >> >>%SYSTEMROOT%\system32 into this Python directory. >> > >> > is the part after the comma really necessary? >> > >> > (all installers I've ever used or created install the core DLL in the >> > Python directory as well. are there installers out there that don't >> > do that?) >> >> The Pythonlabs (or should it be called python-dev installer by now?) >> installer doesn't do this. At least not in the Windows 2000 and XP >> installations I use. > > depends on the version, I suppose. the python.org installer I used on > this machine sure left a python23.dll in the c:/python23 directory. > > tim? thomas? As Tim said, this hasn't changed yet - for admin installs it goes into the system directory. For 2.3 releases it will stay this way, for future releases I don't know. win32all is growing in a direction where it makes fewer use of the registry than in the past, and the sandbox py2exe is already able to create frozen com servers which work fine with python23.dll in the executable directory, so I assume somewhere in the future Python releases don't need dlls in the system directory anymore. Thomas From rasjidw at openminddev.net Wed Dec 3 07:39:28 2003 From: rasjidw at openminddev.net (Rasjid Wilcox) Date: Wed, 03 Dec 2003 23:39:28 +1100 Subject: Python, xml, databases, ... References: <3fcdbd79@mail.netspeed.com.au> Message-ID: <3fcdd93f@mail.netspeed.com.au> Zunbeltz Izaola wrote: > Up, I concept missundertand of mine. I want to know if > MySQL/PostgreSQL are only used in large web servers and such things, > or are also used in small programs that both the server and client > runs localy. I've definitely seen MySQL used where both server and client run locally, and I'm sure there is plenty of the same with PostgreSQL. >> What platform are you planning to run this on? If it is Linux, then >> either MySQL or PostgreSQL are easy options - most distros have >> pre-compiled versions out of the box. > > I want to have the program in both linux and windows. > >> On Windows, both MySQL and PostgreSQL rely on the Cygwin dll. It looks >> like MySQL has an easier Windows install, but their use of the cygwin dll >> outside of Cygwin proper has serious stability consequences if the user >> installs another cygwin based program. PostgreSQL is a 'proper' cygwin >> program, but will be harder for non-unix/linux people to >> install/administer. >> >> You could also consider Firebird (http://firebird.sourceforge.net/) it >> has a native Windows version as well as a Unix/Linux version) or SQLite >> (http://www.hwaci.com/sw/sqlite/) with PySQLite >> (http://pysqlite.sourceforge.net/manual.html). >> >> There is also GadflyB5 (http://gadfly.sourceforge.net/) which looks like >> it >> is written in pure python. There are probably other options too. >> > > Can you give me an advaice about what has a better easy to > use/performance ratio. Unfortunately, no, since I'm at about the same stage you are (ie, trying to work out what to use). I have _personally_ rulled out MySQL on Windows (due to it packaging the cygwin dll in a non-standard way, since I use Cygwin at work), and will only consider PostgreSQL on Windows if I can make the install trivial for a non-technical user. SQLite does not support Foreign Key constraints, so I think it is out for me. Gadfly is not multi-user, so it is also out for me also. Firebird is the only full featured open-source database that I know of that has native binaries (non-cygwin) for Windows, and also runs on Linux and Mac (although a native Windows port of PostgreSQL is in progress). Another option that I have is to on Windows use the MDAC component and use a MS Access backend database, and use MySQL or PostgreSQL on Linux/Mac. See http://www.markcarter.me.uk/computing/python/ado.html for some info on how to access a MS Access database from Python on Windows. Without knowing what SQL feature set _you_ are after, it is impossible to know what is the best option for you. >> > I would build a GUI for the program (presumibly with wxPython). I want >> > to separate the GUI layer from the program layer. For comunication of >> > this two layer I have think in asyncore, but i have read something >> > about twisted and piro. Can anyone give my his/her opinion about this? >> >> Funny, I asked almost the same question about 20 minutes before you did. > > I have no see the question yet :-) My question was entitled 'Building a GUI agnostic database application'. Cheers, Rasjid. From crawley.storm at IGetTooMuchSpamAsItIs.com Sun Dec 28 09:27:41 2003 From: crawley.storm at IGetTooMuchSpamAsItIs.com (Crawley) Date: Sun, 28 Dec 2003 14:27:41 +0000 Subject: Help, multidimensional list Message-ID: Im trying to create a list of lists and for some reason its not working: class Tile: _next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, 'sw':None, 'w':None, 'nw':None } def blankGridCanvas( maxx, maxy ): grid = [] for y in xrange( 0, maxy ): yline = [] for x in xrange( 0, maxx ): t = Tile() if y != 0: t._next[ 'n' ] = grid[ y - 1 ][ x ] t._next[ 'n' ]._next[ 's' ] = t yline.append( t ) grid.append( yline ) for y in xrange( 0, maxy ): for x in xrange( 0, maxx ): print grid[ x ][ y ], grid[ x ][ y ]._next return grid now by my reconing this should be a list of lists with each element being an instance of Tile, and some references being manipulated to point to each other. But strangly no, its actually a list of lists where each element is the SAME instance of Tile, so I change one, i change them ALL! Whats going on and how do I solve it? Rich From blibjunk at hotmail.com Tue Dec 2 03:14:20 2003 From: blibjunk at hotmail.com (Krister Liljedahl) Date: 2 Dec 2003 00:14:20 -0800 Subject: FD_SETSIZE not working in 2.3.2? References: Message-ID: >Does anyone else experience problem with large numbers (>63) of >sockets under Windows? Can anyone else succesfully open 64 or more >sockets under Windows and poll them using select? Sorry for the confusion. The questions above should have ended with the words "in a single thread". I'm only concerned with not being able to open more than 64 sockets per thread. /Krister From JoeyTaj at netzero.com Sun Dec 7 18:52:43 2003 From: JoeyTaj at netzero.com (Paradox) Date: 7 Dec 2003 15:52:43 -0800 Subject: PyDoc modifying the source. Message-ID: <924a9f9c.0312071552.6ae2302d@posting.google.com> I would really like to document our private (ie underscored) methods with PyDoc but it does not seem to support this. I would appreciate it if anyone knew a good way to modify it to accomplish this. Thanks Joey From jack at thelobsterofmetal.com Mon Dec 1 09:34:37 2003 From: jack at thelobsterofmetal.com (Jack Liddle) Date: 1 Dec 2003 06:34:37 -0800 Subject: PyNum, A multidimensional array where the elements are arrays? Message-ID: <9832606.0312010634.170e50d3@posting.google.com> Hi there I'm using Numerical Python to handle my arrays but I'm not sure how to accomplish the following. I want a NxNxNxN array where each element of the the array (A[i,j,k,l]) is itself a 3x3 array. So I can then slice my array A[:,:,i,j] into planes and start grabbing matrices from it. I need to slice it in all possible planes and I don't want to start messing around with nested lists. How would I go about doing this in python, I guess in C I would have a an NxNxNxN array full of pointers to matrix objects, but lifes to short for C. Thanks for any help you can give Jack Liddle Department Of Theoretical Physics University Of Oxford From buzzard at urubu.freeserve.co.uk Mon Dec 1 10:24:25 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 1 Dec 2003 15:24:25 -0000 Subject: PyNum, A multidimensional array where the elements are arrays? References: <9832606.0312010634.170e50d3@posting.google.com> Message-ID: "Jack Liddle" wrote in message news:9832606.0312010634.170e50d3 at posting.google.com... > Hi there > > I'm using Numerical Python to handle my arrays but I'm not sure how to > accomplish the following. > > I want a NxNxNxN array where each element of the the array > (A[i,j,k,l]) is itself a 3x3 array. So I can then slice my array > A[:,:,i,j] into planes and start grabbing matrices from it. I need to > slice it in all possible planes and I don't want to start messing > around with nested lists. > > How would I go about doing this in python, I guess in C I would have a > an NxNxNxN array full of pointers to matrix objects, but lifes to > short for C. > Will an NxNxNxNx3x3 array not do the job? Alternatively you can have an NxNxNxN array of type PyObject (less efficient I would think). Duncan From jjl at pobox.com Sat Dec 27 17:09:54 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Dec 2003 22:09:54 +0000 Subject: Project dream References: Message-ID: <87d6a96hfx.fsf@pobox.com> "David LeBlanc" writes: > > > > Will Stuyvesant: > > >Suppose you have the time and the money to start a new project in > > >Python. What would you like to do? > > > > I was thinking of an open source personal information management > > application, to store notes, knowledge, hyperlinks, snippets, documents > > and such in one flexible integrated information structure. All the things > > that now end up in unrelated documents in different folder hierarchies. > > > > Something with the flexibility and visualisation of the Brain > > (www.thebrain.com), the structuring capabilities of InfoHandler > > (www.mdesoft.com/english.htm) and a Googleish search engine. > > > > -- > > Ren? Pijlman > > -- > > Ren?; > > How interested are you in such a project? > > Please feel free to contact me off list! Related links: http://www.nutch.org/ http://www.google.com/search?q=lucene+python&btnG=Google+Search http://www.gnome.org/~seth/storage/ http://www.nat.org/dashboard/ http://haystack.lcs.mit.edu/ http://pythonfs.sourceforge.net/ http://freshmeat.net/projects/tengis/?topic_id=91 John From fumanchu at amor.org Fri Dec 5 00:24:57 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 4 Dec 2003 21:24:57 -0800 Subject: Lists and Tuples Message-ID: Jeff Wagner wrote: > I've spent most of the day playing around with lists and > tuples to get a really good grasp on what > you can do with them. I am still left with a question and > that is, when should you choose a list or > a tuple? I understand that a tuple is immutable and a list is > mutable but there has to be more to it > than just that. Everything I tried with a list worked the > same with a tuple. Everything? ;) >>> a = [1, 2, 3, 4] >>> a.append(5) >>> a [1, 2, 3, 4, 5] >>> del a[2] >>> a [1, 2, 4, 5] >>> b = (1, 2, 3, 4) >>> b.append(5) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> del b[2] Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item deletion I think you've missed how important the difference between "mutable" and "immutable" can be... Robert Brewer MIS Amor Ministries fumanchu at amor.org From dman at dman13.dyndns.org Thu Dec 18 16:53:18 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Thu, 18 Dec 2003 21:53:18 GMT Subject: [reportlab] print directly to printer References: Message-ID: On Thu, 18 Dec 2003 19:27:10 +0100, Karlheinz Klingbeil wrote: > I have deonwloaded and tested reportlab, which seems to be good enough for > my needs with printing reports, formatted text and such things. > > But i have a question: > > I have not seen any hint in the docu how to print a generated PDF directly > to the printer in a portable manner, it has to work under all OS's On some UNIX systems (mine and others with a suitable PDF->printer_language filter), open a pipe to 'lp' and feed the PDF to it. On other UNIX systems you'll need to convert the PDF to PS first, then pipe it to lp. (PS is the standard interchange format for printed material) On Windows - I have no idea. Is your program GUI-based or not? If it is, then I think wxPython has some printer abstraction code you can use to let the user choose the printer, etc. Otherwise I don't know of any existing packages to insulate you from platform differences in the printing sub-system. -- The fear of the Lord leads to life: Then one rests content, untouched by trouble. Proverbs 19:23 www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From EP at zomething.com Mon Dec 22 16:46:31 2003 From: EP at zomething.com (EP) Date: Mon, 22 Dec 2003 13:46:31 -0800 Subject: Using both keyword=something and *unknownqty arguments in a function In-Reply-To: References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: <5.2.0.9.0.20031222133703.00b7a820@mail.zomething.com> Is it possible? def skeptic(first='Zeus', second='Guido', *others) print first print second print others return "and I did not think it could ever work!" answer=skeptic('believer', 'non-believer', 'heretic', first='Eric', second='unknown') Asking this seriously, please forgive any cuteness. Is there a way this can be made to work, or are these two types of arguments mutually exclusive? TIA, Eric Pederson From andymac at bullseye.apana.org.au Sun Dec 28 21:01:28 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 29 Dec 2003 13:01:28 +1100 (EST) Subject: make test segfaults with "--enable-shared" on Python 2.3.3 In-Reply-To: References: Message-ID: <20031229122230.E27671@bullseye.apana.org.au> On Sun, 28 Dec 2003, Berthold Hoellmann wrote: > CXXFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ > -ffast-math -fno-math-errno -funsafe-math-optimizations \ > -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow > > CFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ > -ffast-math -fno-math-errno -funsafe-math-optimizations \ > -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow Build Python with the configure defaults before you start getting creative with optimisation. Problems resulting from trying to use more aggressive optimisations than the default should be taken up with the compiler vendor. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From Bruce.Bon at SubaruTelescope.org Mon Dec 1 15:43:40 2003 From: Bruce.Bon at SubaruTelescope.org (Bruce Bon) Date: 1 Dec 2003 12:43:40 -0800 Subject: Sun audio blocks, even when run in a thread References: <184d1516.0311281857.4f6a8a8a@posting.google.com> Message-ID: <184d1516.0312011243.2b621053@posting.google.com> I converted this module to using threading instead of thread -- same behavior. From swalters_usenet at yahoo.com Wed Dec 31 09:50:32 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Wed, 31 Dec 2003 14:50:32 GMT Subject: RELEASED: allout-vim 031229 References: Message-ID: |Thus Spake Fran?ois Pinard On the now historical date of Wed, 31 Dec 2003 08:17:50 -0500| > [Samuel Walters] > Hello, Sam. I'm not sure I understand your question. Do you mean some > on-line documentation for allout-vim? Then see: > > http://fp-etc.progiciels-bpi.ca/showfile.html?name=allout/vim/doc.txt > http://fp-etc.progiciels-bpi.ca/showfile.html?name=allout/vim/README > > The first shows user documentation, the second contains installation > instructions. These point to a mirror of my work files, while those in > the (tiny) distribution are a bit older. > > As for a description of the distribution, I thought the little blurb > above ("The Allout file format is ...") was sufficient. Is it not? Thanks for the quick response. The first link contains the information I was interested in. Your blurb ("The Allout file format is ...") is only useful if you know what a "synoptic structure of a text file" is, especially in the context of computers. I tried googling for the term and some variations, and only turned up religious sites. I wasn't familiar with the format or the terminology. Looking up synoptic in the dictionary didn't shed much light on the situation. I just wanted to know what it did before I went through the trouble of downloading it. Thank You. Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From __peter__ at web.de Fri Dec 19 17:15:28 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 23:15:28 +0100 Subject: Parsing environment variables in ConfigParser files References: Message-ID: Robert Brewer wrote: > Does this snippet from ConfigParser.py give anyone any ideas on how to > do this without subclassing? ;) > > class RawConfigParser: > def __init__(self, defaults=None): > self._sections = {} > if defaults is None: > self._defaults = {} > else: > self._defaults = defaults > > def defaults(self): > return self._defaults The RawConfigParser does not do interpolation. >>From the docs: "Default values can be specified by passing them into the > ConfigParser constructor as a dictionary. Additional defaults may be > passed into the get() method which will override all others." I would have expected a quote with at least one "%" character ;) If you want to allow both $HOME and %(HOME)s style interpolation, overriding ConfigParser.get() is the solution with the least effort. Both replacements can then be applied orthogonally. Environment variable names are not controlled by your application, so I would oppose injecting them into the default section. > Let's not patch in a single use case when a simple generic solution > already presents itself. I tend to agree. Peter From edreamleo at charter.net Mon Dec 1 21:47:38 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 1 Dec 2003 20:47:38 -0600 Subject: wxPython / styles and marks in TextCtrl References: Message-ID: > 1.) When using a TextCtrl with styles (color etc.) in wxPython, > is it then possible to get a 'list' (or anything) from the widget > which tells you which styles are used in the widget (and where!; > 'beginning of style', 'end of style', 'type of style' ...)? I don't see anything like this in the wxTextCtrl docs. You must also check the docs for the superclasses, but there is nothing: the wxWindow class has some getters, but they apply to the window, not runs of text. Probably it would be a good idea to investigate the wxStyledTextCtrl. There are examples of using it in the wxPython demo program. This control isn't documented in the main alphabetical list of classes in the version of the docs I have. Iirc wxStyledTextCtrl is a wrapper for the scintilla classes. HTH. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From hokiegal99 at hotmail.com Fri Dec 26 20:57:38 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 26 Dec 2003 17:57:38 -0800 Subject: Identifying File type by reading files References: <93f5c5e9.0312261056.22365aa7@posting.google.com> Message-ID: <93f5c5e9.0312261757.1709f131@posting.google.com> WOW. That's a great site. Thanks for the info!!! Robin Munn wrote in message news:... > hokiegal99 wrote: > > Are there certain sets of binary data that are unique to files that > > would be a better way of identifying them? For example, on the N line > > of a MS doc file begining at position X a binary string that is L > > digits in lentgh that begins with B and ends with E will *ALWAYS* be > > present... some one tell me that I'm not dreaming and that something > > like the above example exists??? > > > > A few of my string searches today: > > > > doc = string.find(file(os.path.join(root,fname), 'rb').read(), > > 'Word.Document.') > > xls = string.find(file(os.path.join(root,fname), 'rb').read(), > > 'Excel.Sheet.') > > pdf = string.find(file(os.path.join(root,fname), 'rb').read(), > > 'PDF-1.') > > jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') > > > > Any suggestions or information that better describes how to positively > > ID files w/o the possibiliy of mistake would be very helpful to me. As > > of now, some of my files, though not many (~ 2%) will be given the > > wrong extension, but the logic of the functions is such that they > > append any extension that probably applies to the file so at that > > point it is a simple process of elimination to determine which > > extension is actually the correct one. Normally, I never have more > > than 2 unique extensions attached to the same file. > > Glutton for punishment, aren't you? :-) > > Seriously, that is a non-trivial problem. If that's what you're trying > to do, though, the file format documentation at http://www.wotsit.org/ > may be useful to you. Good luck! From sam at samuel-kleiners-computer.local Sat Dec 6 22:37:58 2003 From: sam at samuel-kleiners-computer.local (Samuel Kleiner) Date: Sat, 06 Dec 2003 21:37:58 -0600 Subject: New inited instance of class? Message-ID: Is there a builtin way of making making another instance of your own class? I really expected type(self)(*args, **keywords) to work this way. Currently i'm doing this: def new(self,*args,**keywords): from new import instance s=instance(self.__class__) if hasattr(D(),'__init__'): s.__init__(*args,**keywords) return s -- "You have to impress him! Be independent and plucky, but often do things that are moronic and out of character!" --50s Diana Dane to 90s Diana Dane From bokr at oz.net Fri Dec 19 01:02:23 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Dec 2003 06:02:23 GMT Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: On Fri, 19 Dec 2003 14:30:23 +1100, Glen Wheeler wrote: >On Fri, 19 Dec 2003 03:17:36 GMT, "Rainer Deyke" >wrote: > >>You're trying to solve the wrong problem. Python caches small integers, so >>you've only got a very small number of distinct integer objects. This is a >>good thing, because each Python object has a eight byte overhead. >>Introducing a new type wouldn't result in any memory savings. >> > > Thanks. I had thought as much, but was not totally sure. > >>The real overhead comes from the references to those objects. Each >>reference is four bytes (on 32 bit computers), and there is no way to >>decrease this. Your best option is to use high level objects that contain >>many integers internally but don't store them as individual Python >>references. The array module is one choice, Numarray is another. If >>immutability isn't an issue, you could even use strings (with each character >>treated as an eight bit integer). > > So the references to each integer is what causes the massive >overhead. > I've read up on Numarray and the array module in the docs, but >didn't see how I could adapt my current program to use these modules >because of how my data is currently organised. > I have one constantly changing dict with many millions of keys >(tuples of ints) which in turn associates itself with a tuple of ints >and two more dicts. > Every single container type contains only integers. Am I correct in >assuming that an array cannot be used as a key for a dictionary? As >they are mutable? Yes, but you might be able to do better than tuples, depending on what the ordering means and whether the same number can repeat in a tuple, etc. If we can tease out a little more about your problem, maybe we can help better ;-) E.g., how do your tuple-keys come into being and how many times are they re-used? If there is no nesting, you could create a string key just by ''.join([chr(el) for el in tup]) which wouldn't be as compact as a compressed bit string, but would be smaller than the tuple. If you were lucky, a change could gain you both time and space. I'm curious what your dicts and their int tuples represent in the real world ;-) Regards, Bengt Richter From gregj at pobox.com Mon Dec 8 15:44:29 2003 From: gregj at pobox.com (Greg Jorgensen) Date: 8 Dec 2003 12:44:29 -0800 Subject: Web authentication References: Message-ID: <9415febc.0312081244.2b03fa65@posting.google.com> luigipaioro at libero.it (Luigi) wrote in message news:... > These are my attempts: > ... > Both don't work! > Where is my mistake?? Since you don't know what the problem is and you probably aren't familiar with proxies and header sniffing, try fetching the page with curl (http://curl.haxx.se/), which you will already have if you run Linux. Once you have it working from the command line with curl you can translate to Python. Turn on curl's verbose output: curl -v http://user:password at www.mysite.com/page.html Possible reasons for your problems: - username/password wrong - url wrong - server not using basic authentication - server expecting specific referrer, IP address, user agent - secure connection (HTTPS) required Some of these problems will be apparent from curl's output. Others (like the referrer or user agent check) will not, but you can perhaps deduce them from how the site works from a browser. Greg Jorgensen PDXperts LLC Portland, Oregon USA From skip at pobox.com Sat Dec 20 19:10:40 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 18:10:40 -0600 Subject: Parsing environment variables in ConfigParser files In-Reply-To: <017301c3c65a$fe3c8040$a3e3a4d5@darkore> References: <3a8e83d2.0312190936.1746d659@posting.google.com> <017301c3c65a$fe3c8040$a3e3a4d5@darkore> Message-ID: <16356.58624.839721.459044@montanaro.dyndns.org> Bogdan> Good idea, but since you want to do this, why stop here? I would Bogdan> really like to have the possibility to expand some previous Bogdan> defined variables in the file: ... ConfigParser already does this. Skip From piir at earthlink.net Sun Dec 7 18:14:29 2003 From: piir at earthlink.net (Todd Gardner) Date: 7 Dec 2003 15:14:29 -0800 Subject: How to use the outp(...) command References: <9b849915.0312060146.7630d752@posting.google.com> Message-ID: <9b849915.0312071514.15483d44@posting.google.com> "Terry Reedy" wrote in message news:... > "Todd Gardner" wrote in message > news:9b849915.0312060146.7630d752 at posting.google.com... > > I think all I have to do is figure out how to use the outp(...) > > command. > > Python itself does not have such a command. Is there something in standard > lib? > See the following module. I believe there is an outp() command like in C if you use this module. From: Gandalf (gandalf at geochemsource.com) Subject: Re: Writing to the parallel port (Mem 0x378) when runnning WinXP or ************************************************* > http://pyserial.sourceforge.net/pyparallel.html ************************************************* > > This is my first project in python and it seems a bit daunting. I am > > trying to communicate to a custom device via the parallel port. At > > this point I only want to write data to the data port. In my case the > > memory address is x378. > > Python itself is, generally, unaware of 'memory addresses'. > > > I installed: Python 2.2, giveio_setup.exe and > > pyparallel-0.1.win32-py2.2.exe. I was running Python2.3 but I don't > > think that it will matter for this newbie project. > > Perhaps giveio... and pyparallel... (which I don't remember any clp mention > of before today) have outp() and one of the docs will tell you more about > how to use it. > > TJR > I have not yet found docs that tell me how to use the functions however, I am still betting the modules have them. Todd From tdelaney at avaya.com Wed Dec 17 01:12:05 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 17 Dec 2003 17:12:05 +1100 Subject: Beginner question - How to effectively pass a large list Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEFE0C3F@au3010avexu1.global.avaya.com> > From: J.R. [snip the results of some pretty good investigation and reasoning] > I think we could eliminate such accumulation effect by > changing the function > as follow: > >>> def f(d=[]): > d = d+[0] > print d The above would work in this case, but is not the canonical way. def f (d=None): if d is None: d = [] d.append(0) print d i.e. use None as a sentinel, and if no parameter is passed create a list to use. In particular, your version uses a different interface to perform the append - d.__add__(list) rather than d.append(int). Tim Delaney From fumanchu at amor.org Sat Dec 6 19:59:54 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 6 Dec 2003 16:59:54 -0800 Subject: list.sorted() Message-ID: Douglas Alan wrote: > "Robert Brewer" writes: > > > I've been looking through my code and can't find a single case where > > I declared a classmethod, then called it from an instance, as in the > > above example. Are there any cases where this is useful? > > Yes, it is useful. I don't know if I've made use of this feature yet > in Python, but I do know that I was bent out of shape when I realized > that C++ doesn't support "virtual static functions" (because I would > have liked to use them. ... > These functions are used in a parser that parses text representations > of objects in the class hierarchy. isLegalFieldTag() is used by the > parser to hlep determine whether or not a token it has just read is a > legal token. For example, whether "hlep" is a legal token? ;) > The reason why I wanted it to be a static function is > that whether or not a token is legal does not depend on a particular > instance -- only on the class of the instance. On the other hand, in > order to do the parsing, I do need to dispatch based on the class of a > particular instance. > > I suppose, unlike in C++, in Python I could fetch the class of the > instance, and then dispatch on that, but that might be a bit > more cumbersome. Ah, thanks. By "more cumbersome" are you talking simply about having to add .__class__ as in: anObject.__class__.foo() ...or is there more to it? I would probably implement your example by making isLegalFieldTag a plain ol' instance method. To take a trivial case: class Tag(object): legal = True def isLegalFieldTag(self): return self.legal If self hasn't defined "legal" then it is resolved via the class. I'm sure your logic was more complex, but that's the route I tend to take. Note that I'm not thinking about barring *all* class access from instances, just those methods explicitly made 'classmethods', which expect cls as a first parameter. Robert Brewer MIS Amor Ministries fumanchu at amor.org From misza at cueEvolution.com Wed Dec 3 15:43:02 2003 From: misza at cueEvolution.com (Michal (wytnijto)) Date: Wed, 3 Dec 2003 21:43:02 +0100 Subject: lambdas (lambda x: printx) Message-ID: Hi, Today I started with python and I cannot understand why expresion lambda x: print x returns syntax error (but for example lambda x: sys.stdio.write(x) does not) First I fought the reason is scopeing, but it shouldnt return syntax error. misza From mhammond at skippinet.com.au Sat Dec 20 18:28:13 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 21 Dec 2003 10:28:13 +1100 Subject: Is anyone using Python for .NET? In-Reply-To: References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: Simon B wrote: > I know everyone has probably heard what I'm about to say a couple of > hundred times, but because it's true, it should be stated. .. >> Again in passing: the concept of .NET was of course based on Java and a >> number of other higher level languages. Every book on the subject >> I've read >> says so (which by now is a small handful), and the goal (aside from >> Microsoft dominating the world as usual) was to improve upon the basic >> premise of a virtual machine. They have been successful and the truth >> stands: the Unix world is cloning .NET because it is a superior >> technology >> for a certain class of language interop problem. It remains to be seen >> whether the *Windows Forms* part of .NET will be cloned successfully, >> or is >> desired by the Unix crowd. I'm referring mainly to the IL. > > > .NET is a platform, not a language. What you probably meant to say was: > "C# is of course based on Java and a number of other higher level > langauges". No, I believe his original statement is correct. Java is both a language and a virtual machine specification. .NET was based on the idea of the JVM, but they decided to make it language agnostic (as opposed to Sun, who made absolutely no concessions to languages-other-than-Java running on their VM. The world could have been quite a bit different if it did) > .NET the platform is, to programmers, a common set of types and > libraries across multiple languages, whereas the JVM was sold along with > the language Java, which in my opinion the only difference in > marketing... Sun associated the JVM with Java so that to use the JVM > they expected you to program in Java. Weird, because they could just > have easily sold it as a platform on which other languages ran, and then > we'd all be impressed about the vision of having multiple languages use > common types... But it's happening anyway > (http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html). There are far > more languages running on the JVM than languages running on .NET. This is true, but if you speak to the language implementors, you will find they prefer .NET over the JVM - mainly as Microsoft got alot of them into a room at once, and asked them what they truly needed, then delivered. Many problems that do not exist for Java, C#, C++ or VB, but do for more niche languages have solutions inside the VM, explicitly to help solve these problems that noone inside MS ever sees. Dynamic languages are still missing some support in V1, but MS promised, and is delivering, enhancements that better support dynamic languages, even though it is not a direct issue for these MS languages. > UNIX is cloning .NET not because it is superior technology (although it > migth be, but that is arguable) but because it creates a situation where > UNIX can run all of the software being churned out by .NET programmers. I don't agree, but there is no way either of us can be proved right here. However, I seriously doubt people are putting all this work into .NET with the sole intention of running code churned out by below average programmers working for some huge insurance company - and that is exactly where .NET is "hot" at the moment. Marketting rules here - "no brain for programming - try .NET" :) The truly smart people, including the people working on alternate implementations, understand the bigger picture. > My opinion on why MS did take the .NET path is based on the premise that > they are only really interested in Operating Systems, which isn't too > bigger a stretch. They want to sell operating systems, and part of the > reason corporations don't upgrade to the lastest version until they > absolutely have to (and even then, they often don't!) is because they > have invested big money in software that will require considerable > testing and/or modification and/or risk if the underlying OS changes. > > .NET solves that problem for Microsoft. I don't understand what you are saying here. That MS only developed .NET to force people to upgrade their OS? I thought .NET was available for existing OS's, for free? MS have invested *hugely* in this - if every legitimate user of an MS OS upgraded once, I seriously doubt they would recover their investment. I believe MS are looking a little more forward than that. Underestimate MS at your own risk. It is one thing to not like MS, and possibly a reasonable positition to take. However, underestimating them is for fools. Mark. From mwh at python.net Sat Dec 27 08:33:03 2003 From: mwh at python.net (Michael Hudson) Date: Sat, 27 Dec 2003 13:33:03 GMT Subject: recursion in grammar? References: <34ea966a.0312270509.5ecc2095@posting.google.com> Message-ID: peri12345 at poczta.onet.pl (Peri) writes: > I'm trying to create Python parser/interpreter using ANTLR. > Reading grammar from language refference I found: > or_expr::= xor_expr | or_expr "|" xor_expr > > For me it looks like infinite recursion. Isn't this just left recursion (a standard LL(1) trick)? > And so it says ANTLR. Maybe I don't understand EBNF notation. For > me it should look like this. or_expr::= xor_expr | xor_expr "|" > xor_expr That wouldn't let you write "1 | 2 | 4", would it? It's not really different from recursion in programming languages (or mathematical induction) -- the Python grammar is a finite way of describing sequences of tokens of arbitrary length. You have to have *some* trick like recursion in there for this to work. I can't help you with ANTLR. Cheers, mwh -- I would hereby duly point you at the website for the current pedal powered submarine world underwater speed record, except I've lost the URL. -- Callas, cam.misc From smi at srasys.co.in Tue Dec 9 07:28:46 2003 From: smi at srasys.co.in (Mythili Madhav) Date: Tue, 9 Dec 2003 17:58:46 +0530 Subject: Help on MSAA Message-ID: <002d01c3be4f$fe0f5f60$980110ac@3mts.com> Hi, I need to write a wrapper around MSAA in Python for having my own control classes like MyApplication, MyWindow, MyPushButton etc which I think is basically to subclass from MSAA's classes. I have downloaded pyAA but I don't know how and from what to subclass. Has anybody worked on this? If yes, kindly revert. Thanks in advance, SMI -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet_spam at janc.invalid Wed Dec 3 23:17:04 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 04 Dec 2003 04:17:04 GMT Subject: Python bounties References: Message-ID: Jay Dorsey schreef: > Just read this page linked from http://slashdot.org/: > > http://www.markshuttleworth.com/bounty.html > > The /. article mentions bounties for the completion of tasks related > to the Mozilla project. I actually decided to *read* the article this > time, and came across the following snippets: > > "I'm a great fan and heavy user of Python. I prefer to fund work done > in Python" "I'm open to requests for funding work that needs to be > done to make Python the most widespread common scripting language on > the net" > > Mr. Shuttlesworth has apparently earmarked USD 100,000 for programming > milestones reached in 2004. And one of the projects he already sponsors is being written in Python too: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From rmunn at pobox.com Sat Dec 6 12:06:07 2003 From: rmunn at pobox.com (Robin Munn) Date: Sat, 06 Dec 2003 17:06:07 GMT Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: <30oAb.9577$aw2.4588872@newssrv26.news.prodigy.com> r.e.s. wrote: > "David M. Cooke" wrote ... >> "r.e.s." wrote: >> >> > But something's wrong with that explanation, because >> > of the following: >> > >> > >>> a = 'gobble' >> > >>> a is 'gobble' >> > True >> > >> > Surely `'gobble'` is not the name of an already-existing >> > object, so I expected exactly the same result as for >> > `100` and `[]`. What's going on there? >> >> Actually, your second use of 'gobble' *is* an already-existing object. >> Python 'interns' string constants, i.e., reuses them. > > > Thanks. That explains it. But take note that this behavior is not guaranteed anywhere in the language reference. As someone else said in this thread, don't count on interning. Sometimes it will happen, and sometimes it won't: >>> a = 'gobble' >>> a is gobble True >>> b = 'foo bar' >>> b is 'foo bar' False The rule of thumb is that Python interns a string if it's likely to be used as a name (i.e., only alphanumerics and underscores). The string 'foo bar' has a space and would be an invalid name, so it wasn't interned. -- Robin Munn rmunn at pobox.com From spiffy at worldnet.att.net Tue Dec 9 01:19:05 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 06:19:05 GMT Subject: running non-python progs from python Message-ID: hello, i'm fairly new to python programming and programming in general, but i have written a python prog that creates a MIDI file (.mid) and I want to be able to play it from another prog which is written in BASIC. It's a command-line prog that takes the MIDI filename as a parameter and plays the file. The 'Learning Python' book talks about using the os.system call, but I haven't been able to get this to work. How can I run this other program from a python script and pass the filename as a parameter? From max at cNvOiSsiPoAnMtech.com Thu Dec 4 10:30:32 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Thu, 04 Dec 2003 15:30:32 GMT Subject: python style guide? Message-ID: Is there anything like a style guide geared towards larger projects? I am particularly interested in module handling (size, complexity, intermodule dependencies). thanks max From alan.gauld at btinternet.com Wed Dec 17 13:46:10 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Dec 2003 18:46:10 GMT Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: <3fe0a2f6.852386076@news.blueyonder.co.uk> On Tue, 16 Dec 2003 16:21:00 +0800, "J.R." wrote: > Actually, the python is passing the identity (i.e. memory address) of each > parameter, and it will bind to a local name within the function. > > Right? Nope. This is one case where understanding something of the insides of Python helps. Basically Python variables are dictionary entries. The variable values are the the dictionary values associated with the variable names which are the dictionary keys. Thus when you pass an argument to a function you are passing a dictionary key. When the function uses the argument it looks up the dictionary and uses the value found there. This applies to all sorts of things in Python including modules - a local dictionary associated with the module, and classes - another dictionary. Dictionaries are fundamental to how Python works and memory addresses per se play no part in the procedings. HTH Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From allenabethea at aol.com Mon Dec 8 18:12:33 2003 From: allenabethea at aol.com (Allenabethea) Date: 08 Dec 2003 23:12:33 GMT Subject: Why Python won't work on .net References: Message-ID: <20031208181233.19126.00000374@mb-m13.aol.com> Actually, I did read about the MONO project for linux from a "glossy magazine" >From several websites I have seen, MONO seems to be making progress. I think it would be great to have an environment in which you are not limited by hardware, OS, or programming paradigm. If an adequate subset of .NET for linux evolves, programmers will be free to use the tools they feel most comfortable and productive with. I like python. I notice it is part of an old Caldera linux distribution I set up on an outdated PC. I notice it is part of the new OpenOffice suite. I'm going through a tutorial using python 1.5.2 on an old 486 laptop running windows 3.1. I hope a form of python will always be available. allen >Subject: RE: Why Python won't work on .net >From: "Robert Brewer" fumanchu at amor.org >Date: 12/7/03 4:25 PM Eastern Standard Time >Message-id: > >It seems to be popular among the MBRGM (Management By Reading Glossy >Magazines) crowd, many of whom are still allowed to make decisions. > > >FuManChu > From nessus at mit.edu Sun Dec 7 17:45:11 2003 From: nessus at mit.edu (Douglas Alan) Date: Sun, 07 Dec 2003 17:45:11 -0500 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: David Eppstein writes: > This doesn't make sense to me as an explanation. Smalltalk didn't reach > much of a mass audience until Goldberg's book was published in 1983, and > other object-oriented languages (e.g. C++) did not immediately adopt > CamelCase (I see none in Stroustroup's 1986 C++ book). In the meantime, > CamelCase (with or without the initial capital) was certainly used prior > to 1983 in languages such as Pascal. Someone else in this thread claimed that CamelCase came to Pascal via Apple. And we know that Apple was lapping at the time from the font of Xerox Parc. This would explain how CamelCase made it from Smalltalk to Pascal. I used Pascal in the very late '70's and very early '80's, and I never saw anyone use CamelCase in it. And now that David Epstein has jogged my memory -- it is indeed in SmallTalk that I first saw people using CamelCase, and, I must say, I was rather aghast. IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopleWouldWriteLike ThisAllTheTime. |>oug From peter at engcorp.com Fri Dec 5 14:03:37 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 14:03:37 -0500 Subject: Case sensitive and ludicrous statements (was: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> Message-ID: <3FD0D689.2C83FDEB@engcorp.com> Douglas Alan wrote: > > Regarding tuples, I never said that I represented any kind of majority > -- only what is obviously correct to *me* and some other accomplished > people. Your statement that Fredrik was "dead wrong" when he asserted the opposite could be interpreted to mean you didn't think it was just your own opinion. You've now clarified that the "dead wrong" statement was about his allegedly calling you names, not about his assertion that you were incorrect in your view so clearly I misinterpreted you (quite justifiably, I believe). > Regarding case-insensitive languages, according to my > experience, I do represent the vast majority and to plain common > sense. At least we're agreed that it is not proven whether it is you or I who is in the majority, and unless and until one of us does something to prove it which is more rigorous than merely asserting the point, we'll progress no further. End of discussion from my point of view. -Peter From skip at pobox.com Thu Dec 18 15:46:37 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 14:46:37 -0600 Subject: Broken python-model.el In-Reply-To: References: Message-ID: <16354.4653.665915.959762@montanaro.dyndns.org> Brian> Wrong type argument: sequencep, cpython Thomas> I also get the above error when the file begins with Thomas> #!/usr/bin/env Thomas> on Windows. XEmacs 21.4 (patch 13), python-mode 4.29. Thomas> Removing this line fixes it. Yeah, I can see where that would cause problems. (py-choose-shell-by-shebang) really needs to see a valid #! line. I'll see if I can figure out a way to worm around this sort of breakage. Skip From rchuso at aol.com Fri Dec 12 10:54:43 2003 From: rchuso at aol.com (rand c huso) Date: Fri, 12 Dec 2003 07:54:43 -0800 Subject: Wireless Village wbxml converter Message-ID: <3FD9E4C3.4080704@aol.com> Anybody have code for doing Wireless Village CSP 1.1 wbxml encoder / decoder in Python? Got no responses from last query. Rand. From bjorn.pettersen at comcast.net Thu Dec 25 06:02:19 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Thu, 25 Dec 2003 05:02:19 -0600 Subject: hex array to array of 16 bit numbers? References: <9b849915.0312250206.61d89841@posting.google.com> Message-ID: [posted and mailed] piir at earthlink.net (Todd Gardner) wrote in news:9b849915.0312250206.61d89841 at posting.google.com: > Hello everyone, > > I would really appreciate some of your expertise or even just > pointers. How do I convert this hex array variable "buffer" to array > of 16 bit numbers? > >>>> >>>> from ctypes import * >>>> buffer = c_buffer(8) >>>> status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, > sampleRate) >>>> print "repr(buffer.raw) =", repr(buffer.raw) > > repr(buffer.raw)= '\xcd\x00\xce\x00\xce\x00\xce\x00' >>>> > > Any ideas would be greatly appreciated! > > Todd First I think your missing the fact that the 'hex' values you're seing is simply an encoding of the byte value at that byte-index in the buffer, ie. your buffer starts with bytes containing the following values: [205] [0] [206] ... besides that, you're looking for the struct module :-) -- bjorn From http Thu Dec 11 02:12:18 2003 From: http (Paul Rubin) Date: 10 Dec 2003 23:12:18 -0800 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> Message-ID: <7xwu93g759.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > 5) use an event loop and use a generator for the relevant code; > when you discover that you need to pause, yield to the framework. This kind of design really could benefit from Raymond Hettinger's PEP of a while back, proposing being able to pass parameters from the caller back to the yield statement of a yielded generator. From tuanglen at hotmail.com Thu Dec 18 17:27:22 2003 From: tuanglen at hotmail.com (Tuang) Date: 18 Dec 2003 14:27:22 -0800 Subject: Which HTMLParser? Message-ID: The library docs show that there is an HTMLParser module and an htmllib module, both of which apparently contain classes named "HTMLParser". There is a bit of decription of differences, but it still doesn't seem clear to me what the intent is. Which one is the best choice for parsing arbitrary real-life Web pages? I get the feeling that maybe the HTMLParser module is the more recent, more practical utility, while the htmllib version is the older one, retained for backward compatibility, but I'm not sure. The docs don't exactly say that. Any recommendations or clarifications of what's going on would be helpful. Thanks. From lkcl at lkcl.net Tue Dec 16 14:55:25 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 19:55:25 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> Message-ID: <20031216195525.GJ17021@lkcl.net> On Tue, Dec 16, 2003 at 08:39:37PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > i think the only really sensible way forward is to begin from a > > sound basis - one that is going to be a big job to add retrospectively, > > but a simple beginning can be made. > > > > proposal: how about building ACLs into the python codebase? > > I fail to see how ACLs are a sound basis to solve the problem that > rexec solves. ACLs, in my view, are a sound basis to solve a different > problem (that of different identities accessing the same resources). > > Also, it seems that nowhere in your proposal you state how ACLs should > be integrated into Python: I.e. what objects are protected by ACLs, all objects - if an acl is non-null. > and how do you classify the various actions in a Python program as > read/write/execute/modify_acl? E.g. given > 3 * 4 > > Is that read, write, execute, and which ACL(s) is(are) considered? execute, and execute only, because there's no I/O involved. on the multiply operation. but _only_ if there's an actual ACL set _on_ the multiply function. if there's no acl set on the multiply function, there's no restrictions on the multiply function. l. From traveller3141 at att.net Tue Dec 30 00:08:16 2003 From: traveller3141 at att.net (Steven Gutstein) Date: 29 Dec 2003 21:08:16 -0800 Subject: Installing PyOpenGL - can't find libnumarray module References: Message-ID: <7447dd2a.0312292108.13c9a737@posting.google.com> "Mike C. Fletcher" wrote in message > Basically, to fix the problem, uninstall NumArray and install NumPy 23.0. > I tried this, without success. I also find I get the same error when I type from numarray import * I'm wondering if there's some problem with the fact that libnumarray is a .pyd file. I came across a comment that for some reason .pyd files don't get found and what I should do is create the following setup.cfg file: [py2exe] includes=numarray.libnumarray, numarray.memory, numarray._bytes, numarray._chararray, numarray._conv, numarray._converter, numarray._ndarray, numarray._numarray, numarray._operator, numarray._sort, numarray._ufunc, numarray._ufuncBool, numarray._ufuncComplex32, numarray._ufuncComplex64, numarray._ufuncFloat32, numarray._ufuncFloat64, numarray._ufuncInt16, numarray._ufuncInt32, numarray._ufuncInt64, numarray._ufuncInt8, numarray._ufuncUInt16, numarray._ufuncUInt32, numarray._ufuncUInt8 This file was supposed to be placed in the same directory as setup.py. The only reasonable setup.py I found was in c:\python23\Tools\scripts. However, my setup.cfg file still didn't work. Is there something obvious that I'm missing here ? From paul at fxtech.com Mon Dec 15 17:05:40 2003 From: paul at fxtech.com (Paul Miller) Date: Mon, 15 Dec 2003 16:05:40 -0600 Subject: PyThreadState_Swap difference in 2.3.2? Message-ID: I have a C++ application that uses multiple embedded Python interpreters. I allocate multiple interpreters using Py_NewInterpreter, and switch between them using PyThreadSate_Swap. In 2.2.2, this all worked fine. I just installed 2.3.2, but now the first time I call Py_NewInterpreter, it bails out in PyThreadState_Swap, in the debug checking code, with: Py_FatalError("Invalid thread state for this thread"); Has the interpreter/thread setup code changed since 2.2? To be complete, I set up with this: Py_Initialize(); PyThreadState *globalState = PyThreadState_Get(); // allocate new interpreter PyThreadState *interp = Py_NewInterpreter(); I am investigating to see if a crash I used to see with 2.2 is still around in 2.3, where if you call Py_Initialize() and Py_Finalize() multiple times it would die. From gagenellina at softlab.com.ar Wed Dec 24 14:48:50 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2003 16:48:50 -0300 Subject: Using Python to send a DNS update packet In-Reply-To: Message-ID: <5.2.1.1.0.20031224164632.01f8caf0@192.168.0.115> At 24/12/2003 18:29, you wrote: >I want to use Python to send a request to a Microsft DNS server to tell it >to update an A record. Ideally, this would be a secure update but primarily, >an unsecure one would do. Are there any python modules that will let me do >it or is there some code knocking around I could use ? Search for pydns or dnslib. One of them was dead and replaced by another project but I dont remember. Gabriel Genellina Softlab SRL From spam at a-nan.net Wed Dec 3 08:54:00 2003 From: spam at a-nan.net (Spam Collctor) Date: Wed, 3 Dec 2003 21:54:00 +0800 Subject: Excuse me! References: <05jpsv4et8qifi2ul0sa1at0vjua4ucakm@4ax.com> Message-ID: thx.... I will in charge of trying this lib. "Rene Pijlman" ??? news:05jpsv4et8qifi2ul0sa1at0vjua4ucakm at 4ax.com ???... > Spam Collctor: > >How can I use RFC822 to do a mail header parser? > > You'd have to read it, and then program one. > > >how do I make it? > > It has already been made: > http://www.python.org/doc/2.3.2/lib/module-email.html > > -- > Ren? Pijlman From engSpideRlem at pdxThiS.edu Sat Dec 6 06:08:02 2003 From: engSpideRlem at pdxThiS.edu (Mark Engle) Date: Sat, 06 Dec 2003 05:08:02 -0600 Subject: Moving around in a string References: Message-ID: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> Ryan Spencer wrote: > On Sat, 06 Dec 2003 09:13:53 +0000, Troels Therkelsen wrote: > > > This sounds suspiciously like homework, but... > > > >>>> foo = "Orange" > >>>> bar = foo[1:] + foo[0] + 'ay' > >>>> bar > > 'rangeOay' > > > > In other words, you can index strings the same way as any other > > sequence, [0] is the first element of the sequence, [1] the second, > > [-1] is the last, and so forth. > > > > See also the standard documentation on sequences: > > > > http://www.python.org/doc/current/lib/typesseq.html > > > > > > Regards, > > > > Troels Therkelsen > > Hey Troels, > > Thanks for the advice, Pulled it off by. > > [start code] > > def pig_latin(word): > > space = word[0] > > result = word[1:]+space+"ay" > print result > > [end code] > > This all leads me to another problem. In my recent attempts I've > been trying to learn how to parse sentences and such down more and > more (by amt. of characters, words, lines, etc.) If you don't mind > another question, how do I go about say, parsing for words in a > string? > > I would logically conclude to somehow find a way to declare that > everything with a space between it (or for every space) add one to a > 'word_count' variable maybe, but, the question for that would be how > do I get the system to search the string for a certain character, > especially if it is a space? > > Thanks a ton, > > ~Ryan I'm also new to Python, but I think I can point you in the right direction. Look into split() in library documentation. http://www.python.org/doc/current/lib/module-string.html The library documentation is a _very_ good reference. Read that whole page and you will find bunches of useful information. I found it to be very clear. Mark From edreamleo at charter.net Mon Dec 15 12:17:28 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 15 Dec 2003 11:17:28 -0600 Subject: ANN: Leo 4.1 rc1 released Message-ID: Leo 4.1 release candidate 1 is now available at: http://sourceforge.net/projects/leo/ The highlights of this release: ------------------------------- - Leo runs in batch mode when invoked with --script aScriptFile.py - Leo supports Unicode characters (e.g. Chinese) in path and file names. - @directives and section references are now valid when executing scripts. - @ignored and orphan nodes now valid in @file-nosent trees. - Script-based find/change commands. - Check Outline command. - Hoist & DeHoist commands. - A new gui-agnostic architecture: useful for batch mode and unit tests. - Several new configuration settings. - Many new unit tests. - A host of bug fixes. Quotes of the month ------------------- "I like Leo more the more I use it...It's an unexpected pleasure to see my (linearly written) code outlined in Leo. I can't wait to use Leo to start a new project, going from outline to code...Thanks again for providing the computing community with such a fine piece of software." -- Jim Shapiro, Ph.D. "If you think you have used all possible programmer's editors, but have not yet tried Leo, you are wrong...I rate Leo as a 'must have' for Python programmers. The code makes for a good read." -- John Tobler http://weblogs.asp.net/Jtobler/ What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.1 or above and tcl/tk 8.3 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Wiki: http://leo.hd1.org/ Edward K. Ream December 15, 2003 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From matt.gerrans at hp.com Tue Dec 16 16:16:48 2003 From: matt.gerrans at hp.com (Matt Gerrans) Date: Tue, 16 Dec 2003 21:16:48 GMT Subject: env variable set using _winreg.SetValueEx() doesn't show w/ os.environ References: <8de75d53.0312161259.5aef3753@posting.google.com> Message-ID: <4DKDb.10823$Ng6.2117@news.cpqcorp.net> Here is what I do; it works well on WinXP/2K/NT and with Python 2.2 and 2.3. (Of course, it wouldn't work for a "limited user" account -- for that case, it could be modified to use HKEY_CURRENT_USER instead, but it would only be able to change the "user variables" not the system variables). The code below is for updating the path variable, but you can modify it to work for any variable. Also, as you may know, this doesn't change the variable settings for the current process, just for all new processes and those few smart ones that actually pay attention to the broadcast message. If you want to also change variables for a sub-process you are launching, then additiobnally modifing those via os.environ will do the trick. If you want to add/modify variables for a process that runs *after* yours (in a shell script, for example), that's the tough one (but it can "kind of" be done by jumping through some silly hoops). """ Appends a chunk to the path in a way that puts it in effect as soon as possible. Command line syntax: appendToSystemPath [some part to append] [another var] If you specify "another var" it means you want to append that environment variable instead. This is only useful if that other variable is a path-like variable, such as classpath, pythonpath, pathext, etc. """ #--------------------------------------------------------------------------- -- # # #--------------------------------------------------------------------------- -- versions = ['2.10.5.1','3.8.18.1'] version = versions[-1] from _winreg import * from win32gui import SendMessageTimeout from win32con import HWND_BROADCAST from win32con import WM_SETTINGCHANGE import os, sys from win32con import WM_STYLECHANGING from win32con import WM_STYLECHANGED from win32con import GWL_EXSTYLE debug = os.environ.get('debug','0') == '1' #--------------------------------------------------------------------------- -- # addToSystemPath() # # Dependencies: _winreg, win32api, win32con, os. # # Description: Adds an item to the system path; currently, the effect will # will not be promulgated properly until after a reboot, # because the documented method of doing this does not work. # The new chunk will only be added if it is not already in the # path (a case-insensitive search is done to verify this). # Parameters: newPart: The chunk to add to the path. # Returns: 1 if all went well. # History: 2002-07-16 mfg: Created; also sent a acrimonious email to # Microsoft about thier inadequated documentation with regards # to setting system variables. #--------------------------------------------------------------------------- -- def addToSystemPath(newPart,item='path'): keypath = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' result = 1 try: if debug: print 'Opening',keypath key = OpenKey( HKEY_LOCAL_MACHINE, keypath ) if debug: print 'Querying',item path,dataType = QueryValueEx( key, item ) key.Close() print 'Current %s is: %s' % (item,path) if path.lower().find(newPart.lower()) == -1: if debug: print 'It does not contain',newPart path = os.pathsep.join( path.split(os.pathsep) + [newPart] ) key = OpenKey( HKEY_LOCAL_MACHINE, keypath, 0, KEY_SET_VALUE ) SetValueEx( key, item, 0, dataType, path ) key.Close() print 'Set %s in registry.' % path # Windows documentation says that this works, but it doesn't: if debug: print 'Broadcasting settings change message...' SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", 0, 1000 ) print 'New %s is:' % item print path else: print 'Nothing to do -- it is already there!' if debug: print 'All done!' except: if debug: print 'Bronk!' result = 0 return result if __name__ == '__main__': if len(sys.argv) > 1: if len(sys.argv) > 2: addToSystemPath(sys.argv[1],sys.argv[2]) else: addToSystemPath(sys.argv[1]) else: print __doc__ "Erick Bodine" wrote in message news:8de75d53.0312161259.5aef3753 at posting.google.com... > I am trying to set a new environment variable on a W2k machine with > only partial success. The name("SSID") and value("ASIM") show up > correctly in the registry and when I go to "System > Properties"->Advanced->"Environment Variables". However, if I open a > console and type 'set', "SSID" is not listed; also if I open a python > shell and do os.environ["SSID"] the variable is not found. What am I > doing wrong??? > > import _winreg > > system = r"SYSTEM\CurrentControlSet\Control\Session > Manager\Environment" > registry = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) > env_key = _winreg.OpenKey(registry, system, 0, _winreg.KEY_SET_VALUE) > > key = "SSID" > value = "ASIM" > > try: > _winreg.SetValueEx(env_key, key, 0, _winreg.REG_EXPAND_SZ, value) > except EnvironmentError: > print "Encountered problems writing (%s) into the registry" % key > > _winreg.CloseKey(env_key) > _winreg.CloseKey(registry) > > I have tried this using ActivePython-2.3.2-232 and Python-2.3.2 w/ the > same results. > > Thanks, > > ERick From martin at v.loewis.de Mon Dec 22 07:07:10 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 22 Dec 2003 13:07:10 +0100 Subject: print arabic characters In-Reply-To: <3014031e.0312220305.c38ffa3@posting.google.com> References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Ahmad wrote: > I am a python newbie, I want to print on the console UTF-8 arabic > characters. They print OK with > print text.encode("UTF-8") Are you talking about console mode (i.e. the cmd.exe window)? Or are you perhaps talking about IDLE? In Python 2.3, they should also print ok when you print a Unicode object proper; sys.stdout.encoding should indicate what encoding the terminal uses. > BUT, the characters are printed LTR, not RTL (right to left). How can > I change the printing direction?? Assuming it is IDLE: This is a bug in Tk, then - I don't know whether Tk supports RTL. Assuming it is the terminal: Does the terminal support RTL in the first place? Python does nothing else but write the characters in logical order to the terminal stream; it would be the terminal's job to put them in the right display order. Perhaps printing RIGHT-TO-LEFT MARK (U+U200F) helps? Regards, Martin From nospam at nowhere.com Mon Dec 8 22:24:48 2003 From: nospam at nowhere.com (Courageous) Date: Tue, 09 Dec 2003 03:24:48 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: >Why is python incompatible with .net? Why can't python be coded in C#? It's not. The .net virtual machine is Turing Complete. C// From echols at OCF.Berkeley.EDU Mon Dec 1 05:44:57 2003 From: echols at OCF.Berkeley.EDU (Nathaniel Echols) Date: Mon, 1 Dec 2003 02:44:57 -0800 Subject: segfault in extension module In-Reply-To: References: Message-ID: > The latter command will give a backtrace, which should tell you where it > crashes. If you don't get enough detail, make sure you compile your > module with debugging information. If you are on Windows, make then sure > that Python is compiled for debugging as well. Regards, Martin Okay: #0 0x420744fe in _int_free () from /lib/tls/libc.so.6 #1 0x420734d6 in free () from /lib/tls/libc.so.6 #2 0x0809dc0d in _PyObject_GC_Del () #3 0x080ce86f in PyDict_Next () #4 0x080d191d in _PyModule_Clear () I guess this makes sense, but I'm still not sure how to fix it. . . From tim.one at comcast.net Tue Dec 2 11:38:54 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 2 Dec 2003 11:38:54 -0500 Subject: Can Python be run off of a CD-ROM? In-Reply-To: Message-ID: [/F] >>> (all installers I've ever used or created install the core DLL in >>> the Python directory as well. are there installers out there that >>> don't do that?) [someone, possibly Gerhard H?ring] >> The Pythonlabs (or should it be called python-dev installer by now?) >> installer doesn't do this. At least not in the Windows 2000 and XP >> installations I use. [/F] > depends on the version, I suppose. the python.org installer I used on > this machine sure left a python23.dll in the c:/python23 directory. > > tim? thomas? "Early" PLabs installers stuffed python23.dll into the system directory, and scribbled registry entries under HKLM. They may also try to update a couple MSVC runtime DLLs in the system directory (e.g., Win95 didn't come with msvcrt.dll out of the box, and Python needs it). "Later" PLabs installers (sometime shortly after I started building them) grew a choice, controlled by a radio button for doing an Admin or non-Admin install. The Admin install is the default if the user running the installer has admin privileges, and acts like early PLabs installers. The non-Admin install is the default if the user running the installer does not have admin privileges, writes nothing to a system directory, scribbles registry entries under HKCU, and installs python23.dll and a couple MSVC runtime DLLs into the root Python directory. I don't think Thomas has changed any of that (yet ). From gashton at cmedltd.com Wed Dec 10 04:32:45 2003 From: gashton at cmedltd.com (Graham Ashton) Date: Wed, 10 Dec 2003 09:32:45 +0000 Subject: Pygtk, libglade References: Message-ID: On Tue, 09 Dec 2003 19:09:38 -0500, Vams wrote: > Problem: > ---------- gtk.main() ------------- > The GUI won't show up w/o calling this function. And if I do call this > function, the control of my program will stay in the mainloop until it > exists (GUI closes). This stops the daemon from doing what it normally > does. > > So, what do I need to do? Should I have the gtk.main() in its own > thread or something? Or can I somehow extend the gtk.main() so that it > does my program's tasks while keeping an eye on the GUI? You could split it into two programs; the daemon and the GUI. Then use gtk.timeout_add() to specify a call back function that the GUI can run to query the status of the daemon. It'd certainly be cleaner than threads. An alternative would be to use some file based IPC between the GUI and the daemon and use gtk.input_add() to get GTK to monitor the file handle for changes and run a function whenever it becomes readable. > Any help would be appreciated. Don't go near threads unless the above two approaches don't do what you want! -- Graham From mesteve_b at hotmail.com Wed Dec 24 21:09:18 2003 From: mesteve_b at hotmail.com (python newbie) Date: Thu, 25 Dec 2003 02:09:18 GMT Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: Thanks to both of you. That was helpful "python newbie" wrote in message news:%thGb.1817$vz5.1144 at newssvr27.news.prodigy.com... > I need the ability to debug, so I think I'm learning toward buying Komodo, > however this would only be for straight Python. When I start building a > wxPython interface to my current program, will this work? > > Does anyone currently develop in wxPython and if so, are you using a > dependable tool for debugging in this? > > Thanks > Steve > > From LittleDanEhren at yahoo.com Fri Dec 19 17:43:10 2003 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 19 Dec 2003 14:43:10 -0800 Subject: dynamic typing questions References: Message-ID: <711c7390.0312191443.4b45e90c@posting.google.com> Jason Tesser wrote in message news:... > I work for at a college where I am one of 2 full-time > developers and we are looking to program a new > software package fro the campus. This is a huge > project as it will include everything from > registration to > business office. We are considering useing Java or > Python. I for one don't like Java because I feel the > GUI is clunky. I also think that we could produce > quality programs faster in Python. > > The other programmer here is very concerned about > dynamic typing though in Python. He feels like this > would be too much of a hinderance on us and too easy > for us to make a mistake and not catch it until > runtime making debugging harder. > > OK what are your guys thoughts here? How have you all > overcome the lack of static typing? Is Python a > bad decision here? By the way we will be using > Postgres in the back if that matters to anyone. Dynamic typing is usually considered an *advantage* of Python, not a disadvantage. Usually, if you're keeping track of what the variables mean, you can use them usefully without errors. The thing about dynamic typing is that functions are more flexible, making something that would cause an error in Java not cause one in Python. So even if the error would be caught in Java, it would run fine in Python. the distinction between certain types (such as number types) is weak in Python, making everything more flexible, but it is still strongly typed where appropriate (eg. numbers and strings). If you still need something to make sure types are used correctly, try PyChecker. Sometimes (rarely), it gives an error for type use when it would run well, but it catches everything. Daniel Ehrenberg From bhan at andrew.cmu.edu Sat Dec 27 18:54:51 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Sat, 27 Dec 2003 18:54:51 -0500 (EST) Subject: Simple way to get the full path of a running script? Message-ID: I know I can do this by get sys.argv[0], tell if it's a full path, and if not, somehow join the relative path with getcwd(). Just wondering if there's a simpler way to do this. Thanks! From hans at zephyrfalcon.org Thu Dec 11 20:20:56 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 11 Dec 2003 20:20:56 -0500 Subject: Kinda newb-ish question In-Reply-To: <5c27220b.0312111650.7f0a128d@posting.google.com> References: <5c27220b.0312111650.7f0a128d@posting.google.com> Message-ID: <3FD917F8.7050204@zephyrfalcon.org> ChocoboMog123 wrote: > What's wrong with line 8 in this code? > x=1 > while 1==1: > x=x+1 > y=range(1,x) > z=0 > q=9 > for count in y: > q=x%y > if q==0: > z=z+1 > if z<1: > print x > It keeps giving me > Traceback (most recent call last): > File "C:\Python23\Prime Number.py", line 8, in -toplevel- > q=x%y > TypeError: unsupported operand type(s) for %: 'int' and 'list' The error message points out what's wrong with it... you're using the % operator with an int (x) and a list (y), which is unsupported. You probably mean something like x % count, although that doesn't make the algorithm work. Quick tips: use range(2,x) rather than range(1,x), and x % count. An infinite loop is probably not a good idea either. :-) HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From kirk at strauser.com Tue Dec 30 16:15:11 2003 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 30 Dec 2003 21:15:11 GMT Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> <87ad5a2s08.fsf@strauser.com> <7x1xqmccda.fsf@ruckus.brouhaha.com> Message-ID: <871xqm2ekg.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-12-30T19:52:01Z, Paul Rubin writes: > It normally only gets compiled once anyway, then cached. If you > have a really large number of different regexps I guess the cache > can overflow and recompilation happens. I'm not seeing that here with 2.3.3: >>> def retest(): ... for i in xrange(1000000): ... re.match(r'unlikely.*pat(..(.))?tern$', 'test') ... >>> def retest2(): ... pat = re.compile(r'unlikely.*pat(..(.))?tern$') ... for i in xrange(1000000): ... pat.match('test') ... >>> start = time.time(); retest(); stop = time.time(); print stop - start 5.39079892635 >>> start = time.time(); retest(); stop = time.time(); print stop - start 5.28148591518 >>> start = time.time(); retest2(); stop = time.time(); print stop - start 1.0404009819 >>> start = time.time(); retest2(); stop = time.time(); print stop - start 1.04278099537 Pre-compiling the pattern is a huge win on my system. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/8erD5sRg+Y0CpvERAtr8AJ43Ae2HO94T8uji3EsMRiLtRcDEEACeOhz6 Ouaa03uSgyVYkbtm2ETgZ9Q= =rbH6 -----END PGP SIGNATURE----- From peter at engcorp.com Mon Dec 1 21:47:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Dec 2003 21:47:49 -0500 Subject: NumTut corrupted References: Message-ID: <3FCBFD55.52A43F03@engcorp.com> "r.e.s." wrote: > > No matter which site I download it from, > NumTut.tgz appears to be corrupted. > Anyone else having this problem? Always describe the symptoms of a problem... what precise behaviour (i.e. what extraction program, platform etc.) are you encountering that leads you to believe it's corrupted? From bjorn.pettersen at comcast.net Thu Dec 25 04:48:42 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Thu, 25 Dec 2003 03:48:42 -0600 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: bokr at oz.net (Bengt Richter) wrote in news:bsd3ra$m85$0 at 216.39.172.122: > On Wed, 24 Dec 2003 09:23:23 -0800, Donn Cave > wrote: > >>In article <%QbGb.2109$1f6.732 at newssvr25.news.prodigy.com>, >> "Moosebumps" wrote: > [...] >> >>> A thought that occured to me is that classes are implemented as >>> dictionaries (correct?). So you could have a dictionary like this: >>> >>> x = {'a': 3, 'b': 5} >>> y = {'a': 5, 'b': 15} >>> >>> This would be the __dict__ attribute of an object I suppose. But I >>> don't see anyway to assign it to a variable so you could access them >>> like x.a and y.a. I don't know if this would be a "nice" way to do >>> it or not. It wouldn't -- using a proper __init__ initializer when you know the structure of the object is by far the better approach. If you didn't care about accessing the contained items using dot notation, you could simply do: x = dict(a=3, b=5) y = dict(a=5, b=15) If you need dot notation, there are several ways of doing it. Continuing with a dict subclass you can e.g. do: >>> class Dict(dict): ... def __setattr__(self, attr, val): ... self[attr] = val ... def __getattr__(self, attr): ... return self[attr] ... >>> x = Dict(a=3, b=5) >>> x.a 3 >>> x.b 5 >>> x.c = 42 >>> x.c 42 >>> x {'a': 3, 'c': 42, 'b': 5} >>> >>class A: >> def __init__(self): >> self.__dict__.update({'a': 3, 'b': 5}) >>x = A() >>print x.a, x.b >> >>Would it be nice? No, it would be horrible, unless you had some >>very compelling reason to do this, in which case it would be fine. > This form of the above can be useful, though: > > class A: > def __init__(self, **kw): > self.__dict__.update(kw) > x = A(a=3, b=5) > print x.a, x.b [...] This is the "inverse" of my example above. Which one I'd choose depends on how much I know about the objects and if there are many other mehtods I need to add. E.g. the __setattr__ in Dict above makes it more typing intensive to add methods to the class. If your use case for this simple struct is to have a very large number of such objects, this might be a legitimate use of __slots__, i.e. the following class will take less memory than a dictionary solution (but not enough less that it makes any sense unless you have _many_ instances of it): >>> class Data(object): ... __slots__ = 'a b'.split() ... def __init__(self, a, b): ... self.a, self.b = a, b ... def __repr__(self): ... return '' % (self.a, self.b) ... __str__ = __repr__ ... >>> x = Data(a=3, b=5) >>> y = Data(b=15, a=3) >>> x >>> y >>> it also has the side-effect that you can't assign to new attributes: >>> x.c = 42 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Data' object has no attribute 'c' >>> which is the price we pay for this memory optimization :-) > Regards, > Bengt Richter -- bjorn From john at doe.com Thu Dec 18 13:01:06 2003 From: john at doe.com (Brian Donovan) Date: Thu, 18 Dec 2003 18:01:06 GMT Subject: Broken python-model.el Message-ID: Hi All, I just compiled Python 2.3.2 on my local machine as an upgrade from 2.2. This appears to have broken my python-mode.el in emacs. When I try to "Execute Buffer" Ctl-c Ctl-c I get: Wrong type argument: sequencep, cpython Any Ideas? From ugly_411 at hotmail.com Fri Dec 12 23:07:54 2003 From: ugly_411 at hotmail.com (ugly_411) Date: Sat, 13 Dec 2003 04:07:54 -0000 Subject: Quickcam and various platforms Message-ID: Hey guys. I am in the process of writing a few tools for various astronomers who use quckcams and webcams for star imaging. I wish to be able to write up packages for generic linux, windows and Max panther. I have found for windows the VideoCapture module, which I have had some remote success with. I have seen much for Video4Linux for which I have no experience (yet). SO my question is this: Does anyone know how to access the cameras (USB specifically) in any of these operating systems? I don't mind writing a new interface if that's what it takes! Thanks ! Ugly From lutz at rmi.net Tue Dec 2 01:54:18 2003 From: lutz at rmi.net (Mark Lutz) Date: 1 Dec 2003 22:54:18 -0800 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> Message-ID: Dave Reed wrote in message news:... > On Wednesday 26 November 2003 17:02, Clark C. Evans wrote: > > Hello. I'm going to be doing quite a bit of travel in January and > > I'd like to continue to program on-the-road. So, I'm in the market > > to buy a PDA with a fullsize (foldable) keyboard. [...] > > Python runs great on the Sharp Zaurus. I can personally speak for the > 5500 but I suspect it runs fine on the 5600 and the new one that's > only officially available in Europe and/or Asia. [...] I'm using Python on a Sharp Zaurus C760 these days, one of the Japan models that you can get converted to English from a number of importers. It comes with a full VGA (640x480) swivel screen, and a nice keyboard. The keyboard isn't full size, but it's much better than the thumbs-key input of most PDAs. Python runs well on this machine too, with the Sharp ROM; you can code and run both console and Qtopia GUI applications. You can also run vim, gcc, mySql, SQLite, Apache, and so on. With gcc, you can even code and compile Python C extensions right on the PDA. There's a new X11 ROM as well (haven't tried it yet). For me, this PDA is very close to a full laptop replacement, and utterly blows away the best of the Palm devices I've owned. The combination of Linux and Sharp hardware is downright amazing. If you want a Python to go, this PDA seems ideal. More details, and a few photos: http://www.rmi.net/~lutz/pic22.html http://www.rmi.net/~lutz/pp2e-updates.html#Ss BTW, Sharp just released a new C860 clamshell model (essentially the same as the C760), and is going to release a 6000 non-clamshell in January (nicer screen, to be sold in the US). Any one of these would be a good choice, but the landscape-oriented keyboards on the clamshell models are a bonus to me. --Mark Lutz (http://www.rmi.net/~lutz) From lkcl at lkcl.net Wed Dec 17 14:58:46 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 17 Dec 2003 19:58:46 +0000 Subject: Access Control (was Re: [Python-Dev] rexec.py unuseable) In-Reply-To: <20031217190652.GE2117@lkcl.net> References: <1071669397.3fe06095c9f3c@mcherm.com> <20031217190652.GE2117@lkcl.net> Message-ID: <20031217195846.GG2117@lkcl.net> okay, to recap. jack jansen explains the difference between capabilities and ACLs: With capabilities you have an (unforgable) right to do something and no-one cares about your identity. with ACLs you have an unforgable identity which is checked against the ACL. nick coghlan gives a definition of a capability as: If you can access it, you have permission to use it. If you aren't allowed to use it, you won't even be able to see it. nick coghlan also gives a definition of an access control list as: "Entity X is allowed to perform action Y on other Entity Z". where an "Entity" may be an object, a function, a user, a module, an identity - anything - but in the context of the python language, it is presumed that "Entity" definitely NOT include "user" or anything remotely connected to the host operating system's concept of "identity". luke leighton defines "action Y" as sufficiently general to include "seeing" as well as "doing". [the reason for such is that the purpose of capabilities may then be perceived to be a subset of the purpose of ACLs.] nick coghlan describes capabilities as a "post-hoc check" which he then concludes that, by nature, the use of capabilities is therefore fast. mike chermside succinctly explains the need for fine-grained access control down to code-section level, but he disagrees with the necessity for having lists of access controls. luke leighton endeavours to justify his opinion that capabilities are appropriate for functional languages c but completely inappropriate for object-orientated languages like python (the function() and the __class__ thing). luke leighton gives a waffly explanation of the NT security descriptor concept and provides some example usage in NT services. he also gives some example ways by which NT SDs could be adapted for use by the python interpreter. guido goes agog and type-casts this discussion as definitely python 3.0-esque. l. From reply.in.the.newsgroup at my.address.is.invalid Thu Dec 11 04:08:58 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 11 Dec 2003 10:08:58 +0100 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> Message-ID: Hung Jung Lu: >From the little I read about Haskell it seems that it's possible to >keep the fundamentals clean and do complex things at the same time. Perhaps it should be the other way around: allow complex fundamentals to be able to do elegant things :-) >The usage of classes is just weird... it's a concept from the 1970s The wheel is a concept from 4000 BC (http://en.wikipedia.org/wiki/Wheel). Pardon my ignorance, but what is the next great thing to replace OO/classes? -- Ren? Pijlman From nav+posts at bandersnatch.org Mon Dec 15 14:19:31 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 15 Dec 2003 14:19:31 -0500 Subject: "Do this, and come back when you're done" References: <7x8ylg5252.fsf@ruckus.brouhaha.com> Message-ID: Kamus of Kadizhar writes: > No, actually, both machines are under my control (and in my house). > I'm slinging large (1GB MOL) files around on an unreliable, slow > wireless network. I am trying to detect an incomplete copy across the > network. If you're checking for incomplete copies, then md5 is overkill. Just make sure the file sizes match. If you're checking for corruption, then maybe doing an md5 sum would help, but again, you only need to do that if the files are the same size. The Python Cookbook site has a recipe that lets you farm out "jobs" to "worker threads", which might help you if you do go with checksumming every file: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871 Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From piir at earthlink.net Mon Dec 8 12:36:17 2003 From: piir at earthlink.net (Todd Gardner) Date: 8 Dec 2003 09:36:17 -0800 Subject: How to use the outp(...) command References: <9b849915.0312060146.7630d752@posting.google.com> <9b849915.0312071514.15483d44@posting.google.com> Message-ID: <9b849915.0312080936.1ed7a479@posting.google.com> IT WORKS with version 2.2. ! Thank you Chris! I am not sure how I can use version 2.3. The code that I need to try it out was this... And I found it of all places, in the docs... go figure :) ************************************** import parallel p = parallel.Parallel() #open LPT1 p.setData(0x55) ************************************** Thank you, Todd From eng_ak at link.net Thu Dec 25 02:51:59 2003 From: eng_ak at link.net (Ahmad) Date: 24 Dec 2003 23:51:59 -0800 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: <3014031e.0312242351.d2604c2@posting.google.com> Hi all, I just wanted to tell everyone here, that none of the tips really worked. The RTLstreamer class seemed so messed up, and printing "\u200F" before my text didn't make any difference!! I can't beleive that after all this time, unicode and bidi support still isn't working nicely :( OTOH, I tried pyGtk, the text is automatically RTL, (nice) but still the first character in the scentence isn't showing. Any other tricks? "Martin v. Loewis" wrote in message news:... > Peter Otten wrote: > > Disclaimer: As I know nothing about right-to-left printing languages, it's > > likely that I have got it at least partially wrong. > > Indeed. First of all, each Unicode character has a directionality, > available as unicodedata.bidirectional; this is L, R, or AL for most > characters; some characters have weak (EN, ES, ET, ...) or neutral > (B, S, ...) directionality. You need to find runs of characters with > the same directionality; extending the run into weak or neutral > characters. Then you need to reverse only RTL runs, leaving the LTR > runs intact. > > Next, in the process of reversing, you may need to mirrot weak LTR > characters, replacing them with their unicodedata.mirrored character. > > Then, for AL runs, you need to replace European numerals with Arabic > numerals (but keeping the LTR order). > > Finally, and again for Arabic characters, you need to perform glyph > shaping, replacing the first character of a word with the INITIAL > FORM, the last character with the FINAL FORM, all other characters > of a word with the MEDIAL FORM, and all remaining characters with > the ISOLATED FORM. This, of course, assumes your font has glpyhs > for these available. > > This is specified in more detail in > > http://www.unicode.org/reports/tr9/ > > > Can anybody point me to a way to iterate over characters with a varying > > number of bytes? > > There is no trivial algorithm. You best decode the string into Unicode, > reverse, then encode again to the original encoding. > > Regards, > Martin From ark at acm.org Fri Dec 5 10:22:41 2003 From: ark at acm.org (Andrew Koenig) Date: Fri, 05 Dec 2003 15:22:41 GMT Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: <5p1Ab.154146$Ec1.6060105@bgtnsc05-news.ops.worldnet.att.net> > Right - because if I do something like : > > a = 4 > b = a > a = 5 > print b > > It prints 4... not 5. > In other words - the line b = a creates a name pointing to the object > 4, rather than a name pointing to the contents of a..... There's no difference between "the object 4" and "the contents of a", so the "rather than" makes no sense in this context. After executing b = a the names "a" and "b" refer to the same object. From ville.spammehardvainio at spamtut.fi Fri Dec 19 06:01:05 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 19 Dec 2003 13:01:05 +0200 Subject: Sorting coordinates array References: Message-ID: Maarten van Reeuwijk writes: > I'm a newbie to Python, so sorry for this maybe trivial question. I have a > numpy array with coordinates, which I want to sort, for example first on > z-coordinate, then x and lastly y-coordinate. So an array like: Implement a comparison function: >>> help([].sort) Help on built-in function sort: sort(...) L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1 Alternatively, you could take a look at DSU pattern (Decorate, Sort, Undecorate): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234 -- Ville Vainio http://www.students.tut.fi/~vainio24 From __peter__ at web.de Thu Dec 18 15:49:16 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Dec 2003 21:49:16 +0100 Subject: cleanup after exceptions References: <0%mEb.1392$HR.4074@news.indigo.ie> Message-ID: Jp Calderone wrote: > On Thu, Dec 18, 2003 at 07:11:12PM +0000, Padraig at Linux.ie wrote: >> Hi, >> >> I'm a little confused why objects >> are not deleted after they go >> out of scope due to an exception? > > Because objects don't go out of scope. Only variables do. Objects > remain > "alive" as long as there are any references to them. > >> >> For e.g. >> >> >>> import time >> >>> >> >>> def f(): >> >>> myfile=open("file.test","w") >> >>> myfile.write("not flushed\n") >> >>> exception=throw >> >>> >> >>> f() >> >>> time.sleep(10) >> >> >> The file is not written/closed until >> the python interpreter exits. >> The same thing applies to other objects. > > In this case, the traceback still holds a reference to the frame from > which the exception was raised, which itself holds a reference to all the > locales from that function. > > Calling sys.exc_clear() (possibly followed by gc.collect()) should force > the cleanup you expect. I tried out your recipe, but with no luck: Python 2.3.2 (#1, Oct 21 2003, 10:03:19) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class T: ... def __del__(self): ... print "now i'm gone" ... >>> def f(): ... t = T() ... raise Exception ... >>> import sys, gc >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f Exception >>> sys.exc_clear() >>> gc.collect() 0 The only way to clear the reference I've found so far is a bit unorthodox: >>> raise Exception now i'm gone Traceback (most recent call last): File "", line 1, in ? Exception There seems to be some dark corner of the exception infrastructure that exc_clear() doesn't touch. However, I think it's about time to direct the OP to the solution of the "real" problem, i. e. ensuring that a resource is released when an exception occurs: >>> def g(): ... t = T() ... try: ... raise Exception ... finally: ... del t ... >>> g() now i'm gone Traceback (most recent call last): File "", line 1, in ? File "", line 4, in g Exception >>> Whether immediate garbage collection occurs, is an implementation detail. The code will be more portable if try...finally is used in such cases. Peter From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 31 12:19:23 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 31 Dec 2003 18:19:23 +0100 Subject: timing a web response using urllib.urlopen?? References: Message-ID: <0816vvcu8qvqa57aubv7cja76rnnhdemoq@4ax.com> Rene Pijlman: > self.starttime = time.time() This requires import time of course. -- Ren? Pijlman From Pieter.Claerhout at Creo.com Wed Dec 3 06:19:16 2003 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Wed, 3 Dec 2003 12:19:16 +0100 Subject: SUSPECT: Re: Python, xml, databases, ... Message-ID: <490316A24CC5D411ACD700B0D078F7F003915CA4@cseexch01.cse.creoscitex.com> SQLite is easier to embed since you don't need to install anything seperately. Include the neccesary Python modules and shared libraries, and you can create databases. With Firebird, MySQL and PostgreSQL, you need to install separate software. If I'm not mistaking, performance wise, SQLite will be faster, but I'm not sure how it handles large databases (let's say 100 MB or more). Cheers, pieter Creo pieter claerhout | remote support focal point prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Zunbeltz Izaola [mailto:zunbeltz at wm.lc.ehu.es.XXX] Sent: 03 December 2003 12:23 To: python-list at python.org Subject: SUSPECT: Re: Python, xml, databases, ... > I think you want to be clear whether you want a database or not. If you > want to put the data into a database, you probably do not want to also put > it into a file structure. Although you certainly could then store to file > in the database, I think you would end up loosing the usefulness of one or > the other (or both). > I think i prefer first to store the information in a file. And then see while the program is growing if it worth to use a database. > > What tool are suitable for this task? I have read somethin > > about MySQL and PostgreSQL, but i think they are only for servers, no > > for program, is that all right? > > What do you mean by 'they are only for servers'? > > Any machine can run a service (such as MySQL or PostgreSQL), and if it > offers that service to other machines then it is acting as 'server', or it > can just use it locally. Up, I concept missundertand of mine. I want to know if MySQL/PostgreSQL are only used in large web servers and such things, or are also used in small programs that both the server and client runs localy. > > What platform are you planning to run this on? If it is Linux, then either > MySQL or PostgreSQL are easy options - most distros have pre-compiled > versions out of the box. > I want to have the program in both linux and windows. > On Windows, both MySQL and PostgreSQL rely on the Cygwin dll. It looks like > MySQL has an easier Windows install, but their use of the cygwin dll > outside of Cygwin proper has serious stability consequences if the user > installs another cygwin based program. PostgreSQL is a 'proper' cygwin > program, but will be harder for non-unix/linux people to > install/administer. > > You could also consider Firebird (http://firebird.sourceforge.net/) it has a > native Windows version as well as a Unix/Linux version) or SQLite > (http://www.hwaci.com/sw/sqlite/) with PySQLite > (http://pysqlite.sourceforge.net/manual.html). > > There is also GadflyB5 (http://gadfly.sourceforge.net/) which looks like it > is written in pure python. There are probably other options too. > Can you give me an advaice about what has a better easy to use/performance ratio. > > I would build a GUI for the program (presumibly with wxPython). I want > > to separate the GUI layer from the program layer. For comunication of > > this two layer I have think in asyncore, but i have read something > > about twisted and piro. Can anyone give my his/her opinion about this? > > Funny, I asked almost the same question about 20 minutes before you did. I have no see the question yet :-) Cheers, zunbeltz > Cheers, > > Rasjid. > -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX -- http://mail.python.org/mailman/listinfo/python-list From bobalistar at mighty.co.za Thu Dec 4 05:34:21 2003 From: bobalistar at mighty.co.za (Bob Alistar) Date: 4 Dec 2003 02:34:21 -0800 Subject: PyThreadState_SetAsyncExc ignores except: clause Message-ID: Hello! I have an IVR server controlling Dialogic hardware through a DLL exposing the C API to Python. The server farms out incoming calls to python scripts based on the telephone number that was dialled, and these scripts are written by other people, sometimes in other companies, and quite often these people have no idea that a hangup event is actually quite hard to catch in the middle of a while1:pass. I had all sorts of alive/dead variables. I had the server load the code and pepper it with checks before I let it run. Nothing worked for all cases, and 3 oclock mornings started to get old (I use a live box, we have no test hardware ($$$)). Now I ask single threads to store their thread_id, and call PyThreadState_SetAsyncExc from my event loop. It works very well. The only issue (aside from the fact that I should not be using this at all ever ever ever and that it was only put there for real developers), is that the exception that is sent upwards from the C call is not trapped (most?all?) of the time. I think it's because I'm doing some braindead stuff, so I beg someone to look at this for me.... the C function I use --- static PyObject * cvoice_async_exc(PyObject *self, PyObject *args) { PyObject *exc; int id, n; if (!PyArg_ParseTuple(args, "iO:async_exc", &id, &exc)) return NULL; n = PyThreadState_SetAsyncExc(id, exc); if (n > 1) { PyThreadState_SetAsyncExc(id, NULL); PyErr_SetString(ErrorObject,"Problem in async_exc: abort"); return NULL; } Py_INCREF(Py_None); return Py_None; } and HangupError is defined like this: --- class HangupError(Exception): def __init__(self, msg=''): self._msg = msg Exception.__init__(self, msg) so from Python I do this --- dll.async_exc(s.thread_id, HangupError) while the thread is doing this --- 500: try: 501: print "hello" 502: except HangupError: 503: pass and I get an exception message (caught from an outer "except Exception,msg:") that reads like this: Traceback (most recent call last): file starla.py, line 501, in run print "hello" HangupError it was not caught? I've quarter-solved the issue by doing this: f = cStringIO.StringIO() traceback.print_exc(None,f) if f.getvalue().splitlines()[-1] == "HangupError": print "Caught" any ideas or answers welcome. b. From pinard at iro.umontreal.ca Sun Dec 21 18:55:11 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 21 Dec 2003 18:55:11 -0500 Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> Message-ID: <20031221235511.GA11803@titan.progiciels-bpi.ca> [John J Lee] > [Fran?ois Pinard] > > http://pinard.progiciels-bpi.ca/showfile.html?name=opinions/editors.all > Well worth reading, thanks. Thanks for the appreciation! :-) > Any good URLs for vim's Python support (scripting vim with Python, I > mean)? URLs, I do not know, but the Linux I use offers: /usr/share/vim/vim62/doc/if_pyth.txt which holds the information one needs. Succinct, but complete. You may have to re-install Vim from sources. The installation recipe I used is not far from: wget ftp://ftp.vim.org/pub/vim/unix/vim-6.2.tar.bz2 tar xfj vim-6.2.tar.bz2 pushd vim62 ./configure --prefix=/usr \ --enable-pythoninterp --with-features=big --enable-multibyte make install popd To quickly check that it works, once in the new Vim, try: :py print 3 + 5 and you should see `8' in the bottom line. > I'm currently thinking of ditching pine (for something, like pine, > that's cross-platform, does IMAP well, is free (beer) but also libre, > has a decent disconnected mode, preferably written in a high-level > language, and that doesn't offer remote buffer overflows on its > feature list!... except such a beast doesn't seem to exist). Gnus was really marvelous, nothing can really compare with it. I looked around a bit for a replacement, and the best I came with is Mutt. I did not consider Pine for long, but do not remember why I excluded it. Getting Mutt and some of my Python scripts to really cooperate required some doing, and a few kludges, and I still feel very far from having a mail agent offering Python as an extension language. I also saw Python extensible mail agents, but which had some weakness in the underlying mail engine, so far that I could judge. Mutt is not perfect overall, but I'm trying to compromise with it for now, it's still give-and-take. But at least, I now feel installed in a much more modular design for my work habits, and if I find something that pleases me more than Mutt, I could change this aspect without having to change everything else with it. In my case at least, the big move is now part of the past, the main suffering is behind. > | I still have no idea on the Vim capabilities for controlling highlighting > I've always thought the way to do this must be to allow both simple > high-level language (elisp, python) ways of doing this for covering the > broad range of languages &c., and some kind of low-level (C, I guess) > plugin standard for wiring up editors to things like the Python parser. > Who wants to reimplement the Python parser, after all? This is about editing SGML, isn't it? I wrote something for Emacs called `xxml.el', that those a job at combining colour attributes that I suspect to be beyond the Vim way of doing such things. But I may be wrong, as my knowledge of Vim is still very fragmentary. My associate, who is a linguist more than in computer science, usually likes to adopt and stick with my work habits, because I can then more fully support him. He does not object switching to Vim from Emacs as I did, but _only given_ that Vim has the equivalent of `xxml.el' first. The fact is that I understand him. How can I politely say it... Euh! Humph! OK: I am still unsuccessful at learning to enjoy HTML editing support in Vim, as it currently stands! :-) I pondered a bit about how I could rewrite `xxml.el' in Python, for later becoming a Vim extension say, but I guess it would require a fairly good amount of work on the Python side only, and no doubt that I would also need to learn Vim advanced usage much more deeply than I know it currently. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From george.trojan at noaa.gov Sat Dec 27 10:52:18 2003 From: george.trojan at noaa.gov (George Trojan) Date: Sat, 27 Dec 2003 15:52:18 +0000 Subject: Python on Max osx and tkinter In-Reply-To: References: Message-ID: <3fedaaa1$0$4761$61fed72c@news.rcn.com> Ralf Wieseler wrote: > Hello! I'm quite new to Python. > > I wrote some little scripts using the "import from tkinter" Statemant > that work well on Windows and Linux. but if i try to execute them in my > Powerbook with Mac OSX 10.2.8 i get only Errors. I imorted the TKinter > Module with the Package Manager of MacPython 2.3 but it doesn't work. > My Macphython has no idea of TKinter. > Whats wrong? > > Thanks for any help! > > Greetz Ralf > I have Mac OS X 10.3 (7B85). Tkinter that came with the OS does not work for me: > trojan$ python > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import Tkinter > Traceback (most recent call last): > File "", line 1, in ? > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter I am a newcomer to Mac, don't know whether this is a build issue (shared library for _tkinter was not linked) or a configuration problem. I guess I will have to build another version, after installing Tk and X11. George From secchi at sssup.it Sat Dec 13 06:56:16 2003 From: secchi at sssup.it (Angelo Secchi) Date: Sat, 13 Dec 2003 12:56:16 +0100 Subject: Evaluating time Message-ID: <20031213125616.312773b0.secchi@sssup.it> What is the best way to check how long a python script takes to be executed ? Thanks in advance angelo From mfranklin1 at gatwick.westerngeco.slb.com Tue Dec 16 04:31:57 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 16 Dec 2003 09:31:57 +0000 Subject: Spell checking and Python In-Reply-To: References: Message-ID: <1071566526.1687.7.camel@m-franklin> On Mon, 2003-12-15 at 19:46, Gilles Lenfant wrote: > Hi pythonists, > > Any experience or pointer on using a spell checker (aspell, ispell ?) with a > Python app ? > > Many thanks by advance > > -- > Gilles quick google for python cookbook then search for spell produces this:- http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117221 Cheers, Martin. -- Martin Franklin From tjreedy at udel.edu Mon Dec 8 12:59:15 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Dec 2003 12:59:15 -0500 Subject: More examples in the docs? References: Message-ID: "Thomas Guettler" wrote in message news:pan.2003.12.08.15.00.38.101419 at thomas-guettler.de... > Hi! > > I read "How Python is developed" (comp.lang.python.announce), > and think that there could be more examples in the docs. > > One think I really like to see: > An example with mycmp(a, b)... in the > documentation for sort(). > > I would add DSU (Decorate, sort, undecorate) there, too. > > The re module would needs more examples, too. > > I will have some spare time around christmas. > > What is the best way to do this? Send patches > via the patch tracker of sourceforge? Raymond Hettinger is expanding the tutorial to include modules in the standard lib. I am sure this will include re (or at least a reference to something). He posted a draft (for comments,etc) to pydev list on 12/3. You can access as newsgroup gmane.comp.python at news.gmane.org or check mail archives thru python.org. I would check with Ref Manual maintainers (there is a special mail address in the online version at python.org) before proposing examples to add. It is already large and I think the idea is to make it accurate and complete and improve tutorial for usage examples. TJR From bokr at oz.net Sun Dec 14 16:32:05 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 21:32:05 GMT Subject: execl difficulty References: Message-ID: On Sun, 14 Dec 2003 20:53:10 GMT, "python newbie" wrote: >Can anyone tell me why this would cause "Invalid Number of Parameters" while >trying to compile (or interpret or whatever) > >import os >os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Main >Web/dp") > >Here's what the Python reference says: > execl(path,arg0, arg1, ...) > >if you can see something obvious, please tell me I think xcopy uses suffixed optional forward-slash switch options, so it might be getting confused? I'd try (note the 'r' prefixes for raw string literals): os.execl(r"C:\WINDOWS\system32\xcopy.exe", r"E:\MainWeb\dreampics\*.*", r"E:\MainWeb\dp") I don't know what the length or count limits might be on expansion of "*.*" but hopefully it it pretty big. Regards, Bengt Richter From timr at probo.com Wed Dec 10 02:36:52 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Dec 2003 23:36:52 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: Skip Montanaro wrote: > > Paul> Here's another idea, piggybacking on the /proc filesystem: > ... > >Here's another idea. Provide a /proc filesystem on systems which don't >support one out of the box. Yes, but his pythonfs product is extremely Linux-centric, where the /proc filesystem is ALWAYS available. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From wsanchez at apple.com Mon Dec 8 17:34:34 2003 From: wsanchez at apple.com (Wilfredo Sanchez) Date: Mon, 08 Dec 2003 14:34:34 -0800 Subject: IMAP4 and deleting a message Message-ID: The docs for imaplib are pretty scant, and i guess the library is meant for people who already know IMAP well and want low-level access to the protocol, as opposed to someone who wants "get me the list of messages" and "get me #34". I'm one of the latter people, and were it not for the example, I'd have no clue how to read messages with the API. After some poking around, I'm still clueless about how to delete the messages I've read: import getpass, imaplib M = imaplib.IMAP4() M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) # DELETE THE MESSAGE HERE M.logout() Can someone hook me up? -wsv From martin at v.loewis.de Fri Dec 5 13:18:50 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Dec 2003 19:18:50 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > If you put a sequence of those in a "string," ISTM the string should > be thought of as having the same encoding as the characters whose > ord() codes are stored. So this is a matter of "conceptual correctness". I could not care less: I thought you bring forward real problems that would be solved if strings had an encoding attached. > But either way, what you wanted to specify was the latin-1 glyph > sequence associated with the number sequence I would use a Unicode object to represent these characters. > >The answer would be more difficult for (4/5)+4.56 if 4/5 was a > >rational number; for 1 < 0.5+0.5j, Python decides that it just cannot > >find a result in a reasonable way. For strings-with-attached encoding, > >the answer would always be difficult. > Why, when unicode includes all? Because at the end, you would produce a byte string. Then the question is what type the byte string should have. > >assuming it is ASCII will give the expected result, as ASCII is a > ^^^^^^^^ oh, ok, it's just an assumption. Yes. I advocate you should never make use of this assumption, but I also believe it is a reasonable one - because it would still hold if the string was Latin-1, KOI-8R, UTF-8, Mac-Roman, ... > >What is the advantage of having an encoding associated with byte > >strings? > If e.g. name had latin-1 encoding associated with it by virtue of source like > ... > # -*- coding: latin-1 -*- > name = 'Martin L?wis' > > then on my cp437 console window, I might be able to expect to see the umlaut > just by writing > > print name I see. To achieve this effect, do # -*- coding: latin-1 -*- name = u'Martin L?wis' print name > Why should I have to do that if I have written # -*- coding: latin-1 -*- > in the second line? Why shouldn't s='blah blah' result in s being internally > stored as a latin-1 glyph sequence instead of an 8-bit code sequence that will > trip up ascii assumptions annoyingly ;-) Because adding encoding to strings raise difficult questions, which, when answered, will result in non-intuitive behaviour. > >Currently, they are represented as ASCII+escapes. I see no reason to > >change that. > Ok, that's no biggie, but even with your name? ;-) I use Unicode literals in source code. They can represent my name just fine. > interesting. Will u'...' mean Unicode in the abstract, reserving the > the choice of utf-16(le|be)/wchar or utf-8 to the implementation? You seem to be missing an important point. u'...' is available today. The choice of representation is currently between UCS-2/UTF-16 and UCS-4, with UTF-8 being an unlikely candidate for implementation choice. > Yes that seems obvious, but I had some inkling that if two modules > m1 and m2 had different source encodings, different codes would be > allowed in '...' literals in each, and e.g., > > import m1,m2 > print 'm1: %r, m2: %r' % (m1.s1, m2.s2) > > might have ill-defined meaning That is just one of the problems you run into when associating encodings with strings. Fortunately, there is no encoding associated with a byte string. > But if s = '...' becomes effectively s = u'...' will type('...') => > ? Of course! > What will become of str? Will that still be the default > pseudo-ascii-but-really-byte-string general data container that is > is now? Well, will continue to be the byte string type, and conversion to str() will continue to produce byte strings. It might be reasonable to add a string() built-in some day, which is a synonym for unicode(). Regards, Martin From http Sun Dec 14 01:12:51 2003 From: http (Paul Rubin) Date: 13 Dec 2003 22:12:51 -0800 Subject: continue and break frustration References: <7xiskk6jhn.fsf@ruckus.brouhaha.com> Message-ID: <7xoeucnd0c.fsf@ruckus.brouhaha.com> Glen Wheeler writes: > I've been using the psyco compiler, and it does help (by about 60%). > I'm trying to leave writing the function as a C extension as a last > resort. Pyrex looks really nice for this situation, though I haven't tried it myself. > I will try with exceptions (get it? :). To the people in the know, > does adding this kind of construct detract from the speed of the code > much? I do know that try+except can be slower than if+else if > exceptions are generated more often than not, but how much slower? If the exception is usually taken, maybe you can reorganize the code some way so that it's not. From boris.boutillier at arteris.net Fri Dec 12 11:44:08 2003 From: boris.boutillier at arteris.net (Boris Boutillier) Date: Fri, 12 Dec 2003 17:44:08 +0100 Subject: Compiling a CPython library on Mac OSX Message-ID: Hi all, I'm trying to make a port of a python library written in C to Mac OsX, is there some documentation to help in the process ? I m having trouble with the creation of the shared library, and I'm not sure this is the way it should be done. Boris From luigipaioro at libero.it Thu Dec 4 10:20:08 2003 From: luigipaioro at libero.it (luigipaioro) Date: Thu, 04 Dec 2003 15:20:08 -0000 Subject: Web authentication Message-ID: Good morning to all! I'm trying to access on a web page that needs user and password authentication. I'm enabled to access there (I mean that I have an user name and a password to access via web), but I cannot access using an automatic procedure (that is what I need to make a daemon that downloads weekly an ASCII file from that site). I've tried using urllib: import urllib conn = urlib.urlopen("http://user:password at www.mysite.com") print conn.read() But it doesn't work (it asks me again user and password). Does anybody know how can I acces to my site with authentication? I think that urllib2 can help me but I don't undestand how!!! Thaks Luigi From mertz at gnosis.cx Tue Dec 9 03:20:21 2003 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 09 Dec 2003 03:20:21 -0500 Subject: Python progamming certification References: Message-ID: Apollo <_ at _._> wrote previously: | > Is there a Python programming certification like Sun's Java |certificates? |I know about BrainBench's certificate. Is there any? There at least *was* a BrainBench certification in Python 1.5.2. I don't know if they still offer it, given the new versions. I happen to know it once existed because I WROTE it. That said, I was *extremely* unimpressed with BrainBench's test design--I have a background in testing theory (and practice). I did the best possible within their guidelines, but the best possible was still not particularly good. If you just want a piece of paper, I suppose it doesn't matter how bad a test is. If you want the certification to actually show something about takers' abilities... well, don't bother with BrainBench. Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Iran nuclear neocon POTUS patriot Pakistan weaponized uranium invasion UN smallpox Gitmo Castro Tikrit armed revolution Carnivore al-Qaeda sarin ---[ Gnosis Software ("We know stuff") ]--------------- From exarkun at intarweb.us Tue Dec 23 11:06:09 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 23 Dec 2003 11:06:09 -0500 Subject: return statement in functions In-Reply-To: <20031223160228.GA25054@intarweb.us> References: <93f5c5e9.0312221718.23e42dac@posting.google.com> <20031223160228.GA25054@intarweb.us> Message-ID: <20031223160609.GB25054@intarweb.us> On Tue, Dec 23, 2003 at 11:02:28AM -0500, Jp Calderone wrote: > > def report(*work): > outputFile = open('report.txt', 'w') > for f in work: > outputFile.write(str(work()) + '\n') > outputFile.close() Of course, I meant to be calling "f()" in the loop. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rasjidw at openminddev.net Thu Dec 11 09:32:30 2003 From: rasjidw at openminddev.net (Rasjid Wilcox) Date: Fri, 12 Dec 2003 01:32:30 +1100 Subject: Upgrage openoffice to 2.3.3? References: <20031210182052.26181.00000472@mb-m15.aol.com> Message-ID: <3fd87fac@mail.netspeed.com.au> Allenabethea wrote: > Is there any advantage to upgrading the python distribution > which is part of OpenOffice to 2.3.3? > I notice it is version 2.2.2 > Are the bug fixes crucial? I think you will find that the python that comes with OpenOffice is a non-standard version required to support the Python-UNO bridge. If you want to automate OpenOffice with Python, it seemst that you need to use the python binary distributed with OO, and not your standard python binary (if you have one). However, I have only played with this very briefly, so I could be wrong. See http://udk.openoffice.org/python/python-bridge.html for details, or write to the OO Udk mailling list. (See the end of the above link.) Cheers, Rasjid. From jjl at pobox.com Tue Dec 23 14:53:43 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 19:53:43 +0000 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> <3FD9D4E9.FE199F61@engcorp.com> <7xfzfphdzt.fsf@ruckus.brouhaha.com> <3FDDC1FD.6687FD2@engcorp.com> <874qw0zxzw.fsf@pobox.com> <3FE86133.ADF4810F@engcorp.com> Message-ID: <87u13ria48.fsf@pobox.com> Peter Hansen writes: > "John J. Lee" wrote: [...] > > Of course, cookies are "allowed" to vanish at random times. I > > remember reading something about servers telling browsers which > > cookies are important to users and shouldn't be thrown away, but I've > > completely forgotten where that was... > > Hmm.... I doubt they're supposed to vanish if there is not too much > data stored in them, and as there are no reports that I can find on the I guess the only way to find out would be to find/write a little proxy that keeps the most recent N HTTP messages, so you can look back at what happened after they vanish. > web about similar behaviour, I suspect they _don't_ vanish, even if they're > allowed to. You mean maybe the server deletes them by mistake? Could be. John From francisgavila at yahoo.com Wed Dec 17 15:04:30 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 17 Dec 2003 15:04:30 -0500 Subject: Converting arrarys in Python to arrays in C References: <3fe06b14$0$25662$cc9e4d1f@news.dial.pipex.com> Message-ID: Simon Foster wrote in message <3fe06b14$0$25662$cc9e4d1f at news.dial.pipex.com>... >I have some code which attempts to convert Python arrays (tuples of >tuples of tuples...) etc. into C arrays with equivalent contents. > >The prototype code is shown below. This doesn't generate legal C. It also does no bounds checking, so you may end up with a Python int that doesn't fit into a C char. (Which is most certainly 1 byte, so why do you use 4 hex digits to represent it?) >My only question is, is there some way of doing this without repeating >the try..except blocks ad-infinitum to handle 3D, 4D arrays etc. Of course. This approach you used is in fact very unusual, especially with the print statements. You've simply made a special purpose function for each depth of array. >I can see there is a pattern here but I can't seem to turn it into a >loop. Would a recursive solution do the trick? The recursive solution is more natural here, I think, but iterative is possible, too. The pattern is ', '.join(), where is {}. The rest is just fluff. You seem to have gotten hung up on the type declaration. You can't declare the type until you know the depth of the array, so generate the array first, *then* get construct the declaration. Now for homework, convert the hackish solution below into a recursive generator. ;) def seqtobrace(seq, depth=0): """Return a comma- and brace-delimited version of seq, and the depth of seq.""" depth += 1 if isinstance(seq[0], (tuple, list)): subelem, depths = zip(*[seqtobrace(s, depth) for s in seq]) delim = ',\n' + ' '*2*depth depth = depths[0] elements = delim.join(subelem) elif isinstance(seq[0], (int, long)): elements = ', '.join(map(hex, seq)) else: raise TypeError, "seq must be list or tuple with int or long leaves." return '{ %s }' % elements, depth def toCarray(seq, name): """Return an unsigned char C array declaration of name from seq.""" assert isinstance(name, basestring) if isinstance(seq, (int, long)): return 'unsigned char %s = 0x%X;' % (name, seq) else: array, depth = seqtobrace(seq) ad = '[]'*depth typedec = 'unsigned char%s %s = \n' % (ad, name) return typedec + array + ';' -- Francis Avila From stephan.diehlNOSPAM at gmx.net Mon Dec 29 11:08:39 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Mon, 29 Dec 2003 17:08:39 +0100 Subject: Some optimization tale References: <0gf0vv4o95ql695fkgemodebdlgvvsh7u7@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Sat, 27 Dec 2003 17:36:46 +0100, rumours say that Stephan Diehl > might have written: > >>A while ago, I've posted a recipie about finding a common prefix to a list >>of strings. While the recipie itself is quite bad (I have to admit) and I >>didn't know at that time that this problem was solved already in the >>os.path module. >>The interesting part can be found in the commentaries, as this turned out >>to be a quest for the most efficient algorithm to solve this particular >>problem. > > You might also want to read: > > http://www.python.org/sf/681780 Terry's solution is much faster (at least on my test set) and, as an additional benefit, is the easiest to understand. From mwh at python.net Mon Dec 1 13:45:28 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Dec 2003 18:45:28 GMT Subject: segfault in extension module References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: Nathaniel Echols writes: > > Looks like refcount problems, check out > > http://www.python.org/doc/current/ext/refcounts.html . > > I read this before and couldn't figure out what it meant. Then I am pretty sure this is your problem :-) > This does seem like it would relate, but I can't figure out what I'm > doing incorrectly. I just have one function which calls a pure C > function and returns a tuple of strings from it. I'm guessing I > need to add a Py_INCREF() somewhere but so far this just makes it > segfault sooner. (I'm not sure what argument to use for > Py_INCREF(), either.) > > I've looked at several other pages, and they all seem to involve setups > more complicated than what I'm doing. I'm already using Py_BuildValue() > to generate the returned tuple, and my understanding is that this should > avoid major problems. . . Post some code. Cheers, mwh -- If Unicode is a horde of zombies with flaming dung sticks, the hideous intricacies of JIS, Chinese Big-5, Chinese Traditional, KOI-8, et cetera are at least an army of ogres with salt and flensing knives. -- Eric S. Raymond, python-dev From mwh at python.net Tue Dec 2 07:25:45 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Dec 2003 12:25:45 GMT Subject: Can Python be run off of a CD-ROM? References: Message-ID: eddie at holyrood.ed.ac.uk (Eddie Corns) writes: > "BJ MacNevin" writes: > > >Hi all, > > >I teach middle school and am currently trying to bring some computer science > >to the students. Our district has a wonderfully linked network throughout > >all our schools... done via MS Windows Network. In order to protect the > >network, our district's IT department does not want things installed on the > >system (or at least makes it VERY difficult to get it done). SO, I am using > >MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it > >off of them. > > >BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I > >can do the same thing... or something similar? Is there a way to install > >Python on a CD-ROM, too, if we don't need it to be accessed from a command > >prompt? Instinct says this Should Just Work. Things to worry about are whether Python gets uppity about not being able to write to sys.path (shouldn't do, happens all the time on linux) and making sure Python can find its files. [...] > Anyway, to answer the main question. You can create a file system with all the > Python files on it and run from there but I think the main problem is search > paths and the like. I believe you ideally need to get the relevant information > into the registry but if you're not able to I think this is problematic. I am *fairly* sure that recent Pythons do not go near the registry. win32all stuff does, and probably has to to get COM stuff working. Cheers, mwh -- It is time-consuming to produce high-quality software. However, that should not alone be a reason to give up the high standards of Python development. -- Martin von Loewis, python-dev From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Dec 1 01:52:51 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 1 Dec 2003 07:52:51 +0100 Subject: how to show a bitmap? References: Message-ID: http://www.pygame.org From jarrodhroberson at yahoo.com Mon Dec 8 16:33:40 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 8 Dec 2003 13:33:40 -0800 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: "Martin v. L?wis" wrote in message news:... > Ville Vainio wrote: > > > What, has .NET suddenly turned out to be popular while I wasn't > > watching? > > Where I work, .NET is pretty popular. People are fascinated of > introspection/reflection, (relative) platform-independence, > ubiquitous serialization, powerful development tools, and the > back-up of a large company. > > Of course, they all use C#, and consider the other .NET languages > toys. > > Regards, > Martin only if you mean Windows 95, 98, ME, 2000, XP as "platform independant" .Net is and for all PRACTICAL PURPOSED be a WINDOWS ONLY development / runtime environment. From jepler at unpythonic.net Mon Dec 29 08:44:50 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Dec 2003 07:44:50 -0600 Subject: strftime - %a is always Monday ? In-Reply-To: <282f826a.0312290503.398d72cd@posting.google.com> References: <282f826a.0312290503.398d72cd@posting.google.com> Message-ID: <20031229134450.GC6171@unpythonic.net> strftime obeyes the exact values specified in its arguments. You specify that tm_wday is 0, so it prints monday. If you want to start with a partial time specification (at least year/month/day), you need to first use mktime() to convert it to seconds-since-epoch, then back to the tuple representation with localtime(). >>> from time import * >>> lst1 = ['2003', '12', '27'] >>> tm = (int(lst1[0]), int(lst1[1]), int(lst1[2]), 0, 0, 0, 0, 0, 0) >>> print strftime("%A, %d (%w %y %m)", tm) Monday, 27 (1 03 12) >>> t = mktime(tm) >>> tm1 = localtime(t) >>> print tm1 (2003, 12, 27, 0, 0, 0, 5, 361, 0) >>> print strftime("%A, %d (%w %y %m)", tm1) Saturday, 27 (6 03 12) Jeff From jepler at unpythonic.net Mon Dec 22 15:14:55 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 22 Dec 2003 14:14:55 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <21bb8d55.0312221204.51d86182@posting.google.com> References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: <20031222201454.GB24252@unpythonic.net> Here are several ways: def count_initial(s, c): return len(s) - len(s.lstrip(c)) def count_initial(s, c): r = "^" + re.escape(c) + "*" m = re.match(r, s) return len(m.group(0)) # enumerate in 2.3 def count_initial(s, c): for i, j in enumerate(s): if j != c: break return i # itertools in 2.3 def count_initial(s, c): return len(list(itertools.takewhile(lambda x: x==c, s))) Jeff From christian.eslbauer at liwest.at Tue Dec 30 10:56:17 2003 From: christian.eslbauer at liwest.at (EsC) Date: Tue, 30 Dec 2003 16:56:17 +0100 Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> <79v2vv0ijgdvqu354uh4mh21v4b3liurj0@4ax.com> Message-ID: <1072798233.200308@news.liwest.at> hy! thanks for your explanations! i want to avoid performance-problems by repeated (very often) function-calls with very long strings. in some languages (C, PHP, Powerbuilder, ...) i have the opportunity, to pass "by value" or "by reference/pointer)". "by value": the CPU must perform a complete copy of the string "by reference/pointer": only a long value (address) is passed ... the performance difference is in most cases unimportant, but sometimes ... Unfortunately i made an error by testing the behavior of Phyton, and so i thougt, LISTs are also passed "by value". But this isn't true, and so i can solve my problem by putting the string- argument in the first place of a list. greetings iolo "Christos TZOTZIOY Georgiou" schrieb im Newsbeitrag news:79v2vv0ijgdvqu354uh4mh21v4b3liurj0 at 4ax.com... > On Tue, 30 Dec 2003 14:21:46 +0100, rumours say that "EsC" > might have written: > > >Hy! > > > >is it possible to pass function-arguments by reference? > >(for example in PHP you can use the "&" operator ... ) > > > >thx > >iolo > > > > There is no such concept as "pass by value" in python. Only references > are passed around, and therefore there is no special syntax for that. > > What you need to understand is that objects can be mutable (changeable) > or immutable. Search for these terms in the python documentation. > > In other languages, variables are a container: they contain a "value". > In python, "variables" are only "names" referring to "objects" and they > have no "value". If you assign anything to a name, you just change the > object it is pointing to. > > Presumably you ask this question because you want your function to pass > back some more data than its return value. Python handles fine multiple > values, check for "tuple" in the docs. > > An example: (I am not familiar with php, therefore I will write program > A in pseudocode, but you will get the point I hope) > > function f(&a): > if (a > 10) then a = 10 > return (a*2) > > var = 20 > result = f(var) > > This function makes sure that the "var" variable stays less than or > equal to 10, and then returns the double of the corrected argument. > > In python you would do this: > > def f(a): > if a > 10: > a = 10 > return a, a*2 > > var = 20 > var, result = f(var) > > If not covered, please write back. > > PS reading this could be helpful too: > http://www.effbot.org/zone/python-objects.htm > > -- > TZOTZIOY, I speak England very best, > Ils sont fous ces Redmontains! --Harddix From r.s at XXmindspring.com Mon Dec 1 23:34:39 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Tue, 02 Dec 2003 04:34:39 GMT Subject: NumTut corrupted References: <3FCBFD55.52A43F03@engcorp.com> Message-ID: "Peter Hansen" wrote ... > "r.e.s." wrote: > > > > No matter which site I download it from, > > NumTut.tgz appears to be corrupted. > > Anyone else having this problem? > > Always describe the symptoms of a problem... what precise > behaviour (i.e. what extraction program, platform etc.) are > you encountering that leads you to believe it's corrupted? Quite right, sorry. I resolved the problem, but will explain what happened in case others encounter something similar ... The file called NumTut.tgz at the SourceForge.net download server is, when downloaded, automatically receiving the wrong file extension by winXP . (WinZip then produces a file that looks like a .py file corrupted by lots of 'unprintable' characters.) That is, clicking NumTut.tgz for download results in "You are requesting file: /numpy/NumTut.tgz Please select a mirror" but the winXP File Download window that comes up says File name: NumTut.gz (sic) File type: WinZip File If renamed back to .tgz, WinZip decompresses it properly, and I see that it's actually a number of files which are python-importable when placed in the folder ...\Numerical\NumTut. (Also for other files from that site, I've sometimes had to re-download when the file is found not to be in recognizable format. This problem seems to occur only for files downloaded from SourceForge, btw.) ===== A related python question, if I may ... With the various .py files in \Numerical\NumTut, *none* of which are named NumTut.py, why does this work? ... >>> from NumTut import * Surely import doesn't use the folder name? As you can see, I'm a beginner at python. Thanks. -- r.e.s. From blk at srasys.co.in Wed Dec 3 08:34:27 2003 From: blk at srasys.co.in (bala) Date: Wed, 3 Dec 2003 19:04:27 +0530 Subject: How to use TestResult Class Message-ID: <014201c3b9a2$2c7e96c0$440210ac@Bala> Hi, Question in UnitTest Module Iam having a TestCase.....Iam able to run that test case..If i want to see the Result..I have to use TestResult Class Right..I don't know how to use the class to print the Result I need Example Code for TestResult class in unittest module.. Here is the Test Case -------------------------------- import unittest import ModNumCal class NumTestCase(unittest.TestCase): def testaddNumber(self): self.assertEqual(ModNumCal.addNumber(0,1),1) def testdivNumber(self): self.assertEqual(ModNumCal.divNumber(10,2),3,"It is Equal") def testdivNumber(self): self.assertEqual(ModNumCal.divNumber(10,2),5,"It is Equal") testCaseSuite = unittest.TestSuite() testCaseSuite.addTest(NumTestCase("testaddNumber")) testCaseSuite.addTest(NumTestCase("testdivNumber")) runner = unittest.TextTestRunner() runner.run(testCaseSuite) ModNumCal.py ----------------------- def addNumber(a=None,b=None): c = a + b return c def divNumber(d=None,e=None): f = d/e return f def multiplyNumber(g=None,h=None): i = g * h return i After Run this TestCase it prints like this .. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK Note: I want to Print the Result...Kindly Give Some Example Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From nhodgson at bigpond.net.au Sun Dec 7 07:49:02 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sun, 07 Dec 2003 12:49:02 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: <2lFAb.43218$aT.25634@news-server.bigpond.net.au> Ruby 2.0 will probably implement strings with encoding attributes. The developers want to avoid changing encoding whenever possible. One posting I saw had joining strings with different encodings as an error although I don't know if this has been finalised. I doubt whether it will work well, so I think the best approach for Python is to watch Ruby and if it is successful then copy. "m17n" is the magic googling term but most of the available information is encoded in Japanese (EUC). Neil From andymac at bullseye.apana.org.au Thu Dec 4 17:00:46 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 5 Dec 2003 09:00:46 +1100 (EST) Subject: anydbm bug ? In-Reply-To: References: Message-ID: <20031205085551.M62102@bullseye.apana.org.au> On Thu, 4 Dec 2003, Gary Richardson wrote: > According to the Python Library Reference invoking anydbm.open() with flag > value 'n' should always create a new empty database. However, the following > code produces an error. I stumbled upon this while writing some test code. > Opening and closing the file before invoking anydbm.open() was an attempt to > delete the results of a previous test. Does this indicate a bug in anydbm? > > import anydbm > filename = r'C:\My Documents\Python\misc\testdb.tmp' > f = open(filename, 'w') > f.close() > file = anydbm.open(filename, 'n') I don't think there's a bug in anydbm, though the docs perhaps should make clear that you should make sure any db files are removed before attempting to create a new db. truncation is a poor way to attempt to get rid of anything that might exist - if it exists, delete it. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bhoel at web.de Mon Dec 29 14:47:06 2003 From: bhoel at web.de (Berthold Höllmann) Date: Mon, 29 Dec 2003 20:47:06 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: Andrew MacIntyre writes: > On Sun, 28 Dec 2003, Berthold Hoellmann wrote: > >> > When I use >> > >> > ./configure --with-thread --with-fpectl --with-signal-module \ >> > --with-pymalloc --enable-shared --with-cxx=g++ >> > >> > make test >> > >> > on 2.3.3 I get >> > >> > ... >> > test_queue >> > test_quopri >> > test_random >> > test_re >> > make: *** [test] Speicherzugriffsfehler (Speicherauszug erstellt) make: *** [test] Segmentation fault (core dumped) >> >> Everything works fine if I remove the "--enable-shared" flag from >> configure. > > You don't mention what platform you are seeing this on. The output of a > verbose test run (python Lib/test/regrtest.py -v test_re), preferably with > error messages translated to English, may help diagnose the issue. env LANG=C LD_LIBRARY_PATH=/home/devel/compile/Python-2.3.3:/usr/local/v/lib:/usr/lib/qt3/lib:/usr/local/pgsql/lib:/usr/teTeX/lib./python Lib/test/regrtest.py -v test_re (LD_LIBRARY_PATH is taken from the "make test" output) gives: test_re test_anyall (test.test_re.ReTests) ... ok test_basic_re_sub (test.test_re.ReTests) ... ok test_bigcharset (test.test_re.ReTests) ... ok test_bug_113254 (test.test_re.ReTests) ... ok test_bug_114660 (test.test_re.ReTests) ... ok test_bug_117612 (test.test_re.ReTests) ... ok test_bug_418626 (test.test_re.ReTests) ... ok test_bug_448951 (test.test_re.ReTests) ... ok test_bug_449000 (test.test_re.ReTests) ... ok test_bug_449964 (test.test_re.ReTests) ... ok test_bug_462270 (test.test_re.ReTests) ... ok test_bug_527371 (test.test_re.ReTests) ... ok test_bug_545855 (test.test_re.ReTests) ... ok test_bug_612074 (test.test_re.ReTests) ... ok test_bug_725106 (test.test_re.ReTests) ... ok test_bug_725149 (test.test_re.ReTests) ... ok test_bug_764548 (test.test_re.ReTests) ... ok test_category (test.test_re.ReTests) ... ok test_constants (test.test_re.ReTests) ... ok test_expand (test.test_re.ReTests) ... ok test_finditer (test.test_re.ReTests) ... ok test_flags (test.test_re.ReTests) ... ok test_getattr (test.test_re.ReTests) ... ok test_getlower (test.test_re.ReTests) ... ok test_groupdict (test.test_re.ReTests) ... ok test_ignore_case (test.test_re.ReTests) ... ok test_non_consuming (test.test_re.ReTests) ... ok test_not_literal (test.test_re.ReTests) ... ok test_pickling (test.test_re.ReTests) ... ok test_qualified_re_split (test.test_re.ReTests) ... ok test_qualified_re_sub (test.test_re.ReTests) ... ok test_re_escape (test.test_re.ReTests) ... ok test_re_findall (test.test_re.ReTests) ... ok test_re_groupref (test.test_re.ReTests) ... ok test_re_groupref_exists (test.test_re.ReTests) ... ok test_re_match (test.test_re.ReTests) ... ok test_re_split (test.test_re.ReTests) ... ok test_re_subn (test.test_re.ReTests) ... ok test_repeat_minmax (test.test_re.ReTests) ... ok test_scanner (test.test_re.ReTests) ... ok test_search_coverage (test.test_re.ReTests) ... ok test_search_star_plus (test.test_re.ReTests) ... ok test_special_escapes (test.test_re.ReTests) ... ok test_sre_character_literals (test.test_re.ReTests) ... ok test_stack_overflow (test.test_re.ReTests) ... ok test_symbolic_refs (test.test_re.ReTests) ... ok ---------------------------------------------------------------------- Ran 46 tests in 0.401s OK Running re_tests test suite 1 test OK. CAUTION: stdout isn't compared in verbose mode: a test that passes in verbose mode may fail without it. so it seems that the other modules loaded in the "make test" run decrease the avaliable stack so that the test does not succeed but calling the test alone finds enough stack space avaliable? > I know that there are platforms where the amount of stack space available > to a threaded process is not easily controlled, and recent versions of gcc > are creating much larger stack frames than earlier versions. The sre > module in 2.3.x (and earlier) is recursive and thus sensitive to stack > space availability. A core dump is a likely indicator of this. Read the > Modules/_sre.c source file for more info. sre in 2.4 will be > significantly improved in this regard. > > FYI, since 2.3 PyMalloc is a default option so you don't need > --with-pymalloc, and most recent Linux and BSD systems will default to > building with --with-thread and --with-signal-module. I really should know, but I usually keep "good" configure settings for reuse and normally don't think much about the settings when everything works. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From martin at v.loewis.de Mon Dec 1 14:14:34 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Dec 2003 20:14:34 +0100 Subject: compile(unicode) & source encoding References: Message-ID: "Denis S. Otkidach" writes: > Why we have to choose one particular encoding and not just assume > all strings to be unicode? Assume the source code reads source = u""" f=open("/etc/passwd","a") f.write("news:x:9:13:News system:/etc/news:/bin/bash\n") """ What data type should the argument of f.write have, in this example? If the answer is not , you would cause many compatibility problems. > Surely. But there is no way to emulate "python -U" behavior for > compiled piece of code. However, python -U does not currently work. When it does, exposing it separately to compile() might be reasonable. OTOH, the current behaviour might be sufficient: If -U is passed, strings created in compile would automatically be Unicode strings - which is the case today. Regards, Martin From donn at drizzle.com Sat Dec 13 12:57:37 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 13 Dec 2003 17:57:37 -0000 Subject: "Do this, and come back when you're done" References: None Message-ID: <1071338254.885587@yasure> Quoth Kamus of Kadizhar : | I have the following function which generates MD5 hashes for files on a | local and remote server. The remote server has a little applet that | runs from inetd and generates an MD5 hash given the file name. | | The problem is that it takes 2+ minutes to generate the MD5 hash, so | this function takes about 5 minutes every time it is called. Since the | first MD5 hash is generated on a remote machine, the local machine does | nothing but wait for half that time. | | Is there any way to rewrite each half of the function to run in the | background, so to speak, and then have a master process that waits on | the results? This would cut execution time in half more or less. Yes. I may be missing something here, because the followups I have seen strike me as somewhat misguided, if they're not just fooling with you. You already have two independent threads or processes here, one on each machine. All you need to do is take the results from the remote machine AFTER the local computation. Move the line that says "remoteMD5hash = Socket.recv(256)" to after the block that ends with "localMD5hash = hasher.hexdigest()". No? Donn Cave, donn at drizzle.com ----------------------------------- | # checkMD5 | def checkMD5(fileName, localDir): | # get remote hash | Socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) | Socket.connect((MD5server,888)) | #throw away ID string | Socket.recv(256) | Socket.send(fileName+'\n') | remoteMD5hash = Socket.recv(256) | | # get local hash | try: | file=open(makeMovieName(localDir,fileName), 'r') | except IOError: | localMD5hash = '0' | else: | hasher = md5.new() | while True: | chunk = file.read(1024) | if not chunk: | break | hasher.update(chunk) | localMD5hash = hasher.hexdigest() | if Debug: print "local:",localMD5hash, "remote:",remoteMD5hash | return localMD5hash.strip() == remoteMD5hash.strip() | | -Kamus From phil.hornby at accutest.co.uk Tue Dec 30 08:28:20 2003 From: phil.hornby at accutest.co.uk (Phil Hornby) Date: Tue, 30 Dec 2003 13:28:20 -0000 Subject: C++ and Python: how can I make it stop? In-Reply-To: Message-ID: I did something similar a while ago... My simple solution was this: As part of my application API I exposed a function "Stop()" in my app I had 2 threads - one that was the GUI etc and another that Python is executed in( using PyRun_SimpleString ). It then becomes the responsibility of the script to ensure that it calls "Stop()" regularly to check whether it should stop executing... We defined a structure with a script containing a function "main()" that was executed by the main app; this function contained a simple loop checking the status - most of the functionality we had relied on callbacks into the script's context from other threads of execution. eg. import gui def a_callback(): # do something def main(): # do some initialisation while not gui.Stop(): # so something # do some shutdown It is a fairly simple structure but it did work fairly well. HTH Phil From http Thu Dec 4 14:47:11 2003 From: http (Paul Rubin) Date: 04 Dec 2003 11:47:11 -0800 Subject: Web authentication References: Message-ID: <7xn0a8qsao.fsf@ruckus.brouhaha.com> "luigipaioro" writes: > Does anybody know how can I acces to my site with authentication? > > I think that urllib2 can help me but I don't undestand how!!! It's documented in the manual. Try something like (untested): import urllib class Open_with_auth(urllib.FancyURLopener): def prompt_user_passwd(self, host, realm): return ('username', 'userpassword') # the uid and passwd you want to use urllib._urlopener = Open_with_auth() From fredrik at pythonware.com Thu Dec 11 01:29:27 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 07:29:27 +0100 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> Message-ID: Aaron Watters wrote: > ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha now, how cool is this. hugunin and watters both reappear after many years, on nearly the same day, both with stuff that shows that they didn't really give up on Python hacking; they've just been working on the perfect design... > In order to allow transactions to wait the options are: > > 1) Use an event loop and write the application "inside out", > much like a fortran 4 program attempting to emulate recursion. > > 2) Use operating system threads (which have very high overhead > and sometimes don't really work the same across different > platforms...) > > 3) Use stackless. > > 4) punt: automatically abort any transaction which needs > to wait. 5) use an event loop and use a generator for the relevant code; when you discover that you need to pause, yield to the framework. From ville.spammehardvainio at spamtut.fi Fri Dec 19 18:58:04 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Dec 2003 01:58:04 +0200 Subject: UserLinux chooses Python as "interpretive language" of choice Message-ID: I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville Vainio http://www.students.tut.fi/~vainio24 From miki.tebeka at zoran.com Sun Dec 28 02:53:43 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 27 Dec 2003 23:53:43 -0800 Subject: How to determine if an instance of your program is already running? References: Message-ID: <4f0a9fdb.0312272353.6f85eaf3@posting.google.com> Hello Mike, You can have your program create a known directory (which IIRC an atomic operation). When a new instance tries to create it, there will be an exception. Make sure that when you application is closing to remove this directory. HTH. Miki From pythonguy at Hotpop.com Wed Dec 10 01:31:32 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 9 Dec 2003 22:31:32 -0800 Subject: Python progamming certification References: <87fzfuszsq.fsf@pobox.com> Message-ID: <84fc4588.0312092231.279ba130@posting.google.com> Perhaps this mail need to be brought to the attention of the marketing-python mailing list as a possible (not to mention easy too!) way of making money from Python :-)) Well Brandon, where art thou?? -Anand jjl at pobox.com (John J. Lee) wrote in message news:<87fzfuszsq.fsf at pobox.com>... > Maxim Khesin writes: > > > > to know it once existed because I WROTE it. > [...] > > I should just mention that I got hit up for an interview last week due > > to my BrainBench C++ test. So they are not entirely worthless (even > > C++ is one area where a simple test might be useful, though. Python, > much, much less so. > > [...] > > the Python test is worth the $45 they are charging from that > > perspective since I suspect very few potential employers will be > > looking for Python programmers on BrainBench. > > Certainly. > > > John From seberino at spawar.navy.mil Tue Dec 9 19:19:35 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 9 Dec 2003 16:19:35 -0800 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? Message-ID: I know IPython is another interpreter for Python and was wondering what people liked about it and if I should switch to it. If it is so good then why is it not part of the standard Python tarball? Chris From jzgoda at gazeta.usun.pl Fri Dec 19 16:40:20 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Dec 2003 21:40:20 +0000 (UTC) Subject: Parsing environment variables in ConfigParser files References: <3a8e83d2.0312190936.1746d659@posting.google.com> Message-ID: Matthew Barnes pisze: > [section_name] > data_file=${HOME}/mydata.dat Curly braces are so... php'ish... No, I don't like this idea. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From bokr at oz.net Tue Dec 16 21:17:54 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Dec 2003 02:17:54 GMT Subject: why are these exec times so different? References: Message-ID: On Wed, 17 Dec 2003 01:09:06 GMT, "r.e.s." wrote: >Should one expect the following execution times >to be so different? ... > >Module_A takes about 4 seconds to run: >x = (stuff_1) >(stuff_2) > >Module_B takes about 80 seconds to run: >x = (stuff_1) >def f(y): > (stuff_2) >f(x) > >where (stuff_1) and (stuff_2) are respectively >the same in both modules. I understand that >they should differ in execution time, but by a >factor of 20?! > >(I'll supply the actual code if requested, but >I didn't want to clutter things up needlessly. >I'm using PythonWin, win32all build 163.) Timing is tricky, because of all the extra time that can sneak in. So the thing is to make the circumstances for both timings as near equal as possible. Best if you can run them separately in separate executions of python, and do a short loop and get the best time of several. Don't do too many if you have a CPU that gets hot and slows its clock to avoid burning. By the same token, don't do a second test before it's cooled off from the first. Looping should get rid of cache-miss time loss, and hopefully also garbage collection affected loops will be thown out. Usually looping and taking the best will be ok to do in the same program for several tests, but sometimes not. Make sure you are comparing apples and apples too. I.e., if stuff_2 involves copying a huge list or using range instead of xrange etc., it's not a fair comparison. Generally stuff done with local variables inside a function ought to be faster than the same accessing globals. Not to mention all the background stuff that could be going on. Don't be dragging windows around or be playing solitaire or playing music or downloading while testing. Maybe some spy-ware kicked in and called home? ;-) Regards, Bengt Richter From sebb at linuxcult.com Fri Dec 19 23:13:28 2003 From: sebb at linuxcult.com (sebb) Date: 19 Dec 2003 20:13:28 -0800 Subject: What's going on with python.org Message-ID: <56f42e53.0312192013.333cfeef@posting.google.com> Just want to know why python.org is down. From engsolnom at ipns.com Mon Dec 29 17:36:01 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Mon, 29 Dec 2003 14:36:01 -0800 Subject: NEWBIE: ishexdigit revisited Message-ID: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> After looking at the suggestions for a ishexdigit method, (thanks again), I decided on the following, partly because I don't have to import string, and I believe it's pretty readable by Python newbies, which we (including myself) have at work: def ishexdigit(sx): ix = 0 for cx in sx: ix += 1 if not cx in '0123456789abcdefABCDEF': return 0 if ix % 2 == 0: return 1 else: return 'Extra nibble' # Try it out: sx = '0123abcDEF' # 5 bytes print ishexdigit(sx) if ishexdigit(sx): print 'All hex' else: print 'Not hex' sx = 'S123abcDEF' # The 'S' is not hex print ishexdigit(sx) if ishexdigit(sx): print 'All hex' else: print 'Not hex' sx = '123abcDEF' # 4 bytes plus a nibble print ishexdigit(sx) if ishexdigit(sx): print 'All hex' else: print 'Not hex' Results: 1 All hex 0 Not hex Extra nibble All hex Notice that the user is warned (if he/she cares to be), that the string isn't on byte boundries. Norm From mgerrans at mindspring.com Tue Dec 16 02:57:38 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 16 Dec 2003 07:57:38 GMT Subject: More info on my Python problem... References: Message-ID: "JD" wrote: > I want to figure out if this really IS a python bug, but I suspect > that if it hangs up the console, it would be a bug. That's a bit of a leap. I've had plenty of Python programs that did things like that and none of it was because of a bug in Python. After all, it is possible for a module to do any silly thing it wants, entirely out of Python's purview. I think something stupid like range(100000000) is sufficient to get this behavior on some platforms/configurations. Is that a Python bug? > Is there someone who I might contact via phone to walk me through > this? (Assuming I can't get adequate information here? ... Operators are standing by. If you are not completely satisfied, there is 100% money-back guarantee, too. > ... Or does anyone care about Python bugs?) Seriously, asking sardonic questions is probably not the optimal approach to generate an outpouring of sympathy and helpfulness. Anyway, it may come as a shock to you, but there is probably a bit of a chasm between people "caring about Python bugs" and wanting to give you free phone support. You might start by fulfilling the promise of your subject and provide "more info." Such as, what is your Python program doing, what modules is it using, etc. Common sense stuff, as described here: http://www.catb.org/~esr/faqs/smart-questions.html From bmgz at dev.null Tue Dec 16 04:34:19 2003 From: bmgz at dev.null (bmgz) Date: Tue, 16 Dec 2003 11:34:19 +0200 Subject: shutil.move() Error ([Errno 17] File exists:) on win32 Message-ID: <3fded19b.0@news1.mweb.co.za> I am have made a simple script that moves all desktop clutter (ie files that are not *.lnk) to a specified folder eg. c:\myhome\mydocs\desktopdebris\2003-12-16 ---------------------------------------------------------------------------- ----------------- import re, os, time, shutil os.chdir(os.environ['HOMEDRIVE']+os.environ['HOMEPATH']+"\\Desktop") DESKTOP = os.listdir(os.environ['HOMEDRIVE']+os.environ['HOMEPATH']+"\\Desktop") TODAYDIR = "E:\\My Documents\\desktop_debris\\"+time.strftime('%Y-%m-%d') if not os.path.exists(TODAYDIR): os.mkdir(TODAYDIR) for i in range(len(DESKTOP)): if not re.search("\.lnk$", DESKTOP[i]): shutil.move(DESKTOP[i],TODAYDIR) ---------------------------------------------------------------------------- ----------------------- this works fine for FILES on the desktop, but when a FOLDER is present the script exits with the following error: Traceback (most recent call last): File "E:\My Documents\python\cleanup_desktop.py", line 12, in ? shutil.move(DESKTOP[i],TODAYDIR) File "C:\Program Files\Python-2.3\lib\shutil.py", line 167, in move copytree(src, dst, symlinks=True) File "C:\Program Files\Python-2.3\lib\shutil.py", line 101, in copytree os.mkdir(dst) OSError: [Errno 17] File exists: 'E:\\My Documents\\desktop_debris\\2003-12-16' It seems that the shutil.move() function is trying to recreate the target directory? Is their another module one could use in this case? (shutil.copy() then delete() also gives problems - then again that IS move()..) From fBechmann at web.de Mon Dec 29 16:02:05 2003 From: fBechmann at web.de (Frank Bechmann) Date: 29 Dec 2003 13:02:05 -0800 Subject: why does py_compile.compile() miss some errors in sourcefile? References: Message-ID: thanks a lot for this substantial explanation. seems that I have to try much harder to forget my static compiled language experiences :). if I understood you correctly it is not necessary to try to 'py_compile.compile()' a file once I tried to import it under pychecker-control because the import already executed the file, so the import did not only the compile (if necessary) but also the runtime evaluation. From ville.spammehardvainio at spamtut.fi Sat Dec 20 05:55:30 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Dec 2003 12:55:30 +0200 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: Roy Smith writes: > > If the extra features [...] were really > > worthwhile, they would be added to Python > > Down that path lies madness (i.e. Perl). And that's why I trust the judgement in the language developers hands. If Ruby had enough of a "killer" feature that it would result in flow of people from Ruby to Python, it could be added to Python. As a whole, the py developer team seems to have their act together better than Ruby developers, judging by the "taste" and various perlisms in Ruby. The only thing Ruby will forever have over Python (according to the individuals who tend to be of that opinions) is the lack of whitespace block structure. I guess that would be the main reason why various misguided souls choose Ruby over Python ;-). But then again, various people choose Perl, of all things, over Python, so I guess there doesn't need to be a rational explanation for picking a language. -- Ville Vainio http://www.students.tut.fi/~vainio24 From matt at cynetix.co.uk Wed Dec 24 13:29:03 2003 From: matt at cynetix.co.uk (Matt Whiteley) Date: Wed, 24 Dec 2003 18:29:03 -0000 Subject: Using Python to send a DNS update packet Message-ID: Hello all, I want to use Python to send a request to a Microsft DNS server to tell it to update an A record. Ideally, this would be a secure update but primarily, an unsecure one would do. Are there any python modules that will let me do it or is there some code knocking around I could use ? Thanks Matt From adalke at mindspring.com Tue Dec 23 01:53:19 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 23 Dec 2003 06:53:19 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: Francis Avila: > Ruby uses messages to methods (which attached to > objects), and methods themselves are not first-class, so there's no > ambiguity. > http://onestepback.org/index.cgi/Tech/Ruby/PythonAndRuby.rdoc > > I can't understand the syntax in the example code that shows how you'd get a > Method object. I was thinking of how to elaborate on the description on that page, but all I could come up with was basically a restatement. I'll give it a go anyway. In Ruby, the line obj.methname(param1, param2) is the same as "send the message 'methname' with parameters 'param1' and 'param2' to 'obj'" In Python it is the same as "get the method named 'methname' from 'obj' then call it with parameters 'param1' and 'param2'" In Ruby it's a one step process. In Python it's two steps. In Ruby, the line obj.methname is the same as "send the message 'methname' to 'obj'" while in Python it's the same as the single step "get the method named 'methname' from 'obj'" There isn't a method per se in Ruby, but the base object class knows how to convert a message into a function object (a functor) which can then be called. However, there are no functions in Ruby either, only objects which take messages. So "f(1)" does not work (well, it can because "functions" get turned into private methods of the base object) and instead you call functors with the "call" message. Hence, to emulate Python's two-step method invocation (where you get the bound method in the first step then call the functor in the second step) in Ruby you need to do it as m = obj.method(:methname) m.call(param1, param2) where 'method' is a method of the base object type which takes the method name and returns a bound Method object. (Let me try that again. All objects can receive the message 'method', because it's part of Ruby's base object type. The 'method' message comes with the name of the method. It returns a new object which, when sent the 'call' message, forwards that message to the original object but changes the message type from 'call' to the desired message type, which in this case was the name 'methname'. Any better? It really does help if you think of Ruby as sending message and not as getting callables.) > Of course, the typical Ruby accusation against Python is that it (Ruby) is > "purer OO". I don't know what they mean by "purer". It is in part because of Python's old class/type dichotomy. It's also because Python lets you create instances which are not part of any class or instance. For example, Python has functions, like def spam(count): print "Spam " * count These are not part of any object. (Well, perhaps the module object, but it isn't a method of the module type.) Ruby has syntactic sugar to allow "functions" like this, but under the covers it ends up making 'spam' be a private method of the base object class. When you "call" it you really send the message "spam" with the given count value to the base object class. Philosophically then, while you could think of everything in Python as OO it isn't as "pure" as Ruby because we tend to think of modules, instances, attributes, variables, and classes as different things, while Ruby doesn't make that strong of a distinction between them. > A class is an object, the methods of an instantiated class are > objects, the function a method wraps is an objects, the code of the function > is an object.... I think about the only thing that is not an object in > Python is a name, and I can't think how *that* would work. Perhaps this is a good way to think of the difference. Python thinks namespaces are one honking great idea Ruby thinks OO is one honking great idea Python's modules, classes, instances, and locals are all namespaces. They happen to be specific types in a type system which is nearly unified. Ruby's modules, classes, instances, and locals are all instances, each of which defines its own namespace. (NB: I've never coded Ruby only read the docs and followed the newsgroup for a couple of months, so my perception can be wrong, but I suspect it isn't that wrong.) Andrew dalke at dalkescientific.com From python-url at phaseit.net Mon Dec 8 09:05:20 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Mon, 08 Dec 2003 14:05:20 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 8) Message-ID: QOTW: "Have you ever used the copy module? I am *not* a beginner, and have used it *once* (and I can't remember what for, either)." -- Michael Hudson "It will likely take a little practice before this stuff rattles off your fingertips easily." -- Paul Rubin BJ MacNevin wants to run python from a CD. http://groups.google.com/groups?threadm=BhVyb.389117$Tr4.1144562 at attbi_s03 Brian Lloyd asks if there's interest in a Python for .NET sprint at PyCon 04. http://groups.google.com/groups?threadm=mailman.111.1070550982.16879.python-list at python.org Phil releases Kodos 2.1, a PyQT GUI regular expression designer, tester, debugger and validator. http://groups.google.com/groups?selm=mailman.1070757242.26773.clpa-moderators at python.org Keyphrene announces a bug-fix release for Naja 0.9.3, a download manager and a website grabber tool written in Python/wxPython. http://groups.google.com/groups?selm=mailman.1070378103.9000.clpa-moderators at python.org Jeff Wagner asks the seemingly simple question about Lists and Tuples: why choose one over the other? http://groups.google.com/groups?threadm=7x7k1b4yqn.fsf%40ruckus.brouhaha.com Jay Dorsey points us to a site offering funds "to make Python the most widespread common scripting language on the net" http://groups.google.com/groups?threadm=mailman.81.1070486342.16879.python-list at python.org Anthony Baxter on behalf of the Python development team releases Python 2.3.3 (release candidate 1), which fixes a couple of serious bugs related to weakrefs and the cyclic garbage collector along with a number of bugs in the standard library. http://groups.google.com/groups?selm=mailman.139.1070635275.16879.python-list at python.org Skip Montanaro, after a quick pointer from Tim Peters, shows how to exploit readline to save and restore interactive sessions. http://groups.google.com/groups?threadm=mailman.18.1070312780.16879.python-list at python.org Peter Otten is looking for ways to turn a function taking a callback into a generator without having to store all intermediate results first. http://groups.google.com/groups?threadm=bql8pd$32q$06$1 at news.t-online.com luigipaioro asks how to use python to access a web page that needs user and password authentication. http://groups.google.com/groups?threadm=mailman.110.1070548764.16879.python-list at python.org John J. Lee wants to know when a bare except: is justified. http://groups.google.com/groups?threadm=873cbzmbld.fsf%40pobox.com Gerald Senarclens de Grancy is stumped when asked 'Why did Guido create Python?'. http://groups.google.com/groups?threadm=3fce6605$0$248$a3f2974a at nnrp1.numericable.fr Enrique spots differences between python 22 and python 23 that now sometimes require specification of a default encoding to properly deal with strings containing binary data. http://groups.google.com/groups?threadm=mailman.72.1070471712.16879.python-list at python.org Detlev Offenbach releases Eric 3.3, a Python IDE written using PyQt and QScintilla that includes project management capabilities, an unlimited number of editors, a Python shell, an integrated debugger and more. http://groups.google.com/groups?selm=npl8a1-125.ln1 at stargate.solsys.priv Bernhard Herzog releases Thuban 1.0rc1, an interactive geographic data viewer implemented in Python and wxPython which runs on Unix-like systems and MS Windows. http://groups.google.com/groups?selm=mailman.1070462582.366.clpa-moderators at python.org Patrick Useldinger announces dfp 0.1, a suite of components which permit detection and processing of changed files. http://groups.google.com/groups?selm=mailman.1070724602.31055.clpa-moderators at python.org Gerhard Haering releases PySQLite 0.5.0, because lots of bugs were fixed and several sensitive changes were made, which need exposure in real life. http://groups.google.com/groups?selm=mailman.42.1070374169.16879.python-list at python.org John J. Lee releases ClientCookie 0.4.10, a Python module for handling HTTP cookies on the client side. http://groups.google.com/groups?selm=mailman.1070757242.26774.clpa-moderators at python.org Stephen Ferg places a python advocacy article titled "Why your organization needs Python" in the public domain. http://groups.google.com/groups?selm=b16e4ef7.0312070813.4cfc46b8 at posting.google.com Brett Cannon documents "How Python is Developed" in an introductory essay. http://groups.google.com/groups?selm=mailman.1070833381.16370.clpa-moderators at python.org ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From fredrik at pythonware.com Thu Dec 11 11:50:52 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 17:50:52 +0100 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com><7xekvb1koc.fsf@ruckus.brouhaha.com><7x65gn1jk5.fsf@ruckus.brouhaha.com> Message-ID: John Roth wrote: > And that is what is called a "real good question." I believe that > you're supposed to be able to use the Tk libraries without using > TCL, but the people that wrote Tkinter weren't able to make it > work. Tk comes with lots of configuration code and widget bindings implemented in Tcl. Tk also uses many pieces of the Tcl C library. both parts can surely be replaced; someone just has to do it (or pay for it). From nospam at nospam.com Thu Dec 11 10:56:33 2003 From: nospam at nospam.com (Mark) Date: Thu, 11 Dec 2003 15:56:33 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Spiffy" wrote in message news:IHrBb.172631$Ec1.6601048 at bgtnsc05-news.ops.worldnet.att.net... > > "Dennis Lee Bieber" wrote in message > news:ef9ha1-6p3.ln1 at beastie.ix.netcom.com... > > Spiffy fed this fish to the penguins on Tuesday 09 December 2003 00:38 > > am: > > > > > from the "Learning Python" book. When I run it, the dos command line > > > appears with the message 'Bad command or file name". Both the .exe and > > > the .mid file are in the python path and the spelling has been > > > checked. What I expected to happen was that the os.system call would > > > start the .exe and begin playing the .mid file. This does not happen. > > > This is what I meant when I said I haven't been able to get this to > > > work. > > > > > So include (don't retype or paraphrase, use cut&paste) the /exact/ > > code which is failing, AND the exact command window output... > > > > Among other things, I don't think os.system() uses the /Python/ > path > > -- its the equivalent of opening a new command prompt and typing the > > command; so it is the OS search path that is used. > > > > Open a command window, and type the exact command you think you > are > > using in os.system() > > > > -- > > > > In the command window the call to the program with the name of the .mid > file to be played works just fine. Here is what it looks like....exactly: > C:\Python22>playb Canyon.mid > > Here is the code used to call it from Python: > import os > filename = "C:\Python22\Canyon.mid" > os.system("C:\Python22\playb.exe%s"%filename) > ...this causes a dos box to appear which promptly hangs and does nothing, at > which time Python stops responding. Vartiations on this will cause the dos > box to appear with the message "Bad command or file name". > Try: import.os os.system(r"C:\Python22\playb.exe %s"%filename) or: import os os.system("C:\\Python22\\playb.exe %s"%filename) -Mark > > ============================================================== < > > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > > wulfraed at dm.net | Bestiaria Support Staff < > > > ============================================================== < > > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > > Home Page: http://www.dm.net/~wulfraed/ < > > > > From exarkun at intarweb.us Sun Dec 21 19:51:49 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 21 Dec 2003 19:51:49 -0500 Subject: Using weakref with execfile? In-Reply-To: <20031221153943.3a6e4a20.wtrenker@shaw.ca> References: <20031221153943.3a6e4a20.wtrenker@shaw.ca> Message-ID: <20031222005149.GB19462@intarweb.us> On Sun, Dec 21, 2003 at 03:39:43PM +0000, William Trenker wrote: > I'm trying to use a weak reference with execfile, if that even makes sense. The following snippet produces an execption: > > Python 2.3.2 (#1, Oct 27 2003, 10:19:56) > [GCC 2.95.3 20010315 (release)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import weakref > >>> d=weakref.WeakKeyDictionary() > >>> execfile('x.py',d) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: execfile() argument 2 must be dict, not instance > > I've read the weakref docs. I thought maybe the weakref.ref or > weakref.proxy functions might be needed but they also return their own > types which are, of course, not "dict" and so make execfile unhappy. > > Am I doing something wrong with weakref, or is it even possible to use a > weak reference dict with execfile? Even if this worked, the dictionary would be empty when execfile() returned, since nothing would be referencing any of the keys. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From newsgroups at jhrothjr.com Sat Dec 20 07:19:06 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 07:19:06 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Skip Montanaro" wrote in message news:mailman.364.1071886706.9307.python-list at python.org... > > John> The biggest problem is that I think Python is beginning to sucumb > John> to the "we're better so we don't have to try harder" syndrome. One > John> of these days, someone is going to start chewing up the user base, > John> and for a while it looked like Ruby might have been it. > > Can you give some concrete examples which support your contention? I think the discussion on this thread is a reasonably good example [grin]. The responses to my comment about method calls with no arguements should say everything that needs to be said about attitude. Let's skip the fluf and get to the crux. There are four languages (not counting minor entries) in the space Python occupies. In alphabetical order, they are: Perl, Python, Ruby and TCL. The originators of those languages have very different language design philosophies. Larry Wall (Perl): There's more than one way to do it. Guido vanRossum (Python): There should only be one obvious way to do anything significant. Metz (Ruby): I want a language that's both productive and fun to program. John Osterhout (TCL). I want a language I can embed in tools as a common scripting language. Notice that there is only one polarity here: Perl vs Python. Ruby goes meta on the discussion in that it looks at what the customer (the developer) *wants*, rather than what the language designer thinks they should have. And *that* is the crux here. A fairly large number of people I respect have used Python and have migrated to Ruby. For a long time, the basic flow was from Perl to Python, for reasons that we don't need to hash over again. Most businesses would look at a competitor who is stealing customers as an opportunity to figure out what those customers want that they aren't getting. The jihad against the "functional" builtins is a good case in point. The replacements for apply, map and filter seem to be adequate, and in the case of list comprehensions, pretty darned useful although I think that it's a rather baroque addition to an otherwise very clear and comprehensible language. On the other hand, claiming that sum() is an adequate replacement for reduce() is so silly that it borders on the absurd. The only explanation I can come up with for that level of absurdity is a desire to get rid of a feature, regardless of what it looks like. In other words, a jihad (holy war.) There is no replacement for lambda in sight, even though lambda is arguably the ***largest single*** one of the functional constructs that needs work, and has obviously needed work for a long time. The obvious replacement for lambda, which is some form of inline block, has not been seriously discussed, with proposed syntax and examples, anywhere I've seen it. Clearly, I'm not ominiscient, so that doesn't mean it hasn't, though. The PEP 308 mess has left a rather sour taste in a lot of people's mouths: there was a clear majority in favor of doing *something*, but the voting was rigged (although I doubt if it was done deliberately) to make certain that no single proposal would get a majority. > > Skip > From reply.in.the.newsgroup at my.address.is.invalid Sat Dec 6 15:17:09 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 06 Dec 2003 21:17:09 +0100 Subject: Reading pipes in Python References: Message-ID: Jeroen van der Ham: >Rene Pijlman: >>f=open('ff','r') >>while 1: >> li = f.readline() >> if not li: break >> print li, > >This works, but only for a single line. No, it works for multiple lines as well. What you probably mean is: it works only for a single writer process. This is what Linus said about it in 1993: "That's how a fifo is supposed to work as far as I can tell: when all writers have exited, the reader gets an EOF and also exits.." http://groups.google.com/groups?threadm=23vt5j%246ok%40klaava.Helsinki.FI Try 'cat' instead of a Python script and you'll see exactly the same behaviour. -- Ren? Pijlman From python at rcn.com Wed Dec 31 16:16:22 2003 From: python at rcn.com (Raymond Hettinger) Date: 31 Dec 2003 13:16:22 -0800 Subject: ishexdigit() References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <4l05vvs0ril5a2lr35pp52vq98n990jmef@4ax.com> Message-ID: <5d83790c.0312311316.d301edb@posting.google.com> [Tim Roberts] > Well, more Pythonish yet is to avoid the extraneous local variables, > avoid the use of a type as a parameter name, and use as many > little-used builtins as possible: > > def ishexdigit(char): > return char in string.hexdigits > > def ishexstring(strng): > return filter(ishexdigit, strng) == strng [Uwe Schmitt] > better/faster/more pythonic: > > return reduce(lambda a,b: a and ishexdigit(b), strng, True) In the vague category of Most Pythonic, code using "filter", "lambda", and "and" tend to be losers. Straight-forward loops run reasonably fast and are much more clear: def ishexstring(s): for c in s: if c not in '0123456789abcdefABCDEF': return False return True The category of Fastest Code is much less vague but tends towards using fancy tricks: def ishexstring(s): try: int(s, 16) except ValueError: return False return True The category of Cutest Code tends to make creative use of data structures: def ishexstring(s): return not sets.Set(s).difference('0123456789abcdefABCDEF') Raymond Hettinger From tov at eecs.harvREMOVEard.edu Sat Dec 20 21:38:49 2003 From: tov at eecs.harvREMOVEard.edu (Jesse Tov) Date: 21 Dec 2003 02:38:49 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <877k0rgdff.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon : > Even with sed I find difficult to do that. If you want to remove blank lines, then sed '/^$/d' will do. If, on the other hand, you actually want to compress pairs of newlines into single newlines (as I think the specification may have said), something a bit more complicated is required. I think that sed 'N;P;/\n$/d;D' will do it. Jesse From Chris.Barker at noaa.gov Wed Dec 31 16:04:06 2003 From: Chris.Barker at noaa.gov (root) Date: Wed, 31 Dec 2003 13:04:06 -0800 Subject: Rekall Binary In-Reply-To: <8a27e309.0312310529.3c1f43a8@posting.google.com> References: <8a27e309.0312310529.3c1f43a8@posting.google.com> Message-ID: It looks like TotalRekall sells the GPL version for 15 pounds: http://www.totalrekall.co.uk/modules.php?op=modload&name=CCart&id=16 Which seems in keeping with: "...small charge for Rekall binary distributions to cover our costs" By the way, it's still not clear how strong a busness model it is to give away GPL software and expect to make money off services. Have you seen what RedHat is now doing? In any case, I don't think there is anything wrong with charging more than distribution costs for a binary version of GPL'd program. Creating binaries that work on various versions of various platforms and providing a nice installer for them is quite a bit of work. Also, the GPL is about freedom: not cheap software. The idea is that it a good thing for all involved for users to have access to source code. That is very different than providing inexpensive software for folks that can't figure out how to compile something (or can't be bothered). Those folks will not be contirbuting to the p[roject, and will not be using the code in their own projects. That being said, I'm very happy that I can get so much open source software in nicely packaged binary (or easy to compile) form. I only contribute to a VERY SMALL fraction of all the free software I use. -Chris From dman at dman13.dyndns.org Mon Dec 8 23:09:11 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Tue, 09 Dec 2003 04:09:11 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: On Tue, 09 Dec 2003 03:24:48 GMT, Courageous wrote: > >>Why is python incompatible with .net? Why can't python be coded in C#? > > It's not. The .net virtual machine is Turing Complete. Sure, you could create and run a python interpreter on the .NET runtime, but how is that better than running the C implementation? Presumably people who discuss .NET integration are looking for the sort of language-agnostic plug-and-play that .NET promises. This is a different scenario than simply re-implementing python on a new platform. -D -- Contrary to popular belief, Unix is user friendly. It just happens to be selective about who it makes friends with. -- Dave Parnas www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From mwh at python.net Mon Dec 29 09:02:21 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Dec 2003 14:02:21 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: engsolnom at ipns.com writes: > What I'd like to do is display is the instance name. Is it hiding > somewhere? >From http://www.amk.ca/quotations/python-quotes/page-8.html: The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)... ....and don't be surprised if you'll find that it's known by many names, or no name at all! -- Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I get the name of a variable from C++ when I have the PyObject*?" One of my favourite Python quotes... Cheers, mwh -- THEOS: Mad cow. Utterly fucking insane cow, in fact. A cow so mad it thinks it's a tetapot. The swamp dragon of the OS world. -- Jim's pedigree of operating systems, asr From mwood at stpo.com Sun Dec 7 04:55:02 2003 From: mwood at stpo.com (Michael Wood) Date: Sun, 07 Dec 2003 01:55:02 -0800 Subject: Accessing Python script with ColdFusion In-Reply-To: <20031207030732.GA22553@gentoo.Earthlink.net> References: <6.0.0.22.2.20031206145251.052fc5c8@mail.stpo.com> <20031207030732.GA22553@gentoo.Earthlink.net> Message-ID: <6.0.0.22.2.20031207014944.0596e760@mail.stpo.com> I've tried using a timeout of 1 and 3. It didn't make any difference. I also just tried setting the outputFile argument to a file in a folder that I know is accessible to CF. It created an empty file. So no joy there. Mike At 07:07 PM 12/6/2003, you wrote: >On Sat, Dec 06, 2003 at 02:52:59PM -0800, Michael Wood wrote: > > We're using mailman (python based) to do mailing lists. I'd like to > write a > > ColdFusion interface to the command line scripts for managing list > > membership but there's a problem. I can run the scripts from the Linux > > command line with no problem. But when I run the scripts via the CFExecute > > tag in ColdFusion there isn't any output returned. That isn't entirely > > true, if I use the -h argument the help screen displays okay but any other > > sort of output never turns up. And it doesn't return an error so it seems > > as though the script is executing or starts to execute but the output > > buffer never flushes to the standard output or something like that... > > > > I'd really like to make this work. Does anyone have any ideas on how to do > > so? > > > >Have you made sure you specified a timeout in the CFEXECUTE tag? >I just recalled a similar situation I encountered: > >http://lists.evolt.org/archive/Week-of-Mon-20030120/133253.html > >See if that helps any; esp. the use of the CFSAVECONTENT tag. > >I feel silly for not remembering this sooner :) > > > >-- >Jay Dorsey >jay at jaydorsey dot com > >-- >http://mail.python.org/mailman/listinfo/python-list From mwh at python.net Fri Dec 12 10:29:57 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 12 Dec 2003 15:29:57 GMT Subject: Q: Meta-class usage References: Message-ID: google at daishi.fastmail.fm (daishi) writes: > Hi, > > I am wondering if someone could help me understand some of the > details of using metaclasses. > > I am trying to use metaclasses to auto-generate some attributes > and methods in a class definition. I am attaching a simplified > example of the kind of code I am considering below, and I have > the following questions: > > 1. Is the code in NamedType.__new__ the "right" way to have a > class which has NamedType as its metaclass inherit from > NamedClass? Apart from the fact that tuple(list(bases)+[NamedClass]) is a strange way of spelling bases + (NamedClass,), yes. > Are the semantics different from if the class with NamedType as its > metaclass explicitly listed NamedClass as a superclass in the > standard way? Well, potentially, depending on where in the bases list you put NamedClass. In general, it might be wise to not add NamedClass to the bases list unless you need to (to avoid MRO calculation errors). > 2. Is the try/except clause in NameType.__init__ the "right" way to > prevent KeyErrors for subclasses of classes with NamedType as its > metaclass? I'd say so, but I'm not totally sure what you're trying to achieve... Cheers, mwh -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From yaipa at yahoo.com Wed Dec 17 02:07:11 2003 From: yaipa at yahoo.com (yaipa h.) Date: 16 Dec 2003 23:07:11 -0800 Subject: Is anyone using Python for .NET? References: Message-ID: <6e07b825.0312162307.7e2d9306@posting.google.com> > In another year it is possible that Python compiled to IL will be faster > than CPython in most cases. But it is really hard to say. It appears that it already does... http://www.python.org/~jeremy/weblog/031209a.html yaipa.h Brian Quinlan wrote in message news:... > > Is anyone using Python for .NET? I mean Brian's version at Zope, > > I'm using it. > > > Not the experimental ActiveState stuff, which tried to compile IL and > > apparently didn't succeed. > > Microsoft funded it as a proof of concept. The concept was proven. > > > 1) whether to use it for my C++ / C# / .NET / Python (?) game project. > > It's a prototype, so in this context a "mostly working beta" is > > acceptable. > > A lot of important features (like subclassing abstract classes and > implementing interfaces) don't work yet. Whenever that has bitten me, I've > written a simple C# class to help me bridge into Python. > > > I won't need "ready for prime time" for another year yet. > > In another year it is possible that Python compiled to IL will be faster > than CPython in most cases. But it is really hard to say. > > Cheers, > Brian From mfranklin1 at gatwick.westerngeco.slb.com Thu Dec 18 05:06:02 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 18 Dec 2003 10:06:02 +0000 Subject: Using python with SSH? In-Reply-To: <3fe0dfd7$1@clarion.carno.net.au> References: <3fe0dfd7$1@clarion.carno.net.au> Message-ID: <1071741962.1115.26.camel@m-franklin> On Wed, 2003-12-17 at 23:00, Steve wrote: > Hi, > > I need to run a remote program from a server that I have access rights > to. I want to be able to do this from within in my python script and I > want to use ssh (or anything else that will work). However, doing > something like: > > ssh -l user host "/path/to/program" > > prompts for a password and I don't know how to supply one via a python > script. Is there an easy way out? Can I log onto to the other machine > via ssh somehow? Does a python script support this? Thanks! > > Steve Steve, You don't say if you are running on Windows or not but this is a ssh wrapper I use that uses the pexpect library...: import pexpect import sys import re import os PROMPT = "\$|\%|\>" class SSH: def __init__(self, user, password, host): self.child = pexpect.spawn("ssh %s@%s"%(user, host)) i = self.child.expect(['assword:', r"yes/no"], timeout=120) if i==0: self.child.sendline(password) elif i==1: self.child.sendline("yes") self.child.expect("assword:", timeout=120) self.child.sendline(password) self.child.expect(PROMPT) def command(self, command): """send a command and return the response""" self.child.sendline(command) self.child.expect(PROMPT) response = self.child.before return response def close(self): """close the connection""" self.child.close() if __name__=="__main__": import getpass password = getpass.getpass("Password: ") ssh = SSH("RemoteUsername", password, "RemoteHost") print ssh.command("pwd") ssh.close() -- Martin Franklin From bokr at oz.net Sun Dec 14 19:44:48 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Dec 2003 00:44:48 GMT Subject: execl difficulty References: Message-ID: On Mon, 15 Dec 2003 00:18:32 +0100, "Fredrik Lundh" wrote: >"python newbie" wrote: > >> Can anyone tell me why this would cause "Invalid Number of Parameters" while >> trying to compile (or interpret or whatever) >> >> import os >> os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Main >> Web/dp") >> >> Here's what the Python reference says: >> execl(path,arg0, arg1, ...) > >first, fix the slashes. xcopy wants backward slashes in the filenames, >not forward slashes. > >next, fix the number of arguments. at the top of the reference page >you refer to, there's a paragraph explaining how the exec arguments >work: > > The various exec*() functions take a list of arguments for the > new program loaded into the process. In each case, the first > of these arguments is passed to the new program as its own > name rather than as an argument a user may have typed on > a command line. For the C programmer, this is the argv[0] > passed to a program's main(). For example, "os.execv('/bin/echo', > ['foo', 'bar'])" will only print "bar" on standard output; > "foo" will seem to be ignored. > > (from http://www.python.org/doc/current/lib/os-process.html ) > >in other words, you need to pass in the program name twice, to make >sure xcopy sees the filenames as argument 1 and 2. > Hmph, I missed that, in spite of the fact that I execl'd my C++ args printer: Like OP's xcopy execl: >>> os.execl(r'c:\util\pargs.exe', '1', '2', '3') argc = 3 argv[0] = "1" argv[1] = "2" argv[2] = "3" from command line, arg[0] gets inserted: [16:35] C:\pywk\clp>c:\util\pargs.exe 1 2 3 argc = 4 argv[0] = "c:\util\pargs.exe" argv[1] = "1" argv[2] = "2" argv[3] = "3" where [16:58] E:\VCWK\test\t3>type pargs.cpp #include int main(const int argc,const char *argv[]){ printf("argc = %2d\n",argc); for(int i=0;i(are you sure you want os.exec, btw? os.system or os.spawn* might >be a better choice...) Seems like. Regards, Bengt Richter From usenet_spam at janc.invalid Wed Dec 17 01:03:31 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 17 Dec 2003 06:03:31 GMT Subject: Spell checking and Python References: Message-ID: "Gilles Lenfant" schreef: > Any experience or pointer on using a spell checker (aspell, ispell ?) > with a Python app ? Maybe snakespell: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From dwelch91.nospam at comcast.net Wed Dec 24 11:25:03 2003 From: dwelch91.nospam at comcast.net (djw) Date: Wed, 24 Dec 2003 16:25:03 GMT Subject: graphs In-Reply-To: References: Message-ID: km wrote: > Hi all, > > Is there any inbuilt python module which can draw 2-D or 3-D plot to a file (png/jpeg etc) or one which interfaces gnuplot on linux ? > > kindly enlighten, > regards, > KM > Google: python gnuplot http://gnuplot-py.sourceforge.net/ Alos, look at PIL: http://www.pythonware.com/products/pil/ -Don From dw-google.com at botanicus.net Sat Dec 27 06:42:15 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 27 Dec 2003 03:42:15 -0800 Subject: How to determine if an instance of your program is already running? References: Message-ID: <99dce321.0312270342.525b4ea@posting.google.com> Mike wrote... > Can I get a list of currently running processes? There is no portable way of doing it, however if you have a POSIX environment, you can parse the output of ps: def get_process_ids(): output = [] ps = os.popen('ps -o pid,command -C python') ps.readline() for line in ps: bits = line.lstrip()[:-1].split(' ') output.append( (int(bits[0]), ' '.join(bits[1:])) ) return output Don't hold me to this - I tested it on BSD and Linux, and as far as I know both the options I have used are portable. David. From michele.simionato at poste.it Tue Dec 16 02:51:41 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Dec 2003 23:51:41 -0800 Subject: downloading long files Message-ID: <95aa1afa.0312152351.7b6143be@posting.google.com> I have a connection which is not 100% rock solid, so if I try to download a large file (i.e. a Linux ISO image) chances are that the connection will break. Is there a way to check periodically if the connection is open, reopen it if needed, and continue the download without restarting from the beginning? Michele From me at privacy.net Tue Dec 30 16:57:33 2003 From: me at privacy.net (Tobias Pfeiffer) Date: 30 Dec 2003 21:57:33 GMT Subject: Coding an extendable class Message-ID: Hi! I want to write a package of modules that deal with mathematical graphs. So my plan is to have a main.py file where the basic operations are done, like reading the file and creating an adjacence list and all that. In this main.py file, there is created a Graph class with several methods, such as deg(v) or delvertex(v). And then, for all of the other things one can do with a graph, I want to code other modules, e.g. a file euler.py for finding an Euler way through the graph, that extends the class by the method eulerway(). I know that I can do something like # graphtools/euler.py import main class Graph(main.Graph): def eulerway(self): [...] and then the Graph class imported from euler.py will have both the old and the new methods. But what can I do if I want the end user to be able to combine several modules and I don't know in which order he will do? For example, by import graphtools.main, graphtools.hamilton I can do the thingy described above, but what is with something like import graphtools.hamilton, graphtools.euler ? In that case I want the class to have all of the methods defined in the modules. How do I realize that in the best way? Bye Tobias -- please send any mail to botedesschattens(at)web(dot)de From skip at pobox.com Fri Dec 19 12:57:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Dec 2003 11:57:36 -0600 Subject: Parsing environment variables in ConfigParser files In-Reply-To: <3a8e83d2.0312190936.1746d659@posting.google.com> References: <3a8e83d2.0312190936.1746d659@posting.google.com> Message-ID: <16355.15376.165398.692295@montanaro.dyndns.org> Matthew> I'm considering submitting a patch for Python 2.4 to allow Matthew> environment variable expansion in ConfigParser files. data_file=${HOME}/mydata.dat -> data_file=/home/matt/mydata.dat Matthew> The change is pretty straight-forward, but I'm interested in Matthew> feedback on whether this is a good idea, what the syntax for Matthew> environment variable references should look like (currently I'm Matthew> thinking ${varname}), or whether there are any hidden Matthew> complexities or backward-compatibility concerns. There is already a %(foo)s expansion capability in ConfigParser, though the source of key/value pairs is different. I'd check to see if it can be bent (twisted?) to your needs by subclassing ConfigParser and merging a suitably munged os.environ with the user's config file. Using your example, the DEFAULT info would be synthesized or augmented to look like (logically speaking, this might simply be modified to parse os.environ before reading the config file): [DEFAULT] # stuff imported from os.environ HOME=/home/matt USER=matt ... # user's other DEFAULT settings ... and a simple regular expression replace would be performed on the actual config file roughly like so: configf = file("config.ini") configdata = re.sub(r'${([^}]+)}', r'%(\1)s', configf.read()) configf = StringIO.StringIO(configdata) configf.seek(0) Skip From news at grauer-online.de Thu Dec 18 15:51:25 2003 From: news at grauer-online.de (Uwe Grauer) Date: Thu, 18 Dec 2003 21:51:25 +0100 Subject: Standalone client database for Python? In-Reply-To: References: Message-ID: Hi Gustavo, I am using Firebird 1.5 RC7. Very nice and Open Source. see: http://www.firebirdsql.com Uwe Gustavo Campanelli wrote: > What are our options for a standalone (that is one that's not > client/server) easily accesible from Python? > I'm not going to ask for special features as this is only to see what is > avaiable and used (most used most probably meaning well maintained > project). > > Thanks in advance > > Gedece From http Tue Dec 9 15:56:56 2003 From: http (Paul Rubin) Date: 09 Dec 2003 12:56:56 -0800 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> Message-ID: <7xy8tln207.fsf@ruckus.brouhaha.com> Rene Pijlman writes: > >Why not just stick the import statement where you need it? > > Because I need a module from one of a number of different packages, at one > specific point in my code. I still don't understand why you don't want to use an exec statement for this. That's by far the most natural and understandable way to do it. From dtolton at nospam.org Tue Dec 9 16:15:01 2003 From: dtolton at nospam.org (Doug Tolton) Date: Tue, 09 Dec 2003 21:15:01 GMT Subject: File unzipping Message-ID: After searching on Google, the ASPN Cookbook and the Vaults of Parnassus, I was unable to find a solution to simply extract a zipfile. So I wrote one and uploaded it to the ASPN cookbook site. You can find the source here: http://aspn.activestate.com/ASPN/Cookbook/Python Happy extracting. :) -- Doug Tolton (format t "~a@~a~a.~a" "dtolton" "ya" "hoo" "com") From http Tue Dec 16 16:26:16 2003 From: http (Paul Rubin) Date: 16 Dec 2003 13:26:16 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: <7x65gg78uf.fsf@ruckus.brouhaha.com> Charles Steinkuehler writes: > I could be wrong, but it looks to me like SIOD requires a C runtime > library to function. Well, not much of one. > One of the big attractions of using Forth (at least to me) is it's > lack of reliance on a runtime library. Then it has to directly implement the stuff that other systems leave to the libc. > Direct interfacing to the linux kernel should be possible in an > architecture-neutral manner, and the ~10K overhead of a Forth kernel > is very minimal when compared to the ~75K overhead of SIOD (from the > website) I don't think that 75k is program footprint. The program is much smaller than that. However, it uses a copying GC which burns a fair amount of ram. That could be replaced with a mark/sweep GC if you want to use less memory. > the hundreds of KBytes (if not MegaBytes) of overhead for the > runtime C library. There's no need to use such a fancy libc in an embedded system, especially for something like SIOD which needs just a limited subset. The basic C library API is not much different today than it was in the days of V6 Unix on the PDP-11 or BDS C on the Z80. From ramen at lackingtalent.com Fri Dec 5 22:47:51 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 06 Dec 2003 03:47:51 -0000 Subject: Python's simplicity philosophy References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: In article , Douglas Alan wrote: > Lots of languages don't provide reduce() and lots of languages do. Few > provide sum(). Higher-order functions such as reduce() are > problematic in statically typed langauges such as C, C++, or Java, > which may go a long way towards explaining why none of them include > it. Neither C, C++, or Java provide sum() either, though PHP provides > array_sum(). But PHP has a huge number of built-in functions, and I > don't think that Python wishes to go in that direction. Not that this contributes much to either side of this argument, but I just want to mention that PHP *does* have a reduce function: http://www.php.net/array_reduce However, this requires pass-by-name and PHP has no support for closures, so its usefulness is somewhat limited. PHP also has array_map() and array_filter(), which do what you might expect... Ducking out now, Dave =) -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From fredrik at pythonware.com Tue Dec 9 06:43:59 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 12:43:59 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Spiffy" wrote: > > How can I run this other program from a python script and pass the > filename > > as a parameter? > > import os > > filename = "myfile" > os.system("program %s" % filename) > > > > Fredrik, the example you provided is virtually the same as the one from the > "Learning Python" book. that indicates that it's supposed to work, don't you think? > When I run it, the dos command line appears with the message 'Bad command > or file name". that indicates that Windows cannot find the command, don't you think? > Both the .exe and the .mid file are in the python path and the spelling has > been checked. you mean sys.path? that's the problem, most likely. As mentioned in the documentation, os.system() executes the command just as if you've typed it in a "DOS box". Windows doesn't look at the Python path when you do that, so to make sure Windows finds the command, you have to add it to the Windows path (the PATH environment variable), or provide the full path to os.system(). program = r"x:\full\path\to\program" filename = "..." os.system("%s %s" % (program, filename)) the os.path.abspath() function can be useful in cases like this; it makes sure that if your program can find a file, another program can also find it: program = os.path.abspath("x:/somewhere/program") filename = os.path.abspath("somefile") os.system("%s %s" % (program, filename)) (if the filename may contain spaces, you may have to add quotes around the second %s) the relevant manual page contains more information on os.system, and mentions a couple of alternatives (os.startfile, os.spawnlp, etc): ?http://www.python.org/doc/current/lib/os-process.html > Pardon me for being a newbie, but if you don't have an answer, why do you > have to give me attitude? os.system() is still the answer; the problem is in how you used it and what you expected from it, not in the function itself. You cannot expect people to read your mind, and then complain when they fail. From knoppix at laptop.home.net Mon Dec 29 10:34:12 2003 From: knoppix at laptop.home.net (Knoppix User) Date: Mon, 29 Dec 2003 09:34:12 -0600 Subject: Confused Newbie - wxImage vs WxImage pointer References: Message-ID: On Mon, 29 Dec 2003 12:31:42 +0000, Tom wrote: > wxPython is a wrapper around wxWindows. The wxBitmapPtr is a handle to > the C++ object that is the actual object holding the bitmap. > > Badly explained but that's basically it (For wxPython questions you > should try the wxPython mailing list). Thanks, Tom. I'll take wxQuestions to the wxPython list - duh, sorry! Steve From peter at engcorp.com Sun Dec 7 21:43:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Dec 2003 21:43:14 -0500 Subject: Python on web with mod_python References: Message-ID: <3FD3E542.E1629E0B@engcorp.com> Jason Tesser wrote: > > I am thinking about developing a CMS with Python and Postgres. I am developing > on a Linux box with Apache 2. I have used PHP in the past but my at work we are > considering going with Python as our main devellopment language. A few > questions for you guys. > > 1. Is it best to just develop in all Pyhton or to use a mixture of PHP and Python? > Why other than personal feelings? I wouldn't bother with PHP, for several reasons. One is that it's (IMHO) a hodge-podge dog's breakfast of junk that doesn't have real design behind it, another is that Python can do anything it can do, and more readably, and a third is that I like to minimize the number of different technologies used on a given project, to increase maintainability, and to maintain the sanity of developers. > 2. What is the best way to template using Python for me to seperate content > from logic? All the data that will be displayed in dynamic so I am not sure > what the best way to template it would be in Python. http://webware.sourceforge.net/Papers/Templates/ has an overview, and Googling for "python template language" or similar will give you that page and dozens more that will give you a good start. There is no "best way": what is best for you depends on more information than you've provided, and is largely based on personal preference anyway. -Peter From andrew-pythonlist at puzzling.org Fri Dec 5 00:59:57 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 5 Dec 2003 16:59:57 +1100 Subject: Lists and Tuples In-Reply-To: References: Message-ID: <20031205055956.GB452@frobozz> On Fri, Dec 05, 2003 at 05:19:33AM +0000, Jeff Wagner wrote: > I've spent most of the day playing around with lists and tuples to get a really good grasp on what > you can do with them. I am still left with a question and that is, when should you choose a list or > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it > than just that. Everything I tried with a list worked the same with a tuple. So, what's the > difference and why choose one over the other? What's the difference? >>> import sets >>> sets.Set(dir(list)).difference(sets.Set(dir(tuple))) Set(['sort', 'index', '__delslice__', 'reverse', 'extend', 'insert', '__setslice__', 'count', 'remove', '__setitem__', '__iadd__', 'pop', '__delitem__', 'append', '__imul__']) ;) -Andrew. From piir at earthlink.net Sun Dec 7 15:52:31 2003 From: piir at earthlink.net (Todd Gardner) Date: 7 Dec 2003 12:52:31 -0800 Subject: How to graph two columns of x,y numbers? Message-ID: <9b849915.0312071252.6af171db@posting.google.com> I would like to graph two columns of x,y numbers? I would greatly appreciate any pointers or suggestions. Thank you, Todd From boris.boutillier at arteris.net Fri Dec 12 11:53:55 2003 From: boris.boutillier at arteris.net (Boris Boutillier) Date: Fri, 12 Dec 2003 17:53:55 +0100 Subject: Compiling a CPython library on Mac OSX References: Message-ID: On Fri, 12 Dec 2003 17:50:46 +0100, Just wrote: > In article , > "Boris Boutillier" wrote: > >> I'm trying to make a port of a python library written in C to Mac OsX, >> is there some documentation to help in the process ? I m having trouble >> with the creation of the shared library, and I'm not sure this is the way >> it should be done. > > Does it come with a setup.py file? In that case: just follow the regular > instructions. Make sure you have the Apple developer tools installed. > No at the moment this is not the case, this a personal extension I wrote and I didn't made it a distutil extensions. Boris From mshapiro at sunlitsurf.com Thu Dec 18 19:40:09 2003 From: mshapiro at sunlitsurf.com (Marc Shapiro) Date: Thu, 18 Dec 2003 19:40:09 -0500 Subject: Calling a function in __main__ from a module? References: <873cbihqz9.fsf@pobox.com> Message-ID: On 18 Dec 2003 19:21:14 +0000, John J. Lee wrote: > Marc Shapiro writes: > [...] >> Traceback (most recent call last): >> File "./hp", line 62, in ? >> curses.wrapper(main) >> File "/usr/lib/python2.3/curses/wrapper.py", line 44, in wrapper >> res = func(stdscr, *rest) >> File "./hp", line 58, in main >> mb.mainloop(items) >> File "/home/mns/menu.py", line 258, in mainloop >> exec cmd + "('" + name + "')" >> File "", line 1, in ? >> NameError: name 'NOP' is not defined >> >> 'NOP' is the name of the function that I am trying to call. It does >> not exist in the menu module, but is in the calling (hp) module. I >> can't qualify the name (i.e. __main__.NOP() ) since __main__ can not >> be used for qualification, only called module names can be used that >> way. >> >> How do I get the module to call functions in a parent module. Tkinter >> would set up a callback function and bind it to an event. Can >> something similar be done for a console program using curses? > > Stop thinking about 'the parent module'. The question of *which* > module wants to get at a particular function is irrelevant. Think > like this instead: you have a bunch of modules, which any piece of > Python code is free to import stuff from, and you have a main program > which can be a module or not as you choose (if it's on sys.path, it's > a module, if it's not, it ain't; if it *is* a module, you'll also have > an if __name__ == "__main__" to prevent the program startup code > getting executed at times other than program startup). > > So, you want to get at your NOP function. Two obvious choices: > > 1. import it > > 2. pass it as a function argument > > If 1, just make sure the file you want to import it from is on > sys.path (or in a package that's on sys.path; a package is a directory > on sys.path that contains an __init__.py file). You can always just > grab your program startup code (say, main()), and stick it in a tiny > executable file somewhere convenient like ~/bin, and move any other > code that was originally in the same file into a module. > > BTW, I have never yet used exec or eval, and I've written a fair > amount (tens of thousands of lines) of Python code. Whatever you > think you need them for, you probably don't. > > > John I was just about to post back that I had solved the problem. As it turns out, I used method 2. I passed a function argument in place of a string with the function name. Thanks to Python being an untyped language this required only a few minor changes in the module and it is now working as expected. My planned next step was, indeed, to see if I could rewrite so as to avoid using 'exec'. It can certainly be confusing to determine what is being evaluated by which sections of code and at what time. I am sure that when it comes to maintaining this at a later date that it will be a much easier task if I can get rid of the 'exec' lines. -- Marc Shapiro -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From rob02omni at vodafone.it Fri Dec 19 06:05:31 2003 From: rob02omni at vodafone.it (Roberto) Date: Fri, 19 Dec 2003 12:05:31 +0100 Subject: Lanching application References: <%F6Eb.10980$Bl7.7345@news.cpqcorp.net> Message-ID: I've tried win32api.WinExec but it seems to lanch application as single session. What i'm trying to do is lanch multiple session of a program that natively runs only in single session (i know that is possible). Any idea about this? Thanks, Rob From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Dec 1 15:06:52 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 01 Dec 2003 21:06:52 +0100 Subject: PySqlite client_encoding, stores fine but queries don't return unicode Message-ID: <3fcb9f5c$0$1492$e4fe514c@news.xs4all.nl> Hello I'm having some troubles with PySqlite (0.4.3, windows/linux). I want to store unicode strings in the database. So I open a connection with the client_encoding="UTF-8" parameter. When I store a unicode string in a table, it seems to work fine. (a sqlite .dump shows that it encoded the unicode string to UTF-8). But the problem is that a *query* from the same table, doesn't return the string contents as a unicode string! Rather, it returns a normal string that still contains the UTF-8 encoded bytes... Is there any way to make pysqlite decode the UTF-8 strings and return unicode strings automatically ? Thanks! -Irmen de Jong From robin at jessikat.fsnet.co.uk Sun Dec 21 18:31:01 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 21 Dec 2003 23:31:01 +0000 Subject: How do I really delete an imported module? References: Message-ID: ....well you have to delete all references to the module before it goes away. There are references to re in other library modules, but I suspect that most of re is in an extension (or built in). I believe that extension modules are not normally unloaded. Even so, for a python module, I think it depends on the OS whether you'll see a decrease in vmem (and perhaps the allocation/deallocation order). -- Robin Becker From hokiegal99 at hotmail.com Tue Dec 30 09:20:42 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 30 Dec 2003 09:20:42 -0500 Subject: HDD Burn In with Python In-Reply-To: <3ff15d8a$0$318$e4fe514c@news.xs4all.nl> References: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> <84fc4588.0312300019.41a81615@posting.google.com> <3ff15d8a$0$318$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Just letting your harddisk work hard for a long time doesn't > require optimized C code. Python is perfectly suitable for that. Yes, I agree! Now, if I only knew how to conduct a proper stress test. Read, write, verify reads & writes... would that be sufficient? > > The only problem is, that for a true harddisk stress test, you > will want to access sectors all over the disk. I'm not aware of > any mechanism to do that with portable Python... > (although you could format the disk in one huge partition and > then write random files to it until the disk is full). > That's an idea. But what approach might one take if there were already files and folders on the volume that should not be destroyed? Some type of non-destructive test? From mertz at gnosis.cx Thu Dec 4 11:59:07 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 04 Dec 2003 11:59:07 -0500 Subject: Ques From CS Grad Student References: Message-ID: Anthony Baxter wrote previously: |Anthony Baxter: 2.1.2, 2.1.3, 2.3.1, 2.3.2. |Barry Warsaw: 2.2(?) 2.3(?) 2.2.3. |Guido van Rossum: many, including 2.2.2. |Michael Hudson: 2.2.1. |Thomas Wouters: 2.1.1. |Moshe Zadka: 2.0.1. |The only other names I can think of that might have done a (major) |release would be Jeremy, Tim or Fred. Actually, if you count the people who do ports--like Andrew MacIntyre who helps me greatly by maintaining the OS/2 version--the number probably goes up quite a bit. Even though the version numbers are the same, a certain degree of new programming and packaging is required to release a port to a "minor" platform. Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Iran nuclear neocon POTUS patriot Pakistan weaponized uranium invasion UN smallpox Gitmo Castro Tikrit armed revolution Carnivore al-Qaeda sarin ---[ Gnosis Software ("We know stuff") ]--------------- From detlev at die-offenbachs.de Sat Dec 6 04:57:50 2003 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 06 Dec 2003 10:57:50 +0100 Subject: ANN: Eric 3.3 released Message-ID: Hi, I am pround to announce, that eric3 3.3 has been released today. It is available via http://www.die-offenbachs.de/detlev/eric3.html This version includes an interface to omniORB, scripting capabilities, a refactoring browser (the well known Bicycle Repair Man), remapable keyboard actions and a Russian translation. The editor supports split views, keyboard macros, bookmarks and additional breakpoint types. In addition to these new features there are a bunch of changes under the hood, that should increase eric3's usability. For details see the history file in the distribution. What is it? ----------- Eric 3.3 (or short eric3) is a Python IDE written using PyQt and QScintilla. It has integrated project management capabilities, it gives you an unlimited number of editors, an integrated Python shell, an integrated debugger and much more. Please see for yourself by visiting the a.m. page (it contains a picture of Eric our mascot as well). Please report bugs, feature wishes or code contributions to eric-bugs at die-offenbachs.de Help wanted!! ------------- I really need some support in the area of more translations and user documentation. Any volunteers out there? Just let me know. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From hokiegal99 at hotmail.com Sun Dec 14 10:06:14 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 14 Dec 2003 07:06:14 -0800 Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: <93f5c5e9.0312140706.312a3ab1@posting.google.com> "Georgy Pruss" wrote in message news:... > "hokiegal99" wrote in message news:3FDBC1B8.4010205 at hotmail.com... > | s = string.find(fname, '.mp3') > | if s >=1: > > I would say: if fname.lower().endswith( '.mp3' ): Why the '.lower()' part? Wouldn't if fname.endswith('.mp3'): work just as well, or am I missing something here? From andrew-pythonlist at puzzling.org Mon Dec 15 22:04:10 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 16 Dec 2003 14:04:10 +1100 Subject: Jumping around when assigning elements In-Reply-To: <1e963607.0312151857.186adaa8@posting.google.com> References: <1e963607.0312151408.583221e6@posting.google.com> <1e963607.0312151857.186adaa8@posting.google.com> Message-ID: <20031216030410.GA5903@frobozz> On Mon, Dec 15, 2003 at 06:57:19PM -0800, Matthew Sims wrote: [...] > > So far the only way I could get this to work in Python was to insert > "" to represent an empty slot. But Python counts "" when I want to see > how many tapes are currently taking up slots "len(SLOTS)". It would > always show 40. So I now know that I need to write code to tell Python > not to count "". Not too difficult. > > I guess I'm realizing how I need to approach Python as my first OO. > I'm re-writing the script as sort of a training. The program works > flawlessly in Perl, I'm just doing it to learn. So far it has taken > less lines of code in Python to perform the same tasks in Perl...up > til this point. ;) It sounds like your problem isn't OO, but the wrong choice of datastructure. As someone else in this thread has already said, you want a dictionary (known as a 'hash' in perl), not a list. Among other things, len(some_dict) will give you the result you expect. -Andrew. From spamelope.5.djaquay at spamgourmet.com Thu Dec 4 10:12:13 2003 From: spamelope.5.djaquay at spamgourmet.com (David Jaquay) Date: 4 Dec 2003 07:12:13 -0800 Subject: Unit Testing Examples References: Message-ID: <9bd30b65.0312040712.79a54979@posting.google.com> tom_verbeure at hotmail.com (Tom Verbeure) wrote in message news:... > Thanks all for your suggestions! > > Tom Sorry to be late to get to this thread, but I have a Python O/S project at sourceforge.net/projects/d-rose that strives to have complete unit testing, and is a simulation that uses/is-based-on a graph/network. Hope this is of some help to you as an example, and feel free to ask if you have any questions. I certainly won't claim that mine is the best example of such, as I'm just learning TDD, too, but... Dave From mjackson at alumni.caltech.edu Sun Dec 7 21:05:37 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 8 Dec 2003 02:05:37 GMT Subject: Case sensitive and ludicrous statements References: Message-ID: "Robert Brewer" writes: > Douglas Alan wrote: > > IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopl > > eWouldWriteLike > > ThisAllTheTime. > > The Greeks did that quite often. Some ideas take time. [.sig from February 1993] Re. CamelCase and SmallTalk: ISTR that the Alto keyboard lacked an underscore character (I believe the character code was used for left-arrow, which I vaguely recall was used for assignment in BCPL and/or Mesa). As constructions like foo_bar are the obvious alternative to FooBar, could this lack have been a factor at PARC? -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Consistently separating words by spaces became a general custom about the tenth century A.D., and lasted until about 1957, when FORTRAN abandoned the practice. - Sun FORTRAN Reference Manual From __peter__ at web.de Tue Dec 2 08:09:54 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Dec 2003 14:09:54 +0100 Subject: un-tuple (newbie) References: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> Message-ID: Martin Doering wrote: > I could find out, how to create a tuple with just one member, but I > can not find out how to get a value from a tuple with just one member. >>> tpl = "first item", >>> tpl ('first item',) >>> tpl[0] 'first item' You already got the above solution. Here is another one: >>> item, = tpl >>> item 'first item' >>> The trailing comma looks strange, but works on both sides of '='. Packing/unpacking of tuples is remarkably flexible: >>> tpl = (1, 2, ("3a", "3b")) >>> (one, two, (threeA, threeB)) = tpl >>> one 1 >>> threeB '3b' It works even with function arguments: >>> def f(a, (b, c)): ... print a, b, c ... >>> f(1, (2, 3)) 1 2 3 >>> Peter From edreamleo at charter.net Fri Dec 12 10:28:10 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 12 Dec 2003 09:28:10 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> <3FD9D38F.C85433C9@engcorp.com> Message-ID: > Please don't let one person's experience spoil you on the idea of > at least investigating wxPython for your own use. Actually, I think we are in "virulent agreement". I have never suggested writing off wxWindows/wxPython, as Leo's wxPython plugin shows. I merely suggest due caution. My experience isn't that wxWindows doesn't work at all, it is that it takes a lot more work to make wxWindows work as I expect than with, say, Tkinter. It's a cost/risk issue. I should have made that clearer. wxPython reduces that cost difference substantially, and Python provides ways of end-running problems that didn't exist when I was using C++. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From surffirst at yahoo.com Tue Dec 23 07:13:54 2003 From: surffirst at yahoo.com (Leo Yee) Date: Tue, 23 Dec 2003 20:13:54 +0800 Subject: global and None References: Message-ID: Thanks a lot. Now I think 'global' is just a namespace and how to use it. Leo Yee "Leo Yee" ???????? news:bs8pvr$k7m$1 at sea.gmane.org... > Hi, > > I was confused by the global statement and None. > Consider the following code: > > --- code begin --- > > global g > g=None > def foo(): > if g==None: > g=0 > foo() > > --- code end --- > > My purpose is to init g. This is very useful when we cannot construct a > global variable. > But what I got was: > UnboundLocalError: local variable 'g' referenced before assignment > > So I try to solve the problem in this way: > --- code begin --- > > global g > g=None > def foo(): > global g > if g==None: > g=0 > foo() > > --- code end --- > > And it works but the python documentation told me the following: > "Names listed in a global statement must not be defined as formal parameters > or in a for loop control target, class definition, function definition, or > import statement. " > > Does anyone know what I should do to solve this problem? Thanks in advance. > > Leo Yee > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From eugine_kosenko at ukr.net Tue Dec 2 13:35:46 2003 From: eugine_kosenko at ukr.net (=?iso-2022-jp?b?GyRCJyYnUydUJ1YnXydaJ1sbKEIgGyRCJywnYCdjJ1YnXydcJ2AbKEI=?=) Date: Tue, 2 Dec 2003 20:35:46 +0200 Subject: Unicode output to file In-Reply-To: <20031201103923.1E9F.FIRI_MU@fjcl.fujitsu.com> References: <200312010129.21021.eugine_kosenko@ukr.net> <20031201103923.1E9F.FIRI_MU@fjcl.fujitsu.com> Message-ID: <200312022035.46864.eugine_kosenko@ukr.net> ? ????????? ?? 1 ??????? 2003 03:43 Philippe Mougin ???????(a): > #!/usr/bin/python > # -*- coding: cp855 -*- Big thanks for the help. However, this is not the core of the problem. Really, it is enough to use only the second line (my previous failures were due to my misunderstanding of the line syntax). The solution removes the deprecated message, but the problem is remaining: Traceback (most recent call last): File "xp.py", line 9, in ? f.write(u"??????") UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) Note, it seems Python tempts to recode the unicode string in a 8-bit character string, and fails because the characters are outside of the lowest part of the unicode table. First note: what is the problem to convert the characters, if all of them belong to the same codepage (btw, I use cp1251)? Second note: I merely need to save the string in the native utf8 format. I DON'T need to convert it in any format. If I would want that, I will not use unicode at all, it is enough to use native 8-bit format. The main question is "How to switch off the recoding?" Well, I've tried to use utf-8 in the suggested metacomment: # -*- coding: utf-8 -*- f = file(u"content.new", u"wb") print f.encoding f.write(u"??????") The result is UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data Where is the problem now and how to remove it? From ramen at lackingtalent.com Wed Dec 24 03:26:50 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 24 Dec 2003 08:26:50 -0000 Subject: dynamic typing questions References: <2m6hb1-u24.ln1@beastie.ix.netcom.com> Message-ID: In article <2m6hb1-u24.ln1 at beastie.ix.netcom.com>, Dennis Lee Bieber wrote: > Daniel Klein fed this fish to the penguins on Saturday 20 December 2003 > 20:51 pm: > >> If you believe that dynamic typing is a mistake then I have a bridge >> in London to sell you. ;-) >> > London Bridge has already been sold -- as I recall, it was marked, > dismantled, and shipped to some place in the south west US for > reassembly. Lake Havasu City, Arizona. ;) Dave Phoenix, AZ -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From piir at earthlink.net Mon Dec 8 01:30:23 2003 From: piir at earthlink.net (Todd Gardner) Date: 7 Dec 2003 22:30:23 -0800 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> Message-ID: <9b849915.0312072230.5cab87b0@posting.google.com> Peter Hansen wrote in message news:<3FD3E423.B53D23DE at engcorp.com>... > Todd Gardner wrote: > > > > I would like to graph two columns of x,y numbers? I would greatly > > appreciate any pointers or suggestions. > > Yes, include more detail about what you want to do. Specifically, > what platform, do you care if it's wxPython, or Tkinter, or something > else, etc. There are about a zillion possible answers to your > question as it stands, and "python graphing" or something on Google > would likely get you a lot of mileage right now. Maybe after you > do a little research there you can come back with a more detailed > question? > > -Peter There are LOTS of plotting choices on google. I guess I would like to narrow them down by tapping into some expertise. I would like to do 2D and possibly 3D plotting with python. I am tending toward wxpython because of it's ease of use. Any suggestions? Thanks in advance. Todd From ramen at lackingtalent.com Tue Dec 2 01:42:50 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 02 Dec 2003 06:42:50 -0000 Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: In article , Bengt Richter wrote: > On Mon, 01 Dec 2003 10:11:16 GMT, "Raymond Hettinger" wrote: > >>[Peter Otten] >>> > extract[1] >>> > extract["key"] >> >>[Robert Brewer] >>> I'm having a hard time seeing the use cases, given that I find >>> most of them more readable if done with list comprehensions >>> or good ol' for loops. >> >>Peter's post focused on implementation instead of the context. >> >>For Py2.4, the list.sort() will have an optional key argument that encapsulates >>the decorate/sort/undercorate pattern. For example, here is the new fastest way >>to have a case insensitive sort leaving the original case intact: >> >>>>> words = 'The quick BROWN fox JumPed OVER the LAzy dog'.split() >>>>> words.sort(key=str.lower) > Please can we have a name that better expresses the functionality? > > E.g., 'keyfunc', or 'xform' or something that says the method is expecting > a function that will be called with the sorting argument to produce the value > used in sorting? "key=" doesn't do it IMO. I agree. To me, the word "key" has deep meaning with respect to hash tables and databases, and reading it as a parameter makes me first think it might require a string or integer. I would prefer something like "sortfunc" or "decorator", but both of your suggestions would be fine by me and preferable to "key". -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From imbosol at aerojockey.invalid Fri Dec 19 20:43:00 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 01:43:00 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > > Carl Banks writes: >> Consider something like this: >> >> def func(param=((1,2),(3,4),(5,6),(7,8))): >> whatever >> >> Do you really want to be building a big-ass nested tuple every time >> the function is called? > > Come on, the compiler can easily recognize that that list is constant. Yes, but that doesn't account for all expensive parameters. What about this: DEFAULT_LIST = ((1,2),(3,4),(5,6),(7,8)) def func(param=DEFAULT_LIST): pass Or this: import external_module def func(param=external_modules.create_constant_object()): pass Or how about this: def func(param={'1': 'A', '2': 'B', '3': 'C', '4': 'D'}): pass The compiler couldn't optimize any of the above cases. >> Python evaluates default args at time of definition mostly for >> performance reasons (and maybe so we could simulate closures before we >> had real closures). My gut feeling is, moving the evaluation to call >> time would be too much of a performance hit to justify it. > > Python takes so many other performance hits for the sake of > convenience and/or clarity that this particular one would be miniscule > by comparison. Well, I don't have any data, but my gut feeling is this would be somewhat more than "miniscule" performance hit. Seeing how pervasive default arguments are, I'm guessing it would be a very significant slowdown if default arguments had to be evaluated every call. But since I have no numbers, I won't say anything more about it. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From JTesser at nbbc.edu Mon Dec 8 08:12:31 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Mon, 8 Dec 2003 07:12:31 -0600 Subject: Python on web with mod_python Message-ID: <04875CB4331F0240A0AD66F970978651011376F8@paul> Hi >>I am thinking about developing a CMS with Python and Postgres. >Look at Plone http://www.plone.org. It is ready to use, powerfull CMS >system based on Zope http://www.zope.org I want to stay away from a prebuilt framework right now. I am looking into mod_python. From list-python at ccraig.org Tue Dec 30 09:12:16 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 30 Dec 2003 09:12:16 -0500 Subject: Programming language from python References: <8fk2vvg18hgvocrmm09b86epekpdnuc02t@4ax.com> Message-ID: Rene Pijlman writes: > >If it isn?t could you please tell me the name of the best computer > >programming language development tool > > Eiffel. > http://docs.eiffel.com/general/guided_tour/language/invitation-00.html > Most people I know these days say either SML or ANTLR. That said, developing a programming language is an extremely difficult task and the OP should be advised that he should perhaps start with books (such as Aho, Sethi, and Ullman's Red Dragon book [1]) instead of with tools. 1) http://www.amazon.com/exec/obidos/tg/detail/-/0201100886/102-9516987-5143361?v=glance -- Christopher A. Craig Courage atrophies from lack of use From bgporter at acm.org Thu Dec 18 10:00:05 2003 From: bgporter at acm.org (Brett g Porter) Date: Thu, 18 Dec 2003 10:00:05 -0500 Subject: Searching docs (was Re: Logging) In-Reply-To: References: Message-ID: Pieter Claerhout wrote: > You can search through the docs on: > http://web.pydoc.org/ You can also torque up pydoc as a local http server by starting it with the command line python pydoc.py -p ...then point your browser to http://localhost: Running pydoc locally has the advantage that it also lets you poke through all the python modules and packages that are on your system. It has the other advantage that it encourages you (well, me, anyway) to write better docstrings... The disadvantage is that it doesn't offer a search facility. Perhaps some combination of pydoc and LuPy wouldn't be too hard to make happen... From imbosol at aerojockey.invalid Thu Dec 18 06:26:49 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 18 Dec 2003 11:26:49 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: Stian S?iland wrote: > > > * J.R. spake thusly: >> > def f(d=[]): >> > d.append(0) >> > print d >> > f() >> > f() >> > Explain results. When is d bound? > > When is this issue going to be resolved? Enough newbie-pythoners have > made this mistake now. > > Why not evaluate the parameter lists at calltime instead of definition > time? This should work the same way as lambdas. Consider something like this: def func(param=((1,2),(3,4),(5,6),(7,8))): whatever Do you really want to be building a big-ass nested tuple every time the function is called? Python evaluates default args at time of definition mostly for performance reasons (and maybe so we could simulate closures before we had real closures). My gut feeling is, moving the evaluation to call time would be too much of a performance hit to justify it. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From r.s at XXmindspring.com Thu Dec 11 16:45:05 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Thu, 11 Dec 2003 21:45:05 GMT Subject: optimization pointers? Message-ID: Would anyone care to offer pointers on how the following code might be optimized? Or alternatives? ... --- def lz(string): """ Return the Lempel-Ziv complexity (LZ78) of string. """ vocabulary = [] word = '' for char in string: word += char if word not in vocabulary: vocabulary.append(word) word = '' return len(vocabulary) --- On my 2 GHz system running PythonWin, the above code averages about 1.3 hrs to process a 1 MB string. I'd hoped to compute LZ78 for multi-GB files, but it seems infeasible. (?) Thanks for any feedback. -- r.e.s. From rob02omni at vodafone.it Fri Dec 19 04:30:15 2003 From: rob02omni at vodafone.it (Roberto) Date: Fri, 19 Dec 2003 10:30:15 +0100 Subject: Lanching application References: <%F6Eb.10980$Bl7.7345@news.cpqcorp.net> Message-ID: Thanks for the reply i will try to see if i can start multiple session with win32api.WinExec(). Bye, Rob From dpryde+usenet at cis.strath.ac.uk Mon Dec 8 12:18:16 2003 From: dpryde+usenet at cis.strath.ac.uk (Daniel Pryde) Date: Mon, 08 Dec 2003 17:18:16 +0000 Subject: Class problem Message-ID: <3fd4b254$1@nntphost.cis.strath.ac.uk> Hello. I'm currently trying to create my first class in python, but I've ran into a bit of a problem which I fear may just be a simple error. I created a class called ImagePyramid.py which currently only contains an _init_ method which takes in 2 parameters and performs a bunch of things using these parameters. I believe I've followed the tutorial correctly, but when I import it and try to make an instance of it, it returns with the error that 'module' is not callable. I'm kind of new to this language so I believe that it's most likely a simple error on my behalf. Any advice on what I may be doing wrong would be greatly appreciated. Daniel From http Sat Dec 13 17:39:56 2003 From: http (Paul Rubin) Date: 13 Dec 2003 14:39:56 -0800 Subject: ANN: lunatic-python 0.1 References: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> Message-ID: <7xad5wgx4z.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > Accessing above with default IE6 brings up Untrusted Certificate > page. With choices Proceed, Stop, AddCertificate (to root table). > It seems conectiva issued itself its own certificate. I hope this > is just silliness rather than a devious attempt to get people to > accept its self-certification, which I was not about to do. There's no way to turn off that dialog in IE except by using a cert from a recognized CA, which usually costs money. Using a self-signed cert gives you a private communications channel (unless the DNS is hijacked by an active attacker) even though it doesn't provide authentication. Lots of people use self-signed certs instead of paying for commercial certs. From duncan at NOSPAMrcp.co.uk Mon Dec 1 07:44:33 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 1 Dec 2003 12:44:33 +0000 (UTC) Subject: How to delete this file ??? References: Message-ID: Gerrit Holl wrote in news:mailman.1216.1070278795.702.python-list at python.org: > DCK wrote: >> I've path to file, which look like this: >> \\COMPUTER\D$\C++\FILE_TO_DELETE.JPG > > What do you mean exactly by: 'looks like'? Is it the full path to the > file? How did you find out? > >> This path was generated by os.path.walk() function. When i try to >> delete this file, os.remove() can't find it, os.path.fileexists() >> can't find it :( > > Does the directory exist, e.g., what does > 'os.path.exists('\\computer\d$\c++') give as result? And > 'os.path.exists('\\computer\d$')? I think a 'd$' is usually a share in > Windows (not sure), maybe you haven't turned the share on (I'm not > sure what 'mounting' is called in Windows)? You need some raw string quoting there. os.path.exists(r'\\computer\d$\c++') would check for the existence of a directory c++ on drive D of the computer named 'computer', provided you have administrative access to the remote computer. The drive letter shares c$ (and d$ etc. where there is more than one drive) are created automatically and are only accessible to administrators. The UNC pathnames being used mean that there is no need to mount the drive before accessing it. os.path.exists(r'\\computer\d$') will return False whether or not the share exists, however os.path.exists(r'\\computer\d$\\') will return True if the share exists. Note that you need two trailing backslashes even if you don't use the raw quoting. I tried creating a file called FILE_TO_DELETE.JPG in a directory called C++ on a remote machine. I checked the existence of both the file and directory using os.path.exists, and then removed first the file and then the directory using os.remove. Both operations worked as expected, so the '+' character in the filename is not a problem (Python 2.3). I suspect the OP must have something else wrong, possibly a confusion over backslashes, or possibly just insufficient access to the C++ directory (just because you have access to the admin shares doesn't mean you necessarily have full access to all the directories). -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From jzgoda at gazeta.usun.pl Fri Dec 12 17:00:07 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 12 Dec 2003 22:00:07 +0000 (UTC) Subject: Problem with frozen app: compatibility between Unixware and SCO Unix References: <83846327.0312121348.f50f468@posting.google.com> Message-ID: Mike Kent pisze: > What additional information would you like to read? Why you still work with this piece of shit? BP, NMSP ("I'm Sorry, I Couldn't Resist") -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From bokr at oz.net Thu Dec 18 03:39:31 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Dec 2003 08:39:31 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: On Wed, 17 Dec 2003 06:20:54 +0000 (UTC), stain at stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) wrote: >* J.R. spake thusly: >> > def f(d=[]): >> > d.append(0) >> > print d >> > f() >> > f() >> > Explain results. When is d bound? > >When is this issue going to be resolved? Enough newbie-pythoners have >made this mistake now. It works as designed. The default parameter value bindings are made a def time. If you want to do them at call time, the idiom is def f(d=None): if d is None: d = [] d.append(0) print d > >Why not evaluate the parameter lists at calltime instead of definition >time? This should work the same way as lambdas. Lambdas do work the same as defs, except for the automatic name binding and the limitation to an expression as the body. > >>>> f = lambda: [] >>>> a=f() >>>> b=f() >>>> a.append(1) >>>> print a, b >[1] [] The comparable def code to your lambda would be def f(): return [] The above is misguiding attention away from your point, IMO. >Maybe this could be defined in a similar way to remind of the >"lazy-evaluation": > >def getvalue(cls): > return "OK" > >class SomeClass: > def blapp(something: getvalue(), other: []): > print something, other > This might be an interesting concise spelling to accomplish what the following does: (BTW, you need a self for normal methods) >>> class Defer(object): ... def __init__(self, fun): self.fun = fun ... >>> class SomeClass(object): ... def blapp(self, something=Defer(lambda: getvalue()), other=Defer(lambda:[])): ... if isinstance(something, Defer): something = something.fun() ... if isinstance(other, Defer): other = other.fun() ... print something, other ... >>> def getvalue(): return 'gotten_value' ... >>> sc = SomeClass() >>> sc.blapp() gotten_value [] >>> sc.blapp(1) 1 [] >>> sc.blapp('one', 'two') one two >This way, the lambda forms defined after 'something' and 'other' are >evaluated each time the function is called without supplying those >parameters. > >The lambda forms could be evaluated as if within the class-block, and >therefore they might actually use other values defined within that >namespace. However, this might again confuse users, as subclassed >attributes and instance attributes would not be resolved that way. Yes, messy. ISTM better to let them be defined in the same scope as the def, as in my example above. > >(Note that default-parameters-lambdas by today does NOT resolve this way: > >>>> class Blapp: >... ting = 15 >... def fix(self, per=lambda: ting): >... print per() >... >>>> a = Blapp() >>>> a.fix() >Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in fix > File "", line 3, in > NameError: global name 'ting' is not defined Right, though you could get the functionality if you wanted to. > > > >Finally, things could also be done like this, to avoid confusion to all >those new folks (our main goal): If they're confused because their preconceptions are filtering out anything discordant, pandering to them would not serve the language. > >def blapp(something=getvalue(), other=[]): > >getvalue() should be called if something-paramer is not specified (ie. >expression something=getvalue() is evaluated), and likewise for other. No. I like your version with the lambda-colons much better. > > >Although this would break existing code and need to be delayed to at >least 3.0 and implemented in the __future__. > >I must say I can't see the reason to not delay evalution now that we Are you sure you counted your negatives there? ;-) >have nested scopes. This way, even this would work: > You're assuming default_height will refer to A.default_height > >class A: > default_height=100 > default_width=200 > def make_picture(self, height=default_height, > width=default_width): > self.gui.do_blabla(height, width) > set_default_width = classmethod(set_default_width) > IMO better: class A: default_height=100 default_width=200 def make_picture(self, height: A.default_height, width: A.default_width): self.gui.do_blabla(height, width) set_default_width = classmethod(set_default_width) >a = A() >a.make_picture() >A.default_width = 150 >a.make_picture() # Now with new default width > > >One might argue that this could could benefit from resolving >self.default_width instead, that would still require setting >height=None and testing inside make_picture. Or maybe have the implict lambda have an implicit self arg bound like a method if it is the default arg of a method, ie., so you could write class A: default_height=100 default_width=200 def make_picture(self, height: self.default_height, width: self.default_width): self.gui.do_blabla(height, width) Then when the function was called, it would be like getting an implicit something like >>> class A(object): ... default_height=100 ... default_width=200 ... def make_picture(self, height=Defer(lambda self: self.default_height), ... width=Defer(lambda self: self.default_width)): ... if isinstance(height, Defer): height = height.fun.__get__(self)() ... if isinstance(width, Defer): width = width.fun.__get__(self)() ... self.gui.do_blabla(height, width) ... class gui(object): # something to catch the above ;-/ ... def do_blabla(h,w): print 'h=%r, w=%r'%(h,w) ... do_blabla = staticmethod(do_blabla) ... >>> a=A() >>> a.make_picture() h=100, w=200 >>> a.make_picture('one') h='one', w=200 >>> a.make_picture('one','two') h='one', w='two' Obviously the nested class gui is just to make the self.gui.do_blabla call work as spelled ;-) I doubt if this is going to make it, but I think it's feasible without backwards breakage. Write a PEP if you want to pursue something like that, but don't get overexcited ;-) Regards, Bengt Richter From duncan at NOSPAMrcp.co.uk Wed Dec 3 04:11:24 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 3 Dec 2003 09:11:24 +0000 (UTC) Subject: Using and Implementing iterators with classes such as linked lists References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:bqjh7n$of2$1 at panix3.panix.com: > In article , > Duncan Booth wrote: >> >>def __iter__(self): >> def iterate(current): >> while current.next is not None: >> next = current.next >> yield current >> current = next >> return iterate(self) > > Huh? Why the extra function and complexity? > > def __iter__(self): > current = self > while current is not None: > yield current > current = current.next Because I was asleep. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From guettli at thomas-guettler.de Tue Dec 2 02:31:06 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 02 Dec 2003 08:31:06 +0100 Subject: pixels -> metrics References: Message-ID: Am Tue, 02 Dec 2003 06:53:36 +0100 schrieb DCK: > Hello > I wonder, is it possible to draw a line in Python, which one will be 1cm > long after print. In groups.google i found something like "[...]1 pixel is > 1/97inch[...]" but it ist adequate for GD-Library (Kind of PHP library, i > think). Do you have any ideas about it ? If you want to print it, I suggest that you have a look at the library of reportlab. I can create PDF with it. thomas From hwlgw at hotmail.com Sat Dec 27 06:12:53 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 03:12:53 -0800 Subject: Project dream References: <%c2Hb.7537$lo3.4095@newsread2.news.pas.earthlink.net> Message-ID: > [Andrew Dalke"] > An integrated chemical/bioinformatics development and > exploration environment. Got a few million dollars to fund me? > (Actually, more like 10 million, but bootstrappable with only > a few million.) > > :) I guess all that money is needed for getting high quality people into it? Or other reasons? What techniques would you use? > > > - A civilization like game in Python, with multiplayer support via > > twisted. > > There's been a few civ clones -- I recall playing one in the > mid-90s for Python using CLIPS for the AI. Don't recall the > name now. There's also openciv (in Python, nearly complete, > no longer active) or freeciv (in C, active). What would the > advantage be to writing yet another clone? Getting one to 1.0, to *finish* one, to a stable version that is at least as good as the original civ outofthebox. I don't think the C based versions will finish, C is rather too low level to my taste. Maybe Python can do it. I *know* it can, but for it to happen is another thing. > > - An easy to use tool for drawing diagrams, typically various kinds of > > arrows and circles and boxes, that produces nice .eps and .svg files. > > What about Sketch? > http://sketch.sourceforge.net/ I was not aware of Sketch, thanks for the link. But it has to wait until I have broadband again: needs GTK, GTK+, libart, etc. I am on Windows and downloads are slow now. > > - A roguelike in Python. Since there is still no portable curses, it > > needs WConio or something like that, and also multiplayer would be > > great. > > Why does that need to be rewritten in Python? As I understand > it, the C version is very portable and may simply need just bindings > for Python. It is, but I would like to program it. Design an AI, called Borg in roguelikes. And I can not do C bindings (too long ago I did C). Besides I don't *want* to C again :-) > > - Something for weblogging and todo things, probably via CGI. > > Aren't there a few dozen of those already? Falls into the category > of easy to write but without one clear way to do it. So there are > a lot of different implementations, all different, all focused on solving > the given author's needs. Python can be used here to *find* the way to do it, because it is easy to start all over from scratch. But so far I have not found a good path. > > What would your favorite be? > > More important, what would *your* favorite be. It looks like > you want to do a project but don't know which one to focus on. > My answer then is to do any of these projects; they are all great > ones to learn how to do larger, more useful projects. Um, more useful? Can you give some more examples of what you think useful? I am looking for a fun project and inspiration and maybe even fun people who join a project, you got that right :-) From __peter__ at web.de Fri Dec 5 10:57:47 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Dec 2003 16:57:47 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Jimmy Retzlaff wrote: > Perhaps there should be a second queue for an exception and the > sentinel. Then the main loop could look something like this (untested): > > while terminationQueue.empty() or not queue.empty(): > # The timeout is needed because we may have arrived here after > # the last value was placed in the queue but before the sentinel > # or an exception was placed in the terminationQueue. > yield queue.get(timeout=0.1) > > terminationValue = terminationQueue.get() > if terminationValue is not sentinel: > raise terminationValue > > In this case the launcher function would put the sentinel in the > terminationQueue instead of the data queue. The idea of the loop > condition above is to yield everything that came through before the > exception/sentinel, then re-raise any exception if that was the reason > for terminating. This would hopefully help clarify where the exception > occurred (i.e., on which element in the iteration). > > The separate queue also eliminates the problem of someone somehow > finding a way of injecting the sentinel into the data stream. But this > does create the need for the timeout (which doesn't work in 2.2). I > guess it's a judgment call as to whether the sentinel should be placed > in one queue or the other (or both). I'd rather not go with the above approach. At first glance it looks more complicated than the original design. Also, I'm not sure if an item in the terminationQueue could become visible before all items in the data queue. However, seeing raise terminationValue was useful in that I noticed that you do not nead a special sentinel - instead, just put a StopIteration exception into the queue. > Your generalization could make a nice Python Cookbook recipe if you feel > like putting it together. At least two of us have needed this sort of > thing. Since I posted the code, I've found a serious bug. Unless you run the generator to exhaustion, you end up with a thread where a callback waits forever to insert a tuple into the queue. So some two-way communication is needed here to tell the callback "Stop it, we're done", and I've not yet figured out how to do that. An intermediate fix is a "high" timeout and simply returning from launcher() on a Queue.Full exception. When I can advance code quality to prime time, I will probably turn it into a recipe - good idea :-) In the convenience department, this tiny class will make usage even more intuitive: class CbWrapper: def __init__(self, visit, queuesize=1, callbackpos=None): self._visit = visit self.queuesize = queuesize self.callbackpos = callbackpos def __call__(self, *args, **kwd): if self.callbackpos is not None: args = args[:self.callbackpos] + (CALLBACK,) + args[self.callbackpos:] return cbwrapper(self._visit, self.queuesize, *args, **kwd) visit = __call__ # make os.path.walk() almost as easy to use as os.walk() import os mywalk = CbWrapper(os.path.walk, callbackpos=1) for arg, dirname, names in mywalk(".", None): print "directory \'%s\' contains %d items" % (dirname, len(names)) Perhaps some extension of the class approach will also help with the dangling thread problem, killing it at least when the instance goes out of scope. Peter From newsgroups at jhrothjr.com Sun Dec 21 07:57:26 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 07:57:26 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <2rkeb1-fs3.ln1@beastie.ix.netcom.com> Message-ID: "Dennis Lee Bieber" wrote in message news:m4ofb1-123.ln1 at beastie.ix.netcom.com... > John Roth fed this fish to the penguins on Saturday 20 December 2003 > 13:13 pm: > > > languages.) It grew beyond there, but not by all that much. > > Part of it's quirky charm is the way that it's i/o system faithfully > > mirrored the old VM/CMS system. > > > That's the one feature the Amiga version did not duplicate > > Of course, since it was written to be a replacement for exec2, it > probably was quite tied to the base capabilities of IBM's OS. But in > that environment, REXX is essentially the equivalent of a shell script, > not a program running independent of a shell. Actually, it wasn't written as a replacement for exec2. It was originally written for VM/CMS, and Exec2 was an MVT/MVS facility. John Roth > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From fredrik at pythonware.com Thu Dec 18 04:35:14 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Dec 2003 10:35:14 +0100 Subject: Calling dlls with Calldll/WinDll or Ctypes or... References: <9b849915.0312172302.7999d44a@posting.google.com> Message-ID: Todd Gardner wrote: > Pardon my ignorance here. I would like to talk to someone that has > had success in calling ddls in Windows NT/2000/XP. > > I am wondering where to dload any of these packages? Google searches > keep turning up articles similar to this. similar to what? google for ctypes and press "I feel lucky": http://starship.python.net/crew/theller/ctypes/ which has a "downloads" section a bit down. calldll is a bit harder; you have to add "python" to the search string to make "I feel lucky" work: http://www.nightmare.com/software.html both distributions comes with enough demos and samples to get you going. for details on available Win32 functions, see: http://msdn.microsoft.com From http Tue Dec 2 21:39:18 2003 From: http (Paul Rubin) Date: 02 Dec 2003 18:39:18 -0800 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xptf639rd.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Maybe I shouldn't tell you this so you're forced to use a Python app, > but you can either disable the network checks or run spamd. ;-) I do use spamc/spamd, but spamd is what's going the network checks. If I start my own spamd instance I can disable them, so I'll probably do that. From ville.spammehardvainio at spamtut.fi Mon Dec 15 13:00:44 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 15 Dec 2003 20:00:44 +0200 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: Gustavo Niemeyer writes: > Heh.. "people should not".. That's the tipical RMS arrogance. To be fair to RMS, I must say I didn't quote him directly. Just tried to shoot in the right direction, more or less. BTW, the page http://www.gnu.org/gnu/rms-lisp.html Talks about this issue a bit, and says something that is more on topic and kinda interesting: ---- We had a person working last summer finishing up a translator from Python to Scheme. I don't know if it's entirely finished yet, but for anyone interested in this project, please get in touch. So that's the plan we have for the future. ---- > Today, the Lua interpreter source code is included inside APT-RPM > tarball. I've also included in the build all default Lua standard > libraries (string handling, etc), a posix module, and a regular > expression module, moving the static library size to 130kb (no > external dependencies, besides libc). Fair enough. This also sounds like an interesting Python project - make Python small and simple enough to be included in source tarballs w/o dependencies (fork?). It should be doable. I'm not sure what would have to go; some types maybe? It might not be the Real Deal, but in these cases it would still be lesser evil than TCL (don't know enough about Lua yet to say anything). > > BTW, how big is something like Guile or other minimal Scheme anyway? > > Why wouldn't it do? > > Guile's static library is about 1MB in size. In that case I'd > choose Python, not Guile. I don't remember about Scheme, but while Funny - any idea what they screwed up? To a layman, Scheme should be amoung the simplest languages to execute, you don't even need a parser. Also, a config language could execute the code as-is, w/o the bytecode compilation stage. > looking for some embeddable language I've gone trough that path, > and ended up in Lua as the best option. Let me know if you find > something better. For me, the best (well, only) option would be one that could be used in recent versions of Symbian. > > How small does it need to be for your application? > > Do you have something with 1kb? :-) Perhaps someone might be able to hack up a dynamically scoped Lisp interpreter in that space... -- Ville Vainio http://www.students.tut.fi/~vainio24 From vincent at visualtrans.de Mon Dec 22 14:56:14 2003 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 22 Dec 2003 20:56:14 +0100 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> <3014031e.0312221113.38d13d28@posting.google.com> Message-ID: "Ahmad" schrieb im Newsbeitrag news:3014031e.0312221113.38d13d28 at posting.google.com... | Sorry for not being very verbose | | I am on Linux Redhat9. Terminal used is Konsole. I am not really sure | if the terminal should be the one re-arranging the chars?! The konsole | people say it should be the application programmer to arrange the bidi | chars correctly! | | Also, I hope that my application will be cross-platform, so if there | is a way that will work with windows please tell me... The sad thruth is that complex scripts (including Arabic) are not supported on win32 console. Vincent Wehren | | Do I need python2.3? I think the one pre-packaged is 2.2 | | Also, how do I print "(U+U200F)"? | | Thnx a lot | | "Martin v. Loewis" wrote in message news:... | > Ahmad wrote: | > | > > I am a python newbie, I want to print on the console UTF-8 arabic | > > characters. They print OK with | > > print text.encode("UTF-8") | > | > Are you talking about console mode (i.e. the cmd.exe window)? Or are | > you perhaps talking about IDLE? | > | > In Python 2.3, they should also print ok when you print a Unicode object | > proper; sys.stdout.encoding should indicate what encoding the terminal | > uses. | > | > > BUT, the characters are printed LTR, not RTL (right to left). How can | > > I change the printing direction?? | > | > Assuming it is IDLE: This is a bug in Tk, then - I don't know whether | > Tk supports RTL. | > | > Assuming it is the terminal: Does the terminal support RTL in the first | > place? Python does nothing else but write the characters in logical | > order to the terminal stream; it would be the terminal's job to put | > them in the right display order. Perhaps printing RIGHT-TO-LEFT MARK | > (U+U200F) helps? | > | > Regards, | > Martin From dave at pythonapocrypha.com Mon Dec 29 15:29:29 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 29 Dec 2003 13:29:29 -0700 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: <03e501c3ce4a$76242d50$6401fea9@YODA> Thomas wrote: > On Mon, 29 Dec 2003 15:35:56 +0200, Ville Vainio wrote: > > > Thomas Dorn writes: > > > >> In your situation (i.e. trying to build a Windows application which > >> is "standard in every conceivable way"), I would not use Python. > > > > Doesn't using the mfc library (like PythonWin does) enable creating > > applications that are "standard in every conceivable way"? > > Even if there are wrappers for things like the MFC library, I would > not say that Python is a "good choice" for writing Windows applications > as defined by Pjer (and Pjer was asking whether it Python is a "good > choice" for his kind of projects or not). Why? I use Python for writing Windows applications all the time (installers, registry, COM access, etc, etc) and it works really well. > I use Python for 80%+ of my projects (mostly cross-platform) and > would normally recommend it for almost any project; but considering > the various Microsoft OS (incl. Longhorn) and their differences, I > think using C#/.NET (or maybe even C++) is a better choice for some- > one in Pjer's situation. Can you give a specific example of how the various OSs cause problems for Python but not for other languages? -Dave From fumanchu at amor.org Fri Dec 19 13:37:21 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Dec 2003 10:37:21 -0800 Subject: Parsing environment variables in ConfigParser files Message-ID: Does this snippet from ConfigParser.py give anyone any ideas on how to do this without subclassing? ;) class RawConfigParser: def __init__(self, defaults=None): self._sections = {} if defaults is None: self._defaults = {} else: self._defaults = defaults def defaults(self): return self._defaults >From the docs: "Default values can be specified by passing them into the ConfigParser constructor as a dictionary. Additional defaults may be passed into the get() method which will override all others." Let's not patch in a single use case when a simple generic solution already presents itself. Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: Peter Otten [mailto:__peter__ at web.de] > Sent: Friday, December 19, 2003 10:21 AM > To: python-list at python.org > Subject: Re: Parsing environment variables in ConfigParser files > > > Matthew Barnes wrote: > > > I'm considering submitting a patch for Python 2.4 to allow > environment > > variable expansion in ConfigParser files. The use cases for this > > should be obvious. I'd like to be able to specify > something like the > > following in a configuration file: > > > > [section_name] > > data_file=${HOME}/mydata.dat > > > > ...(where HOME=/home/matt) and have ConfigParser > automatically expand > > it to: > > > > [section_name] > > data_file=/home/matt/mydata.dat > > > > The change is pretty straight-forward, but I'm interested > in feedback > > on whether this is a good idea, what the syntax for environment > > variable references should look like (currently I'm thinking > > ${varname}), or whether there are any hidden complexities or > > backward-compatibility concerns. > > > > Matthew Barnes > > I think this can be easily achieved by subclassing the ConfigParser: > > >>> from ConfigParser import ConfigParser > >>> class ExpandingParser(ConfigParser): > ... def getexpanded(self, section, option): > ... import os > ... return self._get(section, os.path.expandvars, option) > ... > >>> p = ExpandingParser() > >>> p.read("expand.ini") > >>> p.get("paths", "mydir") > '$HOME/of/the/brave' > >>> p.getexpanded("paths", "mydir") > '/home/peter/of/the/brave' > >>> > > If you will bother with the library implementation at all, I > would prefer > this level of explicitness, i. e. a dedicated getexpanded() method in > ConfigParser, or alternatively a subclass that overrides > _get() to always > expand in the getXXX() methods. With both approaches you can > stay safely > away from backwards compatibility problems. > > Peter > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From michael at stroeder.com Tue Dec 9 15:23:16 2003 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 09 Dec 2003 21:23:16 +0100 Subject: ANN: python-ldap-2.0.0pre18 Message-ID: Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.0pre18 2003-12-09 Changes since 2.0.0pre17: ldap.ldapobject: * Fixed missing ldap._ldap_function_call() in ReconnectLDAPObject.reconnect() ---------------------------------------------------------------- Released 2.0.0pre17 2003-12-03 Changes since 2.0.0pre16: ldap.functions: * Fixed ImportError when running python -O From gerrit at nl.linux.org Thu Dec 11 10:33:39 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 11 Dec 2003 16:33:39 +0100 Subject: check disc space In-Reply-To: References: Message-ID: <20031211153339.GA4168@nl.linux.org> Fredrik Lundh wrote: > (a third argument is that "free disc space" is a rather meaningless metric > on a modern operating system; it's hardly ever useful for anything except > "warning, warning, less than 5% free space" alerts. you really don't want > people to write "if os.getfreespace() >= len(buffer): f.write(buffer)" and > file a bug when write fails ;-) Well, I think that for installation programs, downloaders and file managers, for example, it would be useful. yours, Gerrit. -- 122. If any one give another silver, gold, or anything else to keep, he shall show everything to some witness, draw up a contract, and then hand it over for safe keeping. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From bokr at oz.net Tue Dec 2 17:17:42 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Dec 2003 22:17:42 GMT Subject: Extract double in binary file References: Message-ID: On 2 Dec 2003 09:40:50 -0800, pascal.parent at free.fr (Pascal) wrote: >A very big thanks to you. >The function run perfectly (after python 2.3! installed for enumerate function) >If you can, give me more details on the methode or the number's representation. > >Thanks a lot! According to an old MASM 5.0 programmer's guide, there was a Microsoft Binary format for encoding real numbers, both short (32 bits) and long (64 bits). There were 3 parts: 1. Biased 8-bit exponent in the highest byte (last in the little-endian view we've been using) It says the bias is 0x81 for short numbers and 0x401 for long, but I'm not sure where that lines up. I just got there by experimentation. 2. Sign bit (0 for +, 1 for -) in upper bit of second highest byte. 3. All except the first set bit of the mantissa in the remaining 7 bits of the second highest byte, and the rest of the bytes. And since the most signficant bit for non-zero numbers is 1, it is not represented. But if if were, it would share the same bit position where the sign is (that's why I or-ed it in there to complete the actual mantissa). MASM also supported a 10-byte format similar to IEEE. I didn't see anything in that section on NaNs and INFs. HTH Regards, Bengt Richter From exarkun at intarweb.us Mon Dec 22 00:48:01 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 22 Dec 2003 00:48:01 -0500 Subject: Singleton process In-Reply-To: References: Message-ID: <20031222054801.GA20853@intarweb.us> On Sun, Dec 21, 2003 at 09:38:49PM -0800, Fortepianissimo wrote: > Here is the situation: I have multiple processes of same Python script > fired, but I want *only one* of them to continue and all the others to > quit immediately. > > I can use a lock file, and the first process will get the necessary > lock. But if I do open(lockfile) all the other subsequent processes > will just wait there - instead I want them to quit immediately. > > Can someone give a simple outline of how to achieve this? Thanks a > lot. import os, errno def shouldRun(): try: os.mkdir(MAGIC_PATH) except OSError, e: if e.args[0] == errno.EEXIST: return False raise return True Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From sridhara at yahoo.com Thu Dec 18 16:18:45 2003 From: sridhara at yahoo.com (SS) Date: 18 Dec 2003 13:18:45 -0800 Subject: executing python within perl script Message-ID: <95650bb5.0312181318.74399278@posting.google.com> I am trying to execute some python commands within a perl script and running into problems. The following works: python -c "import mypkg;do this; do that" however when I try to do something like #!/bin/perl -w ..... ..... $cmd = "import mypkg; do this; do that"; $string = `python -c \"$cmd\"`; and execute this perl script I get error: Traceback (most recent call last): File "", line 1, in ? File "/apps/relibase/python/reliscript/python/reliscript.py" , line 228, in ? __internal__ = internal_storage() File "/apps/relibase/python/reliscript/python/reliscript.py" , line 25, in __init__ import re; self.re = re File "/apps/relibase/python/Python-2.1.1/Lib/re.py", line 28 , in ? from sre import * File "/apps/relibase/python/Python-2.1.1/Lib/sre.py", line 1 7, in ? import sre_compile File "/apps/relibase/python/Python-2.1.1/Lib/sre_compile.py" , line 15, in ? assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 2 04:23:23 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 02 Dec 2003 10:23:23 +0100 Subject: Shared Memory Modules In-Reply-To: References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> <3fcbd6b8$1@nntp0.pdx.net> <3fcbd24f$0$1502$e4fe514c@news.xs4all.nl> Message-ID: <3fcc5a0b$0$1491$e4fe514c@news.xs4all.nl> Bengt Richter wrote: > What's that first zero argument? [...] > Does that mean you are trying to use stdin as the open file handle? No it doesn't, according to Thomas Heller's post in this thread. Thomas said 0 means "not associated with a file" on windows... --Irmen From P at draigBrady.com Thu Dec 11 09:40:55 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 11 Dec 2003 14:40:55 +0000 Subject: What GUI toolkit looks the best? In-Reply-To: References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <3FD881F7.4060901@draigBrady.com> Brian Kelley wrote: > Paul Rubin wrote: > >> I've been approached about writing a Windows app which will need a >> really professional looking GUI. Forget TKinter, this has to actually >> look good (real artists will be available to get the visual stuff >> right). Assuming I write in Python, what's the best toolkit to use? >> Some cost in implementation pain is tolerable if the finished >> interface looks better as a result. It would be nice if the toolkit >> runs on multiple platforms rather than being Windows-only. > > > Why forget Tkinter? I've seen Tkinter applications that look incredibly > fabulous. A lot depends on what you are trying to do. If you are > making a graphics-heavy application then Tkinter's canvas is pretty > sweet. I also think IDLE looks pretty good. > >> I'm thinking Glade. Is that reasonable? I don't know squat about >> Windows and haven't done much fancy GUI programming since the early X >> days. > > > Glade isn't a GUI, it is a GUI builder that uses GTK. In my experience, > GTK doesn't look quite right on windows boxes, especially the menus. Of > course I have the same basic view of Qt and Swing so know you know my > biases. > > I tend to use Tkinter for canvas heavy applications and wxPython for > other stuff. > > As for application building, here are my rankings > 1 Emacs :) > 2 Glade with libglade and Mitch Chapman's python libglade wrapper Freaky. I've been using something VERY similar for the last 2 years. An example of my libglade.py usage is at: http://www.pixelbeat.org/talks/pygtk/mail/ Great minds think alike I suppose :-) P?draig. From rmb25612 at yahoo.com Tue Dec 2 18:19:30 2003 From: rmb25612 at yahoo.com (Richard James) Date: 2 Dec 2003 15:19:30 -0800 Subject: calling programs from python References: Message-ID: <2c60f0e0.0312021519.68904813@posting.google.com> David MacQuigg wrote in message news:... > On Mon, 01 Dec 2003 19:27:34 -0500, "RR" wrote: > > >Hello, > > > >I am trying to call a program in python as I would call it in the command > >line. For example I want to do the following from python: command > file. > >Then read this file. How do I call "command > file" ? Much help > >appreciated. > > Use os.system() For example, on Unix: > >>> import os > >>> os.system( 'command > file' ) > and on Windows: > >>> os.system('start C:\Python23\python.exe') > > -- Dave Windows Python os module has os.startfile() os.startfile('C:\Python23\python.exe') -- Richard From paul.koelle at archit.uni-weimar.de Sun Dec 14 11:06:19 2003 From: paul.koelle at archit.uni-weimar.de (paul) Date: Sun, 14 Dec 2003 17:06:19 +0100 Subject: cPickle from 2.2 to 2.1 Message-ID: hi list, I use cPickle in a small .cgi to save data. It run's fine on python 2.2.3 (used for development) but fails on 2.1.1 (webserver) with: File "spyblog.py", line 543, in __init__ self.entry = cPickle.load(open(log + self.filename, 'r+')) SystemError: Failed to import class _reconstructor from module copy_reg If I create the file on the webserver everything works, so apparently the 2.1.1 version of cPickle can't read files generated with the newer one. Does it mean the cPickle format is not compatible across versions? thx Paul From bdesth.tagada at tsoin-tsoin.free.fr Mon Dec 22 15:53:00 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2003 21:53:00 +0100 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <3fe7554d$0$1156$636a55ce@news.free.fr> John Roth wrote: (snip) > > If a language makes opportunities for errors, then there is > something wrong with the language that needs to be corrected. Lol ! Tell us when you'll find a language that do not "make opportunities for errors". From eaglehawk777 at aol.com Thu Dec 11 04:11:21 2003 From: eaglehawk777 at aol.com (EAGLEHAWK777) Date: 11 Dec 2003 09:11:21 GMT Subject: DO YOU NEED MONEY NOW?? Message-ID: <20031211041121.26239.00000680@mb-m06.aol.com> JUST CHECK OUT MY WEBSITE http://www.webspawner.com/users/hawkk/index.html From shaleh at speakeasy.net Sat Dec 27 10:52:03 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat, 27 Dec 2003 07:52:03 -0800 Subject: shortcut event binding~ In-Reply-To: <20031225025647.89612.qmail@web21326.mail.yahoo.com> References: <20031225025647.89612.qmail@web21326.mail.yahoo.com> Message-ID: <200312270752.03396.shaleh@speakeasy.net> On Wednesday 24 December 2003 18:56, black wrote: > Hi all~ > > I've already binded events for single key pressing but dunno how to > bind events for multiple keys, say shorcut ? any example will be welcome. > You may be better helped if you a) use the tutor at python.org list b) say what you tried and how it failed. From mwh at python.net Thu Dec 11 10:18:28 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 11 Dec 2003 15:18:28 GMT Subject: 2.3.2 Memory Leaks ? References: Message-ID: genjox at yahoo.com (Robert) writes: > Hi, > I am building with VS 6.0 under WinXP, and building with the default > python configuration & settings. I build a test python app with just > the following code: > > > /* testing for memory leaks */ > long tmp_flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); > tmp_flag |= _CRTDBG_LEAK_CHECK_DF; > _CrtSetDbgFlag( tmp_flag ); > > Py_Initialize(); > Py_Finalize(); > > > For some reason I am seeing a *bunch* of memory leaks. Does anyone > know what the problem could be? There are various objects (interned strings being an example) that do not get deallocated before shutdown, but calling them "leaks" seems a bit of a stretch. Are they causing you problems? Cheers, mwh -- SCSI is not magic. There are fundamental technical reasons why it is necessary to sacrifice a young goat to your SCSI chain now and then. -- John Woods From Kevin.Smith at sas.com Thu Dec 11 14:32:14 2003 From: Kevin.Smith at sas.com (Kevin Smith) Date: 11 Dec 2003 19:32:14 GMT Subject: Formatting floats Message-ID: <20031211143214964-0500@braeburn.themorgue.org> I'm trying to get floats formatted in exponent notation but with the first non-zero number to the right of the decimal instead of to the left ( e.g. '-.107E2' instead of '-1.07E1'). Is this possible using the string formatting operations? -- Kevin Smith Kevin.Smith at sas.com From eric.brunel at N0SP4M.com Mon Dec 8 04:08:29 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 08 Dec 2003 10:08:29 +0100 Subject: Nub needs help withTkinter References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> Message-ID: Agency wrote: > I'm trying to program a utility that counts the beats per minute in a > song > by tapping the spacebar. I already have a program that does this, but > I wanted to make my own. The "enter" key resets the counter to zero > along with one of two displays. I'm importing Tkinter and this is what > I have so far. I get a syntax error at this spot -----> > > Any thoughts how to get the keypress to increase the counter better? > Is it possible to convert it to an int or something? > ------------------------------------------------------------------ > from Tkinter import * > > root = Tk() > w = Label(root, text="The BPM Counter") > w.pack() > > class display1: > def beat(): > beat = 0 > if beat > 10000: > beat += > > root.mainloop() > ------------------------------------------------------------------- I can't even begin to undeerstand what you're trying to do here: is only valid in a string as an event description that you can pass to the various bind methods, so converting it to an int has no meaning at all for me... Maybe you should begin with a tutorial for Tkinter; you'd surely understand better what's going on and how you can do things with it. "Thinking in Tkinter" is usually a good place to start: http://www.ferg.org/thinking_in_tkinter/index.html (follow the link all_programs.html to get the full the whole series of scripts and the explanations around them). HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From paolo.cantore at t-online.de Sat Dec 13 17:23:06 2003 From: paolo.cantore at t-online.de (Paolo G. Cantore) Date: Sat, 13 Dec 2003 23:23:06 +0100 Subject: beginner python cgi question References: Message-ID: <3FDB914A.2030002@t-online.de> Use 'fields=cgi.FieldStorage(keep-blank-values=1)' and you don't have to worry about KeyErrors anymore. Hope this helps. Paolo Brandon Boles wrote: > Hi folks, > > I am trying to learn python, and have a form processing script giving me > this error: > > Traceback (most recent call last): > File "inquiry", line 16, in ? > Address=fields["address"].value > File "/usr/local/python2.2/lib/python2.2/cgi.py", line 550, in __getitem__ > raise KeyError, key > KeyError: address > > This is the snippet of code the error is referring to: > > ...snip... > fields=cgi.FieldStorage() > if (fields.has_key("name") and fields.has_key("emailaddr")): > SenderName=fields["name"].value > Address=fields["address"].value > City=fields["city"].value > State=fields["state"].value > ...snip... > From jeder at earthlink.net Sat Dec 6 14:20:58 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Sat, 06 Dec 2003 19:20:58 GMT Subject: Translation (used to be 'Moving around in a string') Message-ID: Hello Again Everyone, As previously aforementioned in my post 'Moving around in a string', I've finally found my result to the pig_latin approach. [start code] import string choice = raw_input("Would you like pig latin (p) or ubby dubby (u) translation? ") sentence = raw_input("Please enter a sentence: ") #Split up the sentence words_within = sentence.split() #Pig Latin if choice == "p": words_within = sentence.split(" ") for word in words_within[0:]: pig_latin = word[1:]+word[0]+"ay" print pig_latin, [end code] Now all I have to find out how to do is find a vowel within the words of a string and then do the ubbi dubbi thing (adding 'ub' after every spoken vowel in a word it describes) ~Ryan From martin at v.loewis.de Mon Dec 8 12:34:06 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Dec 2003 18:34:06 +0100 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: Duncan Booth writes: > > The question is whether a Python implementation for .NET would be CLS > > compliant (CLS == Common Language Specification). The existing > > implementation has shown that this is not possible without giving up > > parts of the Python semantics. > > > The main problem is that functions are first class objects in Python, but > not in the CLS. The CLS uses delegates to refer to functions, and a > delegate encapsulates both an object and a pointer to a method. In addition, I think one problem is that in CLS, a class has a pre-determined set of data attributes, whereas in Python, instances grow new data attributes as they live. > I have been playing around with a variant on the managed Python compiler, > and I think I have figured a way to implement Python which might just get > around this bottleneck. Unfortunately it requires a lot of refactoring from > the original model, and I'm only working on it occasionally in my spare > time. Very interesting. Are you willing to share the intermediate results that you get? Publish early, publish often :-) Regards, Martin From aahz at pythoncraft.com Sun Dec 28 10:11:28 2003 From: aahz at pythoncraft.com (Aahz) Date: 28 Dec 2003 10:11:28 -0500 Subject: Project dream References: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Message-ID: In article , Will Stuyvesant wrote: > [Rene Pijlman] >> >> Yes, that's what I meant. Although Chandler seems much more ambitious. >> Very interesting project. > >I wonder how healty it is: their wiki is empty, the Mitch Kapor blog >is stopped, there is not much recent news. But interesting certainly. Mitch Kapor was looking for a Python tutor a while back; he may be taking a breather to really learn Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From marcos at nordesia.org Mon Dec 22 03:37:04 2003 From: marcos at nordesia.org (Marcos Eimil Pardo) Date: Mon, 22 Dec 2003 09:37:04 +0100 Subject: Some pygame issues In-Reply-To: References: Message-ID: <3FE6AD30.8090407@nordesia.org> > >class dot: > x = 317.5 > y = 207.5 > width = 15 > height = 15 > #dir = +1 > # You can uncoment dir = 1 # *or* add a variable called speed so it has clearer meaning speed = 1 > > #Collision detection > if leftpadd.y > 430: > leftpadd.y = 430 > > if rightpadd.y > 430: > rightpadd.y = 430 > > if leftpadd.y < 0: > leftpadd.y = 0 > > if rightpadd.y < 0: > rightpadd.y = 0 > > #Dot Motion > dot.x = dot.x+1 > # Replace the previous line with, so dot will move along direction dot.x = dot.x + dot.dir # or with the variable speed dot.x = dot.x + dot.speed > > #Dot collision HAVING ISSUES HERE! > if dot.x + dot.width > rightpadd.x: > dot.x = dot.x-1 #Think that dot is not allways colliding pad so you can't do this, when dot collides it should change the sign of it's velocity: dot.dir = -dot.dir # Or dot.speed = -dot.speed > if dot.x + dot.width < leftpadd.x: > dot.x = dot.x+1 > # The same for the left pad dot.dir = -dot.dir # Or dot.speed = -dot.speed > #Refresh the screen and pump the event qeue. > pygame.display.flip() > pygame.event.pump() > I see you haven't take in account the y-axis movement, it works the same way but you should have a 2-component speed, so, the class dot will look like that: class dot: x = 317.5 y = 207.5 width = 15 height = 15 speedx = +1 speedy = +1 Greets, Marcos. (And merry xmas :) From amy-g-art at cox.net Fri Dec 26 20:13:50 2003 From: amy-g-art at cox.net (Amy G) Date: Fri, 26 Dec 2003 17:13:50 -0800 Subject: Adding newusers to Unix system from mysql data (Better Approach) Message-ID: I am writing a simple Python program that will read in data from a database (userid, password, username). It will then store the data in a file in the format name:uid:gid:class:change:expire:gecos:home_dir:shell:password or in my case userid::20::::username::sh:password Then I do an os.system('adduser -f ') My problem is this... It writes the data file without problem. But, the os.system... does not necessarily work to add a new user. By 'not necessarily' I mean that it works some of the time, but not all of the time. If I run the program and it does not work, I can simple type 'adduser -f ' at the command line and it works no problem. Any ideas what could be causing this. CODE ****************************************************************** #!/usr/local/bin/python import MySQLdb import os db=MySQLdb.connect(db="challenge") c=db.cursor() c.execute("""SELECT userid, password, name from users where status is null""") aList = [] for line in c: userid, password, name = line aList.append("%s::20::::%s::sh:%s" %(userid, name, password)) f1=open('/home/sean/bin/users.test', 'w') for line in range(len(aList)): f1.write(str(aList[line]) + "\n") f1.close os.system('adduser -f /home/sean/bin/users.test') **************************************************************** Thanks in advance. From bwglitch at hotpop.com Thu Dec 11 21:38:14 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Thu, 11 Dec 2003 21:38:14 -0500 Subject: Kinda newb-ish question In-Reply-To: <5c27220b.0312111650.7f0a128d@posting.google.com> References: <5c27220b.0312111650.7f0a128d@posting.google.com> Message-ID: ChocoboMog123 wrote: > What's wrong with line 8 in this code? > x=1 > while 1==1: I think it would be better as: while True: > x=x+1 > y=range(1,x) > z=0 > q=9 > for count in y: > q=x%y It should be: q=x%count > if q==0: > z=z+1 > if z<1: > print x > It keeps giving me > Traceback (most recent call last): > File "C:\Python23\Prime Number.py", line 8, in -toplevel- > q=x%y > TypeError: unsupported operand type(s) for %: 'int' and 'list' > > It's supposed to be a program to print out prime numbers. > If anyone knows of a program that does this or can write one, can you > show me the code? Thanks. As it points out, y is a list. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "So, give us the scoop! What's it actually feel like, bein' a Pred?" "Like you're three gigabytes of attitude on a two-gig hard drive. No wonder they got personality problems!" -- Cheetor and Rhinox, "Dark Designs" From nospam at nospam.yes Wed Dec 3 04:52:14 2003 From: nospam at nospam.yes (Jon Arter) Date: Wed, 03 Dec 2003 10:52:14 +0100 Subject: redirecting Stdin Message-ID: Hi Is is Possible to redirect the Python stdin in order to receive stdin commands from a file ? The time of redirection can last until exiting the Python and should be transparent for python it self. with regards Jon From francisgavila at yahoo.com Sat Dec 6 17:17:54 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 6 Dec 2003 17:17:54 -0500 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com><8089854e.0312050419.2cf36e34@posting.google.com><30oAb.9577$aw2.4588872@newssrv26.news.prodigy.com> Message-ID: Skip Montanaro wrote in message ... > The >correct way to compare two strings is using '==' (which is independent of >CPython's implementation details), not 'is'. I think it's better to say that the only time you *use* 'is' is when you *know* the object you're comparing to is a singleton (None, True, or False). Every other time, use '=='. And don't be deceived by 'is' working sometimes. -- Francis Avila From __peter__ at web.de Sat Dec 13 06:37:46 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Dec 2003 12:37:46 +0100 Subject: Style question References: Message-ID: Kamus of Kadizhar wrote: > I have the following line: > > remoteMD5hash = Socket.recv(256) > > But what I really want is remoteMD5hash.strip() > > What's the best way to say that on one line? > > remoteKD5hash = string.strip(Socket.recv(256)) ? > > Or something better? remoteMD5hash = Socket.recv(256).strip() Peter From soloj at earthlink.net Fri Dec 5 17:36:09 2003 From: soloj at earthlink.net (Josh) Date: Fri, 05 Dec 2003 22:36:09 GMT Subject: Python modules for manipulating multimedia files? Message-ID: Are there any modules that would allow me to manipulate avi or mpeg files? Specifically, I am looking to do operations like joining avi or mpeg files or convert from one format to another. Google didn't turn up anything useful. From mcfletch at rogers.com Thu Dec 25 16:29:56 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 25 Dec 2003 16:29:56 -0500 Subject: How does "delegation" work as per the FAQ? In-Reply-To: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> References: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> Message-ID: <3FEB56D4.2050902@rogers.com> Rene Pijlman wrote: >Ville Vainio: > > >>Rene Pijlman: >> >> >>>__getattr__: "Called when an attribute lookup has not found the attribute >>>in the usual places". There is no mention of method calls. >>> >>> >>A method is an attribute. >> >> > >I see. But how are the arguments of a method call passed on, when >delegation is implemented this way? > > Jeff already gave you a fairly brief description of why this is so, but I'll try to flesh it out somewhat. In Python, methods of objects are actually themselves objects which wrap up an implementation function (also an object) and a reference to the object on which they are to act (the "self" parameter). To demonstrate this: >>> class x(object): ... def y( self, value ): ... print value ... >>> item = x() >>> item <__main__.x object at 0x011EA4B0> >>> item.y > >>> x.y >>> item.y.im_self <__main__.x object at 0x011EA4B0> >>> item.y.im_func >>> item.y.__call__ So, when you do item.y( somevalue ), you are doing this set of actions: * doing an attribute lookup in the object item for the attribute name y o in this example, this finds the unbound method x.y in the class, which (via various hooks (see discussions of "descriptors")) generates a new bound method object (item.y) for the instance "item" and returns that. o in the sample code you found, the methods for the file object would not be found in the instance "item"'s dictionary or class' dictionary, so the __getattr__ hook (which is called when an attribute lookup fails) would be called and accomplish the delegation by doing another attribute lookup from the object to which it is delegating responsibility. * calling the __call__ method of the (newly created) bound method object with the arguments (somevalue) o in this example, the bound method has a reference to "item" which it will pass as the first argument to it's underlying "y" function, so the arguments passed to the function are (item, somevalue) (corresponding to self, somevalue in the method signature). o In the sample code, the bound method would have a reference to the delegated file, rather than the delegating object, so it will act on the underlying file. Enjoy yourself, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From whisper at oz.net Fri Dec 26 19:30:43 2003 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Dec 2003 16:30:43 -0800 Subject: Tkinter: is event_generate safe from background thread? In-Reply-To: Message-ID: > In general, I thought one should not mess with Tkinter from a background > thread. But Eric Brunel recently posted a clever suggestion that one > could communicate from a background thread to the main thread using > event_generate to create custom events. Very neat: it's direct and it > saves polling. He said it works for him on Linux, Windows and Solaris. > I'd love to use it in my code, but am wondering if it's truly safe, e.g. > safe by design and likely to remain so? > > Also, are there any other things one can safely do with Tkinter from > background threads (such as set variables)? > > -- Russell The general rule is that the thread that owns the GUI can be the only one that can directly manipulate the GUI (call it's functions). Sending messages that the GUI thread processes is nearly always just fine since the GUI thread, and it's state, are used to do the actual GUI manipulation. Directly setting variables from one thread to any other thread without any sort of access control (sempaphore, etc.) is a very not good thing to do, whether it's a GUI thread or not! HTH, Dave LeBlanc Seattle, WA USA From mwh at python.net Fri Dec 5 07:46:48 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 5 Dec 2003 12:46:48 GMT Subject: Lists and Tuples References: <48j5a1-i13.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber writes: > Jeff Wagner fed this fish to the penguins on Thursday 04 December 2003 > 21:19 pm: > > > tuple. So, what's the difference and why choose one over the other? > > > A tuple can be the key for a dictionary, a list can't. > > > Not sure of a tuple containing a list, though... Nope. A tuple is hashable iff all of its elements are. Cheers, mwh -- Now this is what I don't get. Nobody said absolutely anything bad about anything. Yet it is always possible to just pull random flames out of ones ass. -- http://www.advogato.org/person/vicious/diary.html?start=60 From max at cNvOiSsiPoAnMtech.com Tue Dec 9 12:55:47 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Tue, 09 Dec 2003 17:55:47 GMT Subject: Understanding and working with __metaclass__ In-Reply-To: <99dce321.0312081149.2a32575d@posting.google.com> References: <99dce321.0312081149.2a32575d@posting.google.com> Message-ID: There is a nice example in from mailman by Eric Raymond: http://pythonology.org/success&story=esr David M. Wilson wrote: > Hi there, > > I've been sitting on the __metaclass__ feature for about 2 weeks now, > and haven't really got that far with it. It looks like a very powerful > tool, and I think I have even already identified places in my code > where I could use it quite effectively, but I can't quite tell what it > is /meant/ to be used for, or indeed what it is popularly used for. > > Is there a page, posting, or other place I can turn to to get a > developer's run-down on the practical uses of __metaclass__? The > Python documentation states very clearly what it does, but I fear that > journeying off on my own with it will lead to some terrible habit > formation, and I already have enough of those to deal with. :) (:set > ts=3 ;) > > Thanks for your time, > > > David. From abhjrpe at comcast.net Wed Dec 31 13:31:46 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Wed, 31 Dec 2003 13:31:46 -0500 Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> <3ff30f2f.674586974@news.blueyonder.co.uk> Message-ID: Why do I need to tinker with it? You don't need to tinker with mature programs. From tjreedy at udel.edu Mon Dec 29 15:11:49 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2003 15:11:49 -0500 Subject: just another default argument value gotcha References: Message-ID: "Frank Bechmann" wrote in message news:dbc00a99.0312290133.3e9e6241 at posting.google.com... > Eventually most of you will not learn much from this because it's just > another event in the 'default argument value gotcha' series, but There are two issues: when the default value is determined and whether it is mutable. The concern here is timing. > I tried to use some method which was documented to write to > 'sys.stdout' per default The meaning of the expression 'sys.stdout' may depend on when it is evaluated. > so that changing 'sys.stdout' to bind to > another object should allow to get grip on the method's output. If you change the binding before the evaulation, you will affect the result; otherwise not and your inference is incorrect. > but that didn't work - reason was that that 'sys.stdout' was used as > default argument value for the method. Without the doc quoted, I can't tell whether it was misleading or if you misread it. If the doc said 'default argument value' then it was exactly right. > The following code describes it better then my english can do, > so as it seems for me, one should make sure to use the 'f2' variant. The code to use is the one that gives the result you want. To give a function parameter a default *value*, evaluated once and good for all function calls, write the expression yielding the value (a constant object) in the definition-time header as in > import StringIO, sys > > def f1(msg, out=sys.stdout): > out.write("%s\n" % msg) To me, and apparently to GvR, this is what 'default value' means. If you want a backup *expression*, conditionally evaluated at each function call (and therefore potentially yielding different objects in different function calls), write the expression in the run-time body as in > def f2(msg, out=None): > if not out: > out = sys.stdout > out.write("%s\n" % msg) In this case, I see passing an value for param 'out' via the runtime-evaluated global attribute sys.stdout as an alternate (implicit) arg passing mechanism, one that is fairly common. Simplifying f2 gives def f3(msg): out = sys.stdout out.write(("%s\n" % msg) The added complexity of f2 gives one the option of passing 'out' either directly in the call or indirectly via the global. I would only use it if one needed and were going to use the added flexibility. The authors of the method you used did not think it necessary. Another issue your problem touches on is the ambiguity of 'builtin' names like 'sys' and 'sys.stdout'. When the docs use such names, they sometimes to usually to always mean the objects originally bound to the name on interpreter startup, ignoring any possible later rebindings within a program execution. The reader is expected to interprete the text immediately using the default, pre-startup bindings. For example, in 'functions return None by default', 'None' means the singleton NoneType object, not its runtime binding. Similarly, 'sys.stdout' is sometimes used to refer specifically to its original rather than 'current' binding. I would tend to assume this for library modules unless the doc, the code, or experiment showed otherwise. Terry J. Reedy From mickey at tm.informatik.uni-frankfurt.de Wed Dec 17 09:15:48 2003 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 17 Dec 2003 14:15:48 GMT Subject: A GUI toolkit for Python that is NOT x-windows dependent References: <88f9e356.0312162305.58718893@posting.google.com> Message-ID: Andre Brightway wrote: > I need a script to draw a keyboard to the screen and animate the > marking each key when the key is pressed (among other things like > being able to draw menus). This script is for testing keyboards and > needs to be run by people who may never have touched a computer before > so it needs to have an easy to follow GUI interface. But the Linux > boxes these will be runned on are very low-end, 'diskless' terminals > where running a full X-Windows system would be very slow. Does anybody > know of a GUI toolkit (or a way to draw to the screen) that can be > used from Python script in Linux without having to run X-Windows? PyQt binds against Qt/Embedded which runs directly on the framebuffer. We're using this on PDAs and WebPads. From robert_dodier at yahoo.com Mon Dec 29 11:21:39 2003 From: robert_dodier at yahoo.com (Robert Dodier) Date: 29 Dec 2003 08:21:39 -0800 Subject: Special-purpose extension of Python -- new kinds of objects References: <6714766d.0312281442.78cd0a4b@posting.google.com> <7xwu8g7eao.fsf@ruckus.brouhaha.com> Message-ID: <6714766d.0312290821.86b2f64@posting.google.com> Paul Rubin wrote: > robert_dodier at yahoo.com (Robert Dodier) writes: > > # "dn" == "decision network", an Ephemeral construct; > > # this part is parsed separately from the python code > > dn my_example: > > chance X: > > cpd: gaussian [mean: 25, std_dev: 75] > > chance Y: > > cpd: gaussian [mean: 12, std_dev: 19] > > chance Z = X + Y > > I don't see what good this does. You can do the same thing with > ordinary Python classes. Thanks for your interest. I want to make it possible to experiment with notations that don't correspond to Python syntax. For example, to write "X ~ gaussian(mu,sigma2)", or to write "Y <- (X1, X2, X3)", say. The larger goal is to make the decision model description as natural as possible for people that work on decision problems. Development effort should focus on the decision model, which, in interesting problems, may be much larger and more complex than the ordinary Python glue code around it. Languages such as BUGS, S, dot, and Netica express the sorts of ideas that I want in Ephemeral. Robert Dodier -- ``Strange women, lying in ponds, distributing swords, is no basis for a system of government.'' -- Dennis (MP&THG) From nospam at nopes Mon Dec 22 20:35:30 2003 From: nospam at nopes (Steve) Date: Tue, 23 Dec 2003 12:35:30 +1100 Subject: PBS and Python Message-ID: <3fe79ba9$1@clarion.carno.net.au> Hi, Is there a module available for PBS (Portable batch system) interfacing with python? Could someone also point me out to a tutorial? Thanks a lot! Steve From mrfaro at libero.it Tue Dec 9 17:07:32 2003 From: mrfaro at libero.it (Gabriele Farina) Date: Tue, 09 Dec 2003 22:07:32 GMT Subject: Using XUL with python References: Message-ID: Tnx a lot to everyone. I looked at Luxor yesterday, but I don't want to use jython to build my application. Instead pyXPCOM seems a good job, but I cant install the estension under windows. Now I'll try to read the documentation you give me and then I'll try to install the extension. It seems pyXPCOM needs mozilla running to be functional. Is this true?? How can I merge my program and mozilla toghether to work like Komodo does? tnx a lot, good night :) From francisgavila at yahoo.com Wed Dec 24 07:08:41 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 24 Dec 2003 07:08:41 -0500 Subject: writing recursive lambda functions References: Message-ID: Thorsten R?hl wrote in message ... >Hi there, > >at first i have to say i am very new in python so i have a few problems to >get along with some things. > >My first problem i can?t handle is to write a recursive lambda function: >the formal definition is > >letrec map(f) = lambda l. if != NIL then NIL > else cons(f(car(l)), map(f)(cdr(l))) > >after i realised that i can?t use if clauses in lambda definition i tried >to convert the if line in an correspondending boolean operator line: > >def mapp(f): > lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l)))) > >but it doesn?t work. You need to return the lambda. You've been coding too much lisp. ;) >if i try to use the result in the following way i get an error: object not >callable but i don?t understand why it is not callable. Because mapp always returns None (the implicit return value), and None isn't a callable. >So i hope this is question is not to nooby and i did?nt waste your time. > >But i really need a little help with this. I'm not sure why you want to code Python as if it were lisp. This will only lead to tears. It's also quite a bit slower, because calling is expensive in Python. (I understand if this is simply an academic exercize, but still, try to read beyond the formal definitions). Typical thing you'd do in Python is one line: [x*x for x in L] This makes crystal clear what you want to do. I had to puzzle over that pseudolisp to figure out the big picture. Replace x*x with whatever you want. The recursive '(cons ((car L) (func (cdr L))))' pattern in lisp is 'for item in sequence' in Python, and there's no need to pass a lambda into a function factory. Also, we already have a map (as you noticed, because of your namespace clash). So map(lambda x: x*x, [1,2,3,4]) works. If you want to curry it, you can do so: def curry(f, *args): def inner(*args2): return f(*(args + args2)) return inner mapQuad = curry(map, lambda x: x*x) mapQuad([1,2,3,4]) -- Francis Avila From jjl at pobox.com Sat Dec 27 18:52:13 2003 From: jjl at pobox.com (John J Lee) Date: Sat, 27 Dec 2003 23:52:13 +0000 (GMT) Subject: Project dream In-Reply-To: References: Message-ID: On Sat, 27 Dec 2003, David LeBlanc wrote: [...] > > Related links: [...] > Thanks! On a quick look "storage" and haystack looked the most interesting! > > Any pointers towards "mind map" (like "The Brain") type open source? No, because I'm not sure what it is. I looked at the web site (www.thebrain.com), and decided that life is too short to decode marketing hype <0.5 wink> The fact that I want to *know* about the end results that a piece of software facilitates doesn't mean that *reading* about end results in abstract terms is going to give me the slightest understanding of same... but as usual we get pages of bullet points like "decrease time to productivity" ( gee, and I thought your product was designed to *increase* time to productivity...) instead of any hint of what the software actually does. Um, they are selling software, right? Or is an "enterprise knowledge platform" one of those comfy executive chairs with a built-in book-rest? John From deets.nospaaam at web.de Mon Dec 1 07:44:30 2003 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2003 13:44:30 +0100 Subject: how to show a bitmap? References: Message-ID: > Look in the code examples for some effects that utilize this - AFAIK there > is something like a fire or motion blurring. These access pixel data. Just > plug in your array, and you should be done. http://www.pygame.org/pcr/numpy_flames/index.php This is the flames example. The function in question is blit_array - look it up in the docs. This example even deals with indexed_bitmap_data, which is what you want, as you have a only one value per pixel. Regards, Diez From rasjidw at openminddev.net Wed Dec 3 03:23:08 2003 From: rasjidw at openminddev.net (Rasjid Wilcox) Date: Wed, 03 Dec 2003 19:23:08 +1100 Subject: Building a GUI agnostic database application Message-ID: <3fcd9d2a@mail.netspeed.com.au> I am wanting to write a database application using Python. I want it to be GUI agnostic. The GUI will probably be Python/wxPython, but I would also like the option of a Webbased (PHP?) gui, and possibly GUI's in Java or C++, Visual Basic etc. The Python 'backend' may run on the same machine as the client (thick client), or on the same machine as the database (thin client). My main requirements are: 1. Reasonably light-weight 2. Secure authentication between the GUI and the backend. 3. Ideally runs wherever Python runs, and at least on Linux, Mac and Windows. http://www.markcarter.me.uk/computing/python/python.html has a list of possible candidates. These include: Corba, OSE, SOAP, Spread, Twisted, XML-RPC and Yami It looks to me like XML-RPC run over SSL is probably the simplest solution, but I'd be interested in other peoples views. Thanks, Rasjid. From yan at NsOeSiPnAeMr.com Sat Dec 13 08:15:13 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 13 Dec 2003 08:15:13 -0500 Subject: "Do this, and come back when you're done" In-Reply-To: <7xekv8vq0l.fsf@ruckus.brouhaha.com> References: <7x8ylg5252.fsf@ruckus.brouhaha.com> <7xekv8vq0l.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Why don't you look at the rsync program. It brings two machines into > sync with each other by automatically detecting differences between > files and sending only the deltas over the network. Well, the purpose of this whole project was to learn python. I did look at the pysync modules (rsync written in python), but it's too complicated for me at the moment. -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From echols at uclink.berkeley.edu Thu Dec 4 15:01:23 2003 From: echols at uclink.berkeley.edu (Nat Echols) Date: Thu, 4 Dec 2003 12:01:23 -0800 Subject: segfault in extension module In-Reply-To: References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: > Well, I can't see anything flagrantly wrong with that. > > Does a debugger provide any hints? Someone else suggested this, and this is what the backtrace from gdb indicated: #0 0x420744fe in _int_free () from /lib/tls/libc.so.6 #1 0x420734d6 in free () from /lib/tls/libc.so.6 #2 0x0809dc0d in _PyObject_GC_Del () #3 0x080ce86f in PyDict_Next () #4 0x080d191d in _PyModule_Clear () (It goes on like this for a while. . .) As far as the tls C library, which someone told me was buggy - I don't know how to force use of a different library; Python appears to be linked to the same one. At any rate, I seem to have the same problem on two different machines, one running SuSE 8.1, one running RedHat 9.0. thanks, Nat From satya at ttck.keio.ac.jp Thu Dec 11 02:12:25 2003 From: satya at ttck.keio.ac.jp (Satya Arjunan) Date: Thu, 11 Dec 2003 16:12:25 +0900 Subject: sys.argv with quoted strings as option argument Message-ID: <3FD818D9.40109@ttck.keio.ac.jp> Hi everyone, I would like to send an option argument which is a quoted string with whitespaces to a python program. For example: $ ./myprogram.py --includedir="/usr/include /usr/local/include" --libdir="/usr/lib /usr/local/lib" However, sys.argv breaks the arguments whenever it encounter spaces, like this: ['./myprogram.py', '--includedir=/usr/include', '/usr/local/include', '--libdir=/usr/lib', '/usr/local/lib'] So I can't seem to use getopt or optik to process such cases. Is there a good way where I can preserve such option arguments with whitespaces? satya -- Satya Nanda Vel Arjunan Institute for Advanced Biosciences Keio University http://satya.host.sk/ From cfriedl at bigpond.net.au Thu Dec 25 22:11:33 2003 From: cfriedl at bigpond.net.au (Chris Friedl) Date: Fri, 26 Dec 2003 03:11:33 GMT Subject: graphs References: Message-ID: I was just looking at graphs for python recently. try these: http://www.dislin.de/ http://kim.bio.upenn.edu/~pmagwene/disipyl.html http://matplotlib.sourceforge.net/ http://www.scipy.org/site_content/chaco be well and happy always Chris "km" wrote in message news:mailman.94.1072272461.684.python-list at python.org... > Hi all, > > Is there any inbuilt python module which can draw 2-D or 3-D plot to a file (png/jpeg etc) or one which interfaces gnuplot on linux ? > > kindly enlighten, > regards, > KM > From j.r.gao at motorola.com Mon Dec 15 03:01:02 2003 From: j.r.gao at motorola.com (J.R.) Date: Mon, 15 Dec 2003 16:01:02 +0800 Subject: execl difficulty References: Message-ID: You may try os.execl("c:\\WINDOWS\system32\xcopy.exe", "E:\\MainWeb\\dreampics\\*.*", "E:\\MainWeb\\dp") J.R. "python newbie" wrote in message news:W44Db.39213$B03.19442 at newssvr29.news.prodigy.com... > Can anyone tell me why this would cause "Invalid Number of Parameters" while > trying to compile (or interpret or whatever) > > import os > os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Main > Web/dp") > > Here's what the Python reference says: > execl(path,arg0, arg1, ...) > > if you can see something obvious, please tell me > thanks > Steve > > > From jeder at earthlink.net Sat Dec 6 05:07:32 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Sat, 06 Dec 2003 10:07:32 GMT Subject: Moving around in a string References: Message-ID: On Sat, 06 Dec 2003 09:13:53 +0000, Troels Therkelsen wrote: > This sounds suspiciously like homework, but... > >>>> foo = "Orange" >>>> bar = foo[1:] + foo[0] + 'ay' >>>> bar > 'rangeOay' > > In other words, you can index strings the same way as any other sequence, > [0] is the first element of the sequence, [1] the second, [-1] is the last, > and so forth. > > See also the standard documentation on sequences: > > http://www.python.org/doc/current/lib/typesseq.html > > > Regards, > > Troels Therkelsen Hey Troels, Thanks for the advice, Pulled it off by. [start code] def pig_latin(word): space = word[0] result = word[1:]+space+"ay" print result [end code] This all leads me to another problem. In my recent attempts I've been trying to learn how to parse sentences and such down more and more (by amt. of characters, words, lines, etc.) If you don't mind another question, how do I go about say, parsing for words in a string? I would logically conclude to somehow find a way to declare that everything with a space between it (or for every space) add one to a 'word_count' variable maybe, but, the question for that would be how do I get the system to search the string for a certain character, especially if it is a space? Thanks a ton, ~Ryan From zunbeltz at wm.lc.ehu.es.XXX Wed Dec 3 06:23:29 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 03 Dec 2003 12:23:29 +0100 Subject: Python, xml, databases, ... References: <3fcdbd79@mail.netspeed.com.au> Message-ID: > I think you want to be clear whether you want a database or not. If you > want to put the data into a database, you probably do not want to also put > it into a file structure. Although you certainly could then store to file > in the database, I think you would end up loosing the usefulness of one or > the other (or both). > I think i prefer first to store the information in a file. And then see while the program is growing if it worth to use a database. > > What tool are suitable for this task? I have read somethin > > about MySQL and PostgreSQL, but i think they are only for servers, no > > for program, is that all right? > > What do you mean by 'they are only for servers'? > > Any machine can run a service (such as MySQL or PostgreSQL), and if it > offers that service to other machines then it is acting as 'server', or it > can just use it locally. Up, I concept missundertand of mine. I want to know if MySQL/PostgreSQL are only used in large web servers and such things, or are also used in small programs that both the server and client runs localy. > > What platform are you planning to run this on? If it is Linux, then either > MySQL or PostgreSQL are easy options - most distros have pre-compiled > versions out of the box. > I want to have the program in both linux and windows. > On Windows, both MySQL and PostgreSQL rely on the Cygwin dll. It looks like > MySQL has an easier Windows install, but their use of the cygwin dll > outside of Cygwin proper has serious stability consequences if the user > installs another cygwin based program. PostgreSQL is a 'proper' cygwin > program, but will be harder for non-unix/linux people to > install/administer. > > You could also consider Firebird (http://firebird.sourceforge.net/) it has a > native Windows version as well as a Unix/Linux version) or SQLite > (http://www.hwaci.com/sw/sqlite/) with PySQLite > (http://pysqlite.sourceforge.net/manual.html). > > There is also GadflyB5 (http://gadfly.sourceforge.net/) which looks like it > is written in pure python. There are probably other options too. > Can you give me an advaice about what has a better easy to use/performance ratio. > > I would build a GUI for the program (presumibly with wxPython). I want > > to separate the GUI layer from the program layer. For comunication of > > this two layer I have think in asyncore, but i have read something > > about twisted and piro. Can anyone give my his/her opinion about this? > > Funny, I asked almost the same question about 20 minutes before you did. I have no see the question yet :-) Cheers, zunbeltz > Cheers, > > Rasjid. > -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From see_signature__ at hotmail.com Sat Dec 13 22:09:22 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Sun, 14 Dec 2003 03:09:22 GMT Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: "hokiegal99" wrote in message news:3FDBC1B8.4010205 at hotmail.com... | s = string.find(fname, '.mp3') | if s >=1: I would say: if fname.lower().endswith( '.mp3' ): From matthew at barnes.net Fri Dec 19 12:36:11 2003 From: matthew at barnes.net (Matthew Barnes) Date: 19 Dec 2003 09:36:11 -0800 Subject: Parsing environment variables in ConfigParser files Message-ID: <3a8e83d2.0312190936.1746d659@posting.google.com> I'm considering submitting a patch for Python 2.4 to allow environment variable expansion in ConfigParser files. The use cases for this should be obvious. I'd like to be able to specify something like the following in a configuration file: [section_name] data_file=${HOME}/mydata.dat ...(where HOME=/home/matt) and have ConfigParser automatically expand it to: [section_name] data_file=/home/matt/mydata.dat The change is pretty straight-forward, but I'm interested in feedback on whether this is a good idea, what the syntax for environment variable references should look like (currently I'm thinking ${varname}), or whether there are any hidden complexities or backward-compatibility concerns. Matthew Barnes From jepler at unpythonic.net Wed Dec 31 17:50:48 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Dec 2003 16:50:48 -0600 Subject: ishexdigit() In-Reply-To: <5d83790c.0312311316.d301edb@posting.google.com> References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <4l05vvs0ril5a2lr35pp52vq98n990jmef@4ax.com> <5d83790c.0312311316.d301edb@posting.google.com> Message-ID: <20031231225048.GB26016@unpythonic.net> On Wed, Dec 31, 2003 at 01:16:22PM -0800, Raymond Hettinger wrote: > The category of Fastest Code is much less vague but tends towards > using fancy tricks: > > def ishexstring(s): > try: > int(s, 16) > except ValueError: > return False > return True >>> ishexstring("0xff") True ... but probably it doesn't fit the OP's definition Jeff From cpl.19.ghum at spamgourmet.com Fri Dec 12 17:09:00 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 12 Dec 2003 23:09:00 +0100 Subject: Kinda newb-ish question References: <5c27220b.0312111650.7f0a128d@posting.google.com> Message-ID: File "C:\Python23\Prime Number.py", line 8, in -toplevel- >> q=x%y > An infinite loop is probably not a good idea either. :-) Why should it not be a good idea? Are there any ideas that the number of primes is limited? :-) Harald From __peter__ at web.de Sun Dec 28 09:50:24 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 28 Dec 2003 15:50:24 +0100 Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> <3fee1d7d.350511859@news.blueyonder.co.uk> <3fee224a.65125244@news.iprimus.ca> Message-ID: Peter Otten wrote: > And now a sample session (note that I didn't bother to ensure a consistent > initial state): Read: _manually_ ensure a consistent state for the given _example_. The general case is definitely no toy problem. Also, beware of loops in the wiring. Peter From edreamleo at charter.net Thu Dec 11 11:26:06 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 11 Dec 2003 10:26:06 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: I have a lot of experience with both wxPython and Tkinter. I would urge caution regarding any quick judgments. All cross-platform toolkits have significant bugs and design flaws. My experience is that Tkinter is the "least bad" and more flexible. wxPython (of course) inherits all the _many_ bugs in wxWindows. It's not clear that wxWindows really actually works. Whenever I use wxPython/wxWindows I find more bugs in a week than I have found in 3+ years with Tk/Tkinter. YMMV. The (admittedly very cool) wxPython demo regularly segfaults on Windows. Sheesh. The main point is that some real experimentation (and risk!) is going to be required for any significant project. You may as well budget some time for frustration: it _is_ going to be there. Just one example of what you might expect. My app uses a Text widget in many non-trivial ways. Both Tkinter/Tk and wxPython/wxWindows have seemingly minor, but actually _major_ problems with Text widgets. Tk "helpfully" adds a newline at the end of text widgets in various situations, which leads to no end of complications in my app. I wish Tk would just _buzz off_ and not mess with my data. But noooooo. The wxWindows Text widget, OTOH, uses an absolutely brain-dead api that exposes platform-specific line endings. The complications become truly horrendous for serious work: there is no proper model behind Text offsets. Actually, both Tkinter and wxPython totally suck regarding offsets into text widgets. One would like integer offset in the text widget to be _identical in all respects_ with the integer offset into the Python strings that one passes to and receives from these widgets. But nooooooo... I call this the "cursed offset problem", which is really a special case of the "cursed newline problem" :-) In short, any cross-platform gui is going to cause you unexpected problems. I'm not saying "don't use these tools". I am saying: "be prepared for nasty surprises". Edward P.S. The idea that Tk is going to be "revitalized" any time soon is a yawner, IMO. Wake me up when it happens. EKR -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From Padraig at Linux.ie Tue Dec 2 05:40:24 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Tue, 02 Dec 2003 10:40:24 +0000 Subject: leftmost longest match (of disjunctions) ; greediness of "|" In-Reply-To: References: <3FCB7C0B.D4B844AE@engcorp.com> Message-ID: <3FCC6C18.7090209@Linux.ie> Joerg Schuster wrote: > Peter Hansen writes: > > >>produce a longer overall match. In other words, the "|" operator is never >>greedy. > > > O.k. Thanks for pointing this out. Maybe I should have formulated my > question differently: Is there a trick (be it dirty or not) to make > "|" greedy in python? sort the re by size first? P?draig. From matt at overlook.homelinux.net Wed Dec 3 15:05:09 2003 From: matt at overlook.homelinux.net (Matthew Wilson) Date: Wed, 03 Dec 2003 20:05:09 GMT Subject: How to share 3rd-party modules between 2.2 and 2.3? Message-ID: I have Red Hat 9 installed, which uses python2.2 for lots of system tasks. I also installed 2.3 using the rpms available from python.org. I want to write some CGI scripts that use pgdb. I want to write the python scripts using python2.3, but the pgdb.py file is in /usr/lib/python2.2/site-packages which is not part of sys.path in python2.3. What is the best way of sharing these modules? I don't want to add /usr/lib/python2.2/site-packages to my $PYTHONPATH variable because the apache user doesn't get a log in. I thought about adding a symbolic link to /usr/lib/python2.3/site-packages for every file in /usr/lib/python2.2/site-packages. Does anyone have a better idea? From vivek at cs.unipune.ernet.in Tue Dec 23 00:54:47 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Tue, 23 Dec 2003 11:24:47 +0530 Subject: font list on current OS In-Reply-To: <20031223040051.18883.qmail@web21322.mail.yahoo.com>; from quiteblack@yahoo.com on Mon, Dec 22, 2003 at 08:00:51PM -0800 References: <20031223040051.18883.qmail@web21322.mail.yahoo.com> Message-ID: <20031223112447.A23202@cs.unipune.ernet.in> On Mon, Dec 22, 2003 at 08:00:51PM -0800, black wrote: > Hi all~ > > Ooops when i was diving into Tkinter widgets just found no File Dialog available. It seems the best way is to make one by myself. but before do something with widgets I'd get font information on current OS, ie I'd collect all fonts available on system which running my code, anyone could show me and clue on how to achieve that ? > > Best best best Regards~ open the module docs (pydoc) and look at tkFileDialog. It provides you with various functions for opening file dialogs of different types. Regards Vivek Kumar From http Mon Dec 29 19:41:50 2003 From: http (Paul Rubin) Date: 29 Dec 2003 16:41:50 -0800 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> Message-ID: <7x1xqn16i9.fsf@ruckus.brouhaha.com> engsolnom at ipns.com writes: > > def ishexnumber(sx): > > import re > > if not re.match('[0123456789abcdefABCDEF]*$', sx): return 0 > > if len(sx) % 2 == 0: return 1 > > return 'Extra nibble' > If I run this many times, as is likely in our application, does the > 'import re' chew up memory? Importing the re module does use some memory, but it's the same amount of memory whether you call the function once or many times. Normally you'd put 'import re' at the top of the file that the function is defined in, by the way, rather than inside the function, but either way works. > Our strings will almost always be long ones, and the byte values will > range from zero to 255, but I'll tuck this nugget into the archive. This sounds like you almost certainly want to use the binascii module and not write your own function. From aahz at pythoncraft.com Fri Dec 5 16:25:28 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2003 16:25:28 -0500 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> <7xptf639rd.fsf@ruckus.brouhaha.com> <7xoeuq5sp2.fsf@ruckus.brouhaha.com> Message-ID: In article <7xoeuq5sp2.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> spamd is supposed to cache the network checks; perhaps it's not properly >> configured. > >I'm running tens of thousands of messages through it one after another. >It could really be that many distinct addresses. Maybe. OTOH, my ISP (Panix) uses SA for several thousand customers, so I'm sure they can't be taking 1.5 seconds per message. Either they're running much heavier hardware than you (unlikely, IMO) or they've got some config difference that makes it work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From ptmcg at austin.rr.com Wed Dec 24 08:57:10 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 24 Dec 2003 13:57:10 GMT Subject: global and None References: Message-ID: > Hmm, I hadn't thought of that. If this is a use case, aren't the > restrictions placed on global in the specs rather encumbering, and should be > removed? (Well, except for for-loop targets and formal parameters.) As it > is, to comply, you'd have to use a temporary name for construction, and then > assign to the global name. > -- > Francis Avila > ?Que? What needs to be changed? See the example code that I posted. This is exactly where "global" makes sense. -- Paul From dw-google.com at botanicus.net Sun Dec 14 14:13:33 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 14 Dec 2003 11:13:33 -0800 Subject: Shell quoting as part of the standard library? References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: <99dce321.0312141113.76a53fec@posting.google.com> "Francis Avila" wrote... > Why don't you just let the shell deal with it? > > ... > That is a very simple solution I have never seen used before. However, it does not solve my original problem. The solution as I have now been educated, is mkarg() from the commands module. Thanks, David. From emile at fenx.com Sat Dec 6 13:52:01 2003 From: emile at fenx.com (Emile van Sebille) Date: Sat, 6 Dec 2003 10:52:01 -0800 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> <30oAb.9577$aw2.4588872@newssrv26.news.prodigy.com> Message-ID: Robin Munn: > But take note that this behavior is not guaranteed anywhere in the language > reference. As someone else said in this thread, don't count on interning. > Sometimes it will happen, and sometimes it won't: > > >>> a = 'gobble' > >>> a is gobble > True > >>> b = 'foo bar' > >>> b is 'foo bar' > False > > The rule of thumb is that Python interns a string if it's likely to be used > as a name (i.e., only alphanumerics and underscores). The string 'foo bar' > has a space and would be an invalid name, so it wasn't interned. > And don't think you can get around it using intern(): Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 >>> b = intern('foo bar') >>> a = 'foo bar' >>> a is 'foo bar' False >>> b is 'foo bar' False That apparent space requirement should really be better documented. >>> b = intern('foo_bar') >>> b is 'foo_bar' True >>> a = 'foo_bar' >>> a is 'foo_bar' True >From the docs on intern(): "Interning strings is useful to gain a little performance on dictionary lookup " and while it continues: "...names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys" It probably should specifically state that only valid identifiers will be intern()'d and optionally return an error or warning otherwise. Emile van Sebille emile at fenx.com From danl_kramer at yahoo.com Fri Dec 19 21:55:29 2003 From: danl_kramer at yahoo.com (Daniel Kramer) Date: 19 Dec 2003 18:55:29 -0800 Subject: string parsing screwing up on large files? Message-ID: <75765317.0312191855.6ce6f4d2@posting.google.com> Hello, I'm fairly new to python but I've written a script that takes in a special text file (a renderman .rib to be specific).. and filters some of the commands. The .rib file is a simple text file, but in some cases it's very large.. can be 20megs or more at times. The script steps though each line looking for keywords and changes the line if nessisary but most lines just pass in and out of the script un-modified. The problem is sometimes the lines aren't written out correctly and it's an intermittent problem. If I re-run the script again on the same input usually it works fine. After filtering about 100 files i might get 4 or 5 that come out bad.. simply re-running those fixes them. Anyone know what I might look for? It's possible that the machine is under a lot of i/o load and/or cpu load when it happens, but not sure about that.. I normally send this processing to a render farm, so it's hard to predict exactly what sort of load is going on at that time. It feels like a buffer isn't getting flushed before the text is written out.. or something like that. Any suggestions where I might look? thanks daniel From seberino at spawar.navy.mil Mon Dec 15 13:47:26 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 15 Dec 2003 10:47:26 -0800 Subject: Anyone use ELSE minor-mode in Emacs? References: Message-ID: Peter Hello! Thank you very much for your detailed reply to my comp.lang.python post about ELSE. I downloaded the else-mode.el file and was able to load it. I'm having problems getting the Python template file loaded (Python.lse). Can I put this in my home directory and/or specify the path to it instead of placing it somewhere else? Can I load it from Emacs myself?? Also, Python doesn't have as much junk as C to type. Is ELSE still useful in Python since Python has no braces, semicolons, etc. that one needs to automate? Chris -- _______________________________________ Christian Seberino, Ph.D. SPAWAR Systems Center San Diego _______________________________________ "Peter Milliken" wrote in message news:... > I use it - but then I'm the author :-) > > I am hopeful that the "time to learn it" is very short. Probably the > quickest way to get to learn it is to use the "tokens" i.e. enable the > else-mode minor mode in a .py file and type in "def" and then run the > else-expand-placeholder command (C-c / e - this key encoding is "forced" on > Emacs minor mode authors by Emacs expansion conventions - I use F3 > personally :-)). and you should get the appropriate code structure. > Similarly, type in "classC-c / e" and you'll get a class structure. > > Then just "expand" every "placeholder" until you start to get a feel for > where it leads. If you stick with just the "tokens" at first, then you'll > quickly get an idea of what ELSE can do. Using "placeholders" follows fairly > naturally from token expansions. > > If you don't want to handle the menus etc of using placeholders straight off > the bat then that's no problem, just type directly into a placeholder and it > will disappear and get out of your face :-) > > Once you have used it for a while and (hopefully :-)) find it useful, then > perhaps venture into the users manual. I hope I have laid it out reasonably > well, so you can focus in on the areas that interest you. > > Please do not stay with the minor mode key-bindings as the idea of ELSE is > to reduce typing - having to type C-c / x all the time where "x" is "e, p, > n, or k" defeats the entire purpose - but those are the "rules" for minor > mode creators in Emacs :-) That is why the ELSE manual recommends that one > of the first priorities is the creating of a convenient key-binding. I use: > > F3 - else-expand-placeholder > F4 - else-next-placeholder > F5 - else-previous-placeholder > F6 - else-kill-placeholder > > I have a version of else-mode.el that has a command else-show-tokens - this > is useful to quickly see what "tokens" are available for expansion using > this mechanism. At the moment with the current released version of ELSE, you > have to browse the individual language file to see what strings are defined > as tokens. Token definitions are always at the end of the file, BTW :-) Let > me know if you want a copy of that version - I am behind a firewall at work, > so updating the web-site always has to wait for when I have the time to get > on the Internet at home - something that can take weeks to do sometimes :-) > > As a general rule, any "keyword" is defined as a token i.e. return, if, def, > try, while etc etc - try them to see what you get :-) It is very easy to > define your own "tokens" (shortcuts for want of a better term), the manual > describes all of this or you could just look at the language template files > for examples. > > > As for what it does for me - it saves me typing (use it properly and your > main coding experience is the entry of variable names etc) and with more > syntactically strict languages such as C etc it saves me having to type in > {}'s and ;'s :-) If you use ELSE for a language like C then you never get a > compiler error saying you have missed a } or a ; - surely a big time saving > :-) > > The whole idea behind ELSE is to save typing - which means higher > productivity and allows the programmer to focus on the problem at hand - > writing a program to meet a need. The programmer shouldn't be distracted > from the job at hand worrying about whether they got the language syntax > correct or not :-) > > Hope this helps, > > Peter > > > "Christian Seberino" wrote in message > news:bf23f78f.0312091603.f91c1e7 at posting.google.com... > > I am looking at the ELSE home page and trying to figure out if I should > > invest the time to learn about the ELSE minor mode for Emacs. > > > > Is there any programmer out there using ELSE that is getting great > > benefit from it? > > > > What does ELSE minor-mode for Emacs do that is so great for you? > > > > Chris From peter at engcorp.com Mon Dec 15 09:32:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Dec 2003 09:32:51 -0500 Subject: "Do this, and come back when you're done" References: <878ylges2u.fsf@vercingetorix.caesar.org> Message-ID: <3FDDC613.FCC2A155@engcorp.com> Valentino Volonghi aka Dialtone wrote: > > Kamus of Kadizhar writes: > > > Is there any way to rewrite each half of the function to run in the > > background, so to speak, and then have a master process that waits on > > the results? This would cut execution time in half more or less. > > Why don't you use twisted? It's a net framework with a lot of > protocols (and you can define your own ones) and it's based on async > sockets which let you write programs avoiding threads for most of the > times. > > www.twistedmatrix.com > > I'm sure you will find out that's the best thing ever done for python > :) I second that advice, and will also mention that it would avoid the sort of bug that I pointed out in your first post, involving the simplistic .recv(256) calls you are doing. Twisted would make the code much more readable *and* reliable. Well worth learning. If you're doing this just to learn Python, you could do worse than get it working with Twisted, then go poking into the Twisted internals to see how *it* works instead. -Peter From http Wed Dec 31 16:08:22 2003 From: http (Paul Rubin) Date: 31 Dec 2003 13:08:22 -0800 Subject: Project dream References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> <7xllotv8kq.fsf@ruckus.brouhaha.com> Message-ID: <7xllos8zll.fsf@ruckus.brouhaha.com> "Andrew Dalke" writes: > > There could be a wiki page somewhere with a list of interesting > > project suggestions. I'd put stuff there. I can think of all kinds > > of cool programs that I'd like for other people to write ;-). > > Well, isn't that the problem? I can think of quite a few as well. > (Again, all chemical and bio-informatics related.) But from > experience the odds of anyone else working on them is very low and > the effort spent on putting those ideas on a wiki, knowing that it's > almost certainly going to be ignored, makes it simply not worth it. Shrug. The GNU project has had a project list since the 80's. Some things stayed on it for many years and were eventually taken up by somebody. I think if someone asks for a project and you spend a bunch of time thinking one up on the spot, and then the person doesn't go anywhere with it, that's not so great. If you think up something on your own devices and put it on a list that thousands of people will look at, that's a bit more promising. From hs at bluepacific-technologies.com Sun Dec 14 17:10:50 2003 From: hs at bluepacific-technologies.com (SamX) Date: 14 Dec 2003 14:10:50 -0800 Subject: piddle Message-ID: <31e18870.0312141410.6d1d79ed@posting.google.com> Can some please tell me if PIDDLE can plot 3d (x, y, z) points on a canvas? This is to display airfoil cross-sections of a blade. Each section has x-y coordinates and a z coordinate. Hopefully one can rotate, pan and zoom the display. Or even better, the points can be connected by lines or even shade the surface of the blade so it appears solid. Thank you in advance. From imbosol at aerojockey.invalid Thu Dec 18 06:26:49 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 18 Dec 2003 11:26:49 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xzndqr94w.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > > "Greg Ewing (using news.cis.dfn.de)" writes: >> In this case, evaluating the default args at call time would >> have a negative payoff, since it would slow down every call to >> the function in cases where the default value doesn't need >> to be evaluated more than once. > > In those cases the compiler should notice it and generate appropriate > code to evaluate the default arg just once. In many of the cases it > can put a static value into the .pyc file. In a perfect world, that would be a good way to do it. However, Python is NOT in the business of deciding whether an arbitrary object is constant or not, except maybe in the parsing stages. Internally, it's just not built that way. If I were designing, I would definitely make it the language's (and extension writers') business, because there is a lot of opportunity for optimization. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From jepler at unpythonic.net Mon Dec 29 09:08:12 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Dec 2003 08:08:12 -0600 Subject: Best match searching In-Reply-To: References: Message-ID: <20031229140811.GE6171@unpythonic.net> Searching 600*400 values by simply going in order is going to take awhile. It's O(N), linear in the number of values. If your "array" is relatively unchanging, then you can store it in a different way so that searching takes much less time. I think that the method I'm going to describe is O(log N) complexity. You want to choose a tree representation for your data with the following property: at each node of the tree, there are N children, and each of the N children has approximately 1/N of the leaves below that node. Furthermore, there must be a simple test that will let you choose which of those children may hold the closest node under your distance measure. I think that one algorithm you could follow is described at http://www.cs.sunysb.edu/~algorith/files/kd-trees.shtml Beware that if you write your k-d trees in Python but compare to a linear search using numpy that effectively runs in C, the numpy approach may win on your example. But if the search space grows larger the tree approach will eventually win over a brute-force approach. Jeff From CousinStanley at hotmail.com Wed Dec 31 09:13:55 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 31 Dec 2003 07:13:55 -0700 Subject: Project dream References: Message-ID: | Suppose you have the time and the money to start a new project | in Python. | | What would you like to do ? Will .... You might spend some time checking the requests for programs at the Made-To-Order freeware site .... http://www.csn.ul.ie/~madman/software/order.htm There are enough requests there to keep a L A R G E army of coders busy for a very L O N G time .... -- Cousin Stanley Human Being Phoenix, Arizona From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 10 15:57:33 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 10 Dec 2003 21:57:33 +0100 Subject: ANN: Twisted 1.1.1 In-Reply-To: <8765gowgp7.fsf@mobile.foo> References: <8765gowgp7.fsf@mobile.foo> Message-ID: <3fd788bd$0$204$e4fe514c@news.xs4all.nl> Lawrence Oluyede wrote: > claird at lairds.com (Cameron Laird) writes: > > >> . >>Think about that last just a bit more. Asyncore is SUCH an >>upgrade over what most of the world is doing. > > > Can you explain "over what most of the world is doing" a bit more? > I'm seriuosly interested. [Perhaps a bit offtopic?:] While you're at it-- is there somewhere a *recent* tutorial on using asyncore/asynchat? Sam Rushing's one (found via Google) is from 1999... (I'm interested in using asyncore directly, not as part of a framework such as Twisted or Medusa). --Irmen. From uwe.schmitt at procoders.net Wed Dec 31 05:40:29 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 31 Dec 2003 10:40:29 GMT Subject: ishexdigit() References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <4l05vvs0ril5a2lr35pp52vq98n990jmef@4ax.com> Message-ID: Tim Roberts wrote: > Well, more Pythonish yet is to avoid the extraneous local variables, avoid > the use of a type as a parameter name, and use as many little-used builtins > as possible: ... > def ishexstring(strng): > return filter(ishexdigit, strng) == strng better/faster/more pythonic: return reduce(lambda a,b: a and ishexdigit(b), strng, True) Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From aahz at pythoncraft.com Fri Dec 19 22:36:59 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Dec 2003 22:36:59 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> Message-ID: In article , Michael Hudson wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> Michael Hudson wrote: >>>Gerrit Holl writes: >>>> >>>> So the Zen of Python shouldn't *be called* the Zen of Programming. >>> >>>No, it should be called "19 Pythonic Theses", which has the advantage >>>of being vaguely accurate... >> >> Actually, it should be called "20 Pythonic Theses", because that was >> Tim's original title. > >But there isn't a 20th thesis yet is there? I thought that was still >waiting on Guido... Yup. Doesn't change the title, though. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From eldada at mdstud.chalmers.se Wed Dec 17 05:23:33 2003 From: eldada at mdstud.chalmers.se (Ali El Dada) Date: Wed, 17 Dec 2003 11:23:33 +0100 Subject: OO issues in python Message-ID: hi all: in python, when a class, say Father, has a member that itself is an instance of another class, say Child, an instance of Father actually only has a reference to a Child, not the Child object itself, right? because i know that in eiffel they give the programmer the 2 options, the second being implemented with an additional keyword (expanded) so as the eiffel documentation says, "Consider the example of a class covering the notion of car. Many cars share the same originating_plant , but an engine belongs to just one car. References represent the modeling relation "knows about"; subobjects, as permitted by expanded types, represent the relation "has part", also known as aggregation. The key difference is that sharing is possible in the former case but not in the latter" the reason why i'm asking is that i want my Child() instance to know things about the parent without having to explicitly pass them as arguments. this is not working :( eg code that doesn't work: class Father: def __init__(self): self.a = 'foo' self.son = Child() class Child: def __init__(self): print f.a f = Father() thanks for any help.. Cheers, Ali Dada From __peter__ at web.de Sat Dec 6 04:00:53 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Dec 2003 10:00:53 +0100 Subject: question on HTMLParser and parser.feed() References: Message-ID: Stephen Briley wrote: > I am satisfied with the HTMLparse of my htmlsource > page. But I am unable to save the output of My guess is that in the long run you will be even more satisfied with the HTMLParser in the HTMLParser module - it has a cleaner interface and can handle XHTML. > parser.feed(htmlsource). When I type > parser.feed(htmlsource) into the interpreter, the > correct output streams across the screen. But all of > my attempts to capture this output to a variable are > unsucessful (e.g. capt_text = > parser.feed(htmlsource)). > > What am I missing and how can I get this to work? > Thanks in advance! > > > from htmllib import HTMLParser > from formatter import AbstractFormatter, DumbWriter > parser = HTMLParser(AbstractFormatter(DumbWriter())) > parser.feed(htmlsource) You can provide a file object to the dumbwriter object to write the formatter output to a file: outstream = file("tmp.txt", "w") parser = HTMLParser(AbstractFormatter(DumbWriter(outstream))) parser.feed(htmlsource) outstream.close() When you don't want to store the output you can instead provide a StringIO instance that behaves like a file, but does not store anything on disk: # cStringIO contains the faster version of StringIO from cStringIO import StringIO from htmllib import HTMLParser from formatter import AbstractFormatter, DumbWriter htmlsource = """ Hello world For demonstration purposes """ outstream = StringIO() parser = HTMLParser(AbstractFormatter(DumbWriter(outstream))) parser.feed(htmlsource) data = outstream.getvalue() outstream.close() # your code here, I just print it in uppercase print data.upper() Peter From ajsiegel at optonline.com Thu Dec 25 19:24:22 2003 From: ajsiegel at optonline.com (Arthur) Date: Fri, 26 Dec 2003 00:24:22 GMT Subject: 2.3 list reverse() bug? References: Message-ID: <26vmuvooh62ko48t7m8n2cumg0se7dd7v5@4ax.com> > >Try reading this: > > http://starship.python.net/crew/mwh/hacks/objectthink.html Not easy sledding IMO. But one get's there. The post that instigated the tutorial asks the question when surprised by some behavior along the lines of this thread: """ Who is wrong here: my intuition or Python (2.2)? """ I would say,neither. It is as it is, let's assume for excellant reason, Which doesn't mean it is necessarily what one's naive intution first expects. But the response: """ Almost needless to say, it was the poster's intuition that was at fault, but he is (was) far from unique in having this sort of misconception. """ frankly bothers me a bit, though it is understandable somewhat in the context of the phrasing of the posters question. Generally speaking, it is hard to understand how someone's intutition can be flawed. It's just an "is". That the programming language might do slight damage to one's naive intution is not either the fault of the programming language. Something perhaps simply needs to be learned. Once learned, one's intuition is happly overridden - no hard feelings. Art > >Happy Christmas everyone! > >Cheers, >mwh From g2h5dqi002 at sneakemail.com Sun Dec 7 22:36:05 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Mon, 08 Dec 2003 16:36:05 +1300 Subject: Lists and Tuples In-Reply-To: References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > mwilson at the-wire.com (Mel Wilson) writes: > >> To me, it's a distinction without a difference. Tuples >>*act* like immutable sequences, and I use them that way. I >>don't know, though, that I won't get caught some day. > > You'll be fine. The only thing you have to watch out for is that some > rude folks here might call you names. That would add some spice to Python's error messages... Python 3.7 (#1, Sep 31 2007, 14:19:37) [GCC 5.6.7] on slartibartfast Type "help", "copyright", "credits" or "license" for more information. >>> t = (1, 3, 77, 654, 8) Traceback (most recent call last): File "", line 1, in ? HumiliationError: The programmer is a pink-faced baboon (tuple used where list would be more appropriate) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From exarkun at intarweb.us Tue Dec 30 17:16:32 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 30 Dec 2003 17:16:32 -0500 Subject: twisted mail server - SMTP AUTH extension not supported In-Reply-To: References: Message-ID: <20031230221632.GB15706@intarweb.us> On Tue, Dec 30, 2003 at 11:05:53AM -0800, Mark Carter wrote: > I'm trying to create a mail server in Twisted. > > I either get > SMTPSenderRefused > or > SMTPException: SMTP AUTH extension not supported by server. > > What do I need to do to get it to work? > > > --- Here is the server: > > from twisted.internet import reactor > > from twisted import mail > import twisted.mail.mail > import twisted.mail.maildir > > service = mail.mail.MailService('ExampleMail') If you want unauthenticated users to be able to send mail, you need to explicitly allow it. from twisted.cred import checkers service.smtpPortal.registerChecker(checkers.AllowAnonymousAccess()) > smtp = service.getSMTPFactory() SMTP AUTH is really part of ESMTP. Try service.getESMTPFactory() instead of service.getSMTPFactory(). > pop3 = service.getPOP3Factory() > > domain = mail.maildir.MaildirDirdbmDomain(service, '/temp') > domain.addUser('salvador', 'gala') > service.addDomain('dali', domain) > > reactor.listenTCP(25, smtp , interface='dali') > reactor.listenTCP(110, pop3 , interface='dali') > > reactor.run() > Also, note that the above code accomplishes roughly the same thing as the following command line: mktap mail --maildirdbmdomain dali=/temp --default \ --user salvador=gala \ --pop3 110 --smtp 25 If you just want a mail server, using the command line is probably better. If you need more flexibility than it can offer, sticking with code is the right choice. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From sebastien.giraud at eds.com Fri Dec 19 03:53:40 2003 From: sebastien.giraud at eds.com (Giraud, Sebastien) Date: Fri, 19 Dec 2003 08:53:40 -0000 Subject: Newbie Question HELP! Message-ID: You have two way to exec python files : put your python.exe directory in your path and exec python scripts or making a *.exe with MacMillian or Py2exe tools. -----Message d'origine----- De : python-list-bounces+sebastien.giraud=eds.com at python.org [mailto:python-list-bounces+sebastien.giraud=eds.com at python.org] De la part de TyBriD Envoy? : vendredi 19 d?cembre 2003 09:40 ? : python-list at python.org Objet : Newbie Question HELP! hello guys i am new top programming and was told python is the best place to start i so far understand variables ex: print ("Fill In Below") name = raw_input("Enter Your Name Please: ") age = input("Enter Your Age Please: ") print "Your Name Is", name print "Your Age Is", age but i was wondering if there was a way to compile a EXE file to display the print because this only seems to run in python shell, or is there a way to create my own interface for my program in python thanks in advanced -- http://mail.python.org/mailman/listinfo/python-list From ville.spammehardvainio at spamtut.fi Fri Dec 12 08:14:08 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 12 Dec 2003 15:14:08 +0200 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> <87r7za2a6a.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Now, if he'll just publish that in a glossy magazine and make > asynchronous network programming fashionable... then half of all FWIW, in Symbian pretty much every program is single threaded, w/ comms and such handled by asynchronous "Active Objects" and "Active Scheduler" that execs the RunL method of Active Object when the object has stuff to do. This is mostly done to save resources, allegedly. -- Ville Vainio http://www.students.tut.fi/~vainio24 From http Sat Dec 13 02:46:54 2003 From: http (Paul Rubin) Date: 12 Dec 2003 23:46:54 -0800 Subject: ANN: lunatic-python 0.1 References: Message-ID: <7xd6atgnwx.fsf@ruckus.brouhaha.com> Gustavo Niemeyer writes: > What is it? > ----------- > > Lunatic Python is a two-way bridge between Python and Lua, allowing > these languages to intercommunicate. Being two-way means that it > allows Lua inside Python, Python inside Lua, Lua inside Python > inside Lua, Python inside Lua inside Python, and so on. > > Where to get it? > ---------------- But you left out the most important question: WHY? From tgill at sincom.com Tue Dec 2 22:12:27 2003 From: tgill at sincom.com (Ted Gill) Date: Wed, 03 Dec 2003 03:12:27 -0000 Subject: Weird idle behavior for GUI apps Message-ID: Platform: Windows ME Python version: 2.3.2-1 Problem: Running GUI apps in Idle does not work. When executing GUI (tkinter/pmw) apps from the edit windows or doing an "import " in the shell window GUI apps freeze and do not respond to internal widgets or window decoration. They also do not repaint. Only way to bail out is to restart the interpreter. Same apps work fine from DOS window or double-clicked in file manager. These apps also still work in Python 2.2 environment (still installed) Character-based apps seem to work fine. Anyone seen this before? TIA, Ted Gill From bill at rfa.org Sun Dec 28 13:00:00 2003 From: bill at rfa.org (Bill Eldridge) Date: Sun, 28 Dec 2003 19:00:00 +0100 Subject: Unicode from Web to MySQL In-Reply-To: References: Message-ID: <3FEF1A20.10407@rfa.org> Serge Orlov wrote: >>It seems the mixed language is throwing stuff off, which wouldn't >>bother me if my re.search for only the Vietnamese text were working >>properly, but it isn't. >> >> > >Why? re.search works fine for my Russian unicode characters. > > > Yes, it seems and should be very easy and straight-forward, do not know why, will have to spend more time on it. From tjreedy at udel.edu Mon Dec 29 00:02:30 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2003 00:02:30 -0500 Subject: [puzzle] References: <3fef8612$0$117$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: "Anton Vredegoor" wrote in message news:3fef8612$0$117$3a628fcd at reader2.nntp.hccnet.nl... I don't know what 'Glen Wheeler's problem' is, what your 'antonian' numbers are, what 'ISTMT' abbreviates, nor precisely what 'sorted reflected' means to your without an example, so I won't try to solve your puzzle. I will just comment on the class definition. > class AntonianSorted: > > def __init__(self, n, k): > self.limits = [k for i in range(n)] > self.state = [] > self.iterator = self.__gen__() > > def __iter__(self): return self > def next(self): return self.iterator.next() The generation will go faster if you delete the above three line and change 'gen' to 'iter' in the next. > def __gen__(self): > state, limits = self.state, self.limits > while 1: > if len(state) < len(limits): > state.append(0) > else: > i = len(state)-1 > while i > 0 and state[i] == limits[i]-1: > state.pop() > i -= 1 > if state[i] < limits[i]-1: > state[i] += 1 > else: > raise StopIteration > yield state[:] Making __iter__ itself a generator function (which returns an iterator, as __iter__ should) is the smoothest way to use generators with classes. Wrapping genit.next with a regular function undoes perhaps half the speed benefit of generators. They are fast partly because they do not have to stash and retrieve local in the instance and partly because they resume without the normal (slow) function call process. Writing __iter__ as generator also make the instance reiterable. In this case, I do not see any reason to wrap the generator in a class instead of calling it directly, but perhaps you have a usage in mind where persisting the instance after the generator run makes sense. Terry J. Reedy From skip at pobox.com Fri Dec 5 12:10:34 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Dec 2003 11:10:34 -0600 Subject: Lists and Tuples References: Message-ID: <16336.48138.657660.174163@montanaro.dyndns.org> (Probably more response than you wanted. I kind of got carried away...) >> I've spent most of the day playing around with lists and tuples to >> get a really good grasp on what you can do with them. I am still left >> with a question and that is, when should you choose a list or a >> tuple? Generally, choose between tuples and lists based upon your data. In situations where you have a small, fixed collection of objects of possibly differing types, use a tuple. In situations where have a collection of objects of uniform type which might grow or shrink, use a list. For example, an address might best be represented as a tuple: itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201") caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866") Though all elements are actually strings, they are conceptually different types. It probably makes no sense to define itcs as itcs = ("2020 Ridge Avenue", "60201", "IL", "Evanston") If you are reading test scores from a file, you'd likely accumulate them into a list: scores = [] for line in file("foo"): scores.append(float(line.strip())) then operate on them as a group, possibly normalized to the list's length: nscores = len(scores) mean = sum(scores)/nscores variance = sum([(n-mean)**2 for n in scores])/nscores print "Mean:", mean print "Variance:", variance Unlike tuples, it's often perfectly reasonable to reorder lists without any loss of meaning: scores.sort() print "Min:", scores[0] print "Max:", scores[-1] print "Median:", scores[nscores/2:nscores/2+1] Think of lists as arrays and tuples as Pascal records or C structs and you'll probably choose correctly most of the time. If you want to associate methods with your tuples (similarly for lists), you should probably define a class instead: import latlong class Address: def __init__(self, street, city, state, zip): self.street = street self.city = city self.state = state self.zip = zip def distance(self, other): return latlong.cdistance("%s, %s" % (self.city, self.state), "%s, %s" % (other.city, other.state)) itcs = Address("2020 Ridge Avenue", "Evanston", "IL", "60201") caffe_lena = Address("47 Phila Street", "Saratoga Springs", "NY", "12866") print itcs.distance(caffe_lena), "miles" For the curious, when run, the above prints: 961.976657911 miles Looks like I won't be attending a concert at Caffe Lena tonight. (latlong is a module I wrote for use in the Mojam and Musi-Cal websites but never released publically.) Skip From vxg49 at yahoo.com Wed Dec 17 22:31:56 2003 From: vxg49 at yahoo.com (Fred Murray) Date: Thu, 18 Dec 2003 03:31:56 GMT Subject: Handling states with HTTP Message-ID: Hi all, I've been looking around for a utility that will let me do something like this: while 1: # Ask user for username and password username, password = user_session.form_input(LOGIN_SCREEN) # If username is invalid, warn user and ask again if username not in users: user_session.print(INVALID_USERNAME) continue # If password is invalid, warn user and ask again if users[username] != password: user_session.print(INVALID_PASSWORD) continue # If username and password match, then break out of loop break # (code to log in user goes here...) In other words, I'm looking for a package that will use cookies or CGI variables to save the state of the program in between HTTP requests. Packages like Albatross seem to require class definitions for each page, which isn't as natural or convenient as treating an HTML form as an input function (like raw_input()). If anyone knows if anything like this is available, thanks for letting me know! From bkelley at wi.mit.edu Thu Dec 11 17:13:42 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 11 Dec 2003 17:13:42 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: <7xhe0781tc.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> Message-ID: <3fd8ebbe$0$573$b45e6eb0@senator-bedfellow.mit.edu> Paul Rubin wrote: > Bruno Desthuilliers writes: > >>>I guess >>>I can get the client to pay >> >>Why ? It's free (as in free beer and free speech) > > > I mean for the build tools (Visual C++ or whatever). I can't really > use the WxWindows source code without a way to compile it. I'm getting > discouraged to hear that WxWindows itself has numerous bugs though. I think that these might be a bit overblown. I have released some medium-scale academic research packages to beta-testers using wxPython and have had no problems so far. There are about 150 installations so far at ten different sites. I have had more problems with different installation styles of microsoft excel than I have had with supporting wxPython bugs. Your mileage may vary however, and I certainly don't use all the widgets (read textctrl). The largest hurdles are with differences between windows/linux and mac, but I have experienced similar differences with Tkinter. Not for the GUI itself but with dealing with the clipboard etc. You may get different behavior on different platforms so debugging on those platforms is a must. I've been luck so far and the documentation is pretty good. I have seen wxPython crashes during development but they all have to do with errors in the constructors of subclassed widgets. If you raise an exception in a constructor before calling the baseclass' __init__ function wxPython get's very unhappy and dies miserably taking everything down. Two solutions/workarounds are 1) always call the subclassed constructor first 2) use a try...except block where call the base __init__ with default arguments and raise an event that will close down the app nicely. I haven't been able to figure out a way to do this automatically on constructor errors yet. If I could I would submit it to wxPython. If you are running on windows or redhat linux, you won't need to build wxPython/wxWindows, you can just download and install the binaries. If you want to build wxPython/wxWindows by yourself you will just need Visual C++. Brian From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 23 18:38:08 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 24 Dec 2003 00:38:08 +0100 Subject: OT: Why -g when compiling In-Reply-To: <4f0a9fdb.0312231526.394a518e@posting.google.com> References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: <3fe8d1e0$0$329$e4fe514c@news.xs4all.nl> Miki Tebeka wrote: > >>Disk space is cheap. > > Yes but memory sometimes isn't. On my cygwin installation the > libpython2.3.dll goes from 2.9MB to 1.1MB. On machines with little RAM > (embdded ...) this matters a lot. Use strip after a compile? --Irmen From jjl at pobox.com Mon Dec 15 08:36:17 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Dec 2003 13:36:17 +0000 Subject: minidom and pulldom References: <877k0yhq6f.fsf@pobox.com> Message-ID: <878yle8apa.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: [...] > Didn't this get answered just the other day? [...] Whoops, local news trouble, I guess. John From gerrit at nl.linux.org Wed Dec 3 07:23:36 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 3 Dec 2003 13:23:36 +0100 Subject: Random traceback In-Reply-To: References: Message-ID: <20031203122336.GA3434@nl.linux.org> user at domain.invalid wrote: > Is there any condition that would cause the following traceback: > ++++++++++++++++++++ > Traceback (innermost last): > File "/tmp/multimeter.py", line 157, in ? > myLogger.logMessage(message) > File "/tmp/Logger.py", line 46, in logMessage > self.__logToSyslog__(message) > File "/tmp/Logger.py", line 85, in __logToSyslog__ > syslog.syslog("%s" %reading) > TypeError: [priority,] message string > ++++++++++++++++++++ It seems like message is not a string... yours, Gerrit. -- 141. If a man's wife, who lives in his house, wishes to leave it, plunges into debt, tries to ruin her house, neglects her husband, and is judicially convicted: if her husband offer her release, she may go on her way, and he gives her nothing as a gift of release. If her husband does not wish to release her, and if he take another wife, she shall remain as servant in her husband's house. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From js at cis.uni-muenchen.de Mon Dec 8 08:02:43 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 08 Dec 2003 14:02:43 +0100 Subject: Quantify over all functions of a module Message-ID: Hello, I want to refer to all functions of a module, say test2.py, without having to manually enumerate them. The following code comes closest to what I am trying to do. It does not work, because dir() does not return functions, but function names as strings. ##### test2.py ##### def plus_2(_int): return _int + 2 def plus_3(_int): return _int + 3 #### test.py ##### #!/usr/bin/env python import re import test2 func_list = [] for func in dir(test2): test = re.search("^__", func) if not test: func_list.append(func) for func in func_list: print apply(func, (2,)) I failed to find a solution by searching the net, probably because I didn't know the right keywords. And I suppose that searching would not be necessary, if I knew the right keywords. J?rg From torppa at staff.megabaud.fi Sat Dec 13 14:32:50 2003 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Sat, 13 Dec 2003 19:32:50 +0000 (UTC) Subject: Very slow opening of client connections to localhost with httplib References: <8ce71920.0312120951.4c49b061@posting.google.com> Message-ID: In article <8ce71920.0312120951.4c49b061 at posting.google.com>, Martin Fuzzey wrote: > I am using xmlrpclib (based on httplib) in Python 2.3 on Mandrake > Linux. > > When my client attempts to connect to a server using a > "http://localhost:port" style URL there is a long delay before the > connection is established (it finally works). ... > import socket > socket.getaddrinfo("localhost", 10000, 0, socket.SOCK_STREAM) > > and sure enough it blocked for several seconds before finally > returning 127.0.0.1 > > If I remplace the 0 in the getaddrinfo call above by socket.AF_INET > all is fine as well. Try adding ::1 localhost to your /etc/hosts Or delete IPv6 from your kernel. -- Jarkko Torppa, Elisa Internet From prouleau at impathnetworks.com Wed Dec 10 14:24:34 2003 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Wed, 10 Dec 2003 14:24:34 -0500 Subject: Is there a portable way to retrieve the local host subnet mask? Message-ID: Hi all, socket.gethostbyname_ex(socket.gethostname()) will return the list of IP addresses on a the local host. I did not find any function that can be used to get the subnet mask and default gateway. Under Win32, the Win32 IP helper API provides a GetIpAddrTable() function that returns information that contain the subnet mask, but that's Win32 level, and is not portable. Is there something available in the Python library for that purpose? Thanks Pierre From bokr at oz.net Wed Dec 24 14:49:38 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Dec 2003 19:49:38 GMT Subject: Lanching application References: <%F6Eb.10980$Bl7.7345@news.cpqcorp.net> Message-ID: On 23 Dec 2003 08:30:55 -0800, rob02omni at vodafone.it (Roberto) wrote: >Hi Bengt, > >> >> >>> import os >> >>> def startit(path): os.system('start %s' %path) >> ... > >well not really... > >Notepad is natively a multi-session program i mean it can run any >number of itself cleanly. > >What i'm trying to accomplish is to launch an application that is not >"multi-session". I know that this is possible (tricks in the >process/applications threads) but i dont know how :) > >Any idea?? I'm not sure what you mean by "natively multi-session." ISTM that's the default. If an OS normally launches programs in separate processes, UIAM the programs have to be programmed specifically to _prevent_ running simultaneously. Various tricks can be used to accomplish that, so if you have a program that "is not multi-session" because it is successfully noticing that it is not the first instance to run, and exiting (some might communicate parameters to the running instance before they do that), then ISTM you are asking how to interfere with that program logic. E.g., if it is mutex-based, can you prevent the second instance from seeing the mutex? What if it's based on a lock file, or scanning current windows for title text? If there's a DLL using a shared memory section to act as a mutex, maybe there's a way (OTTOMH I don't know of it, but I wouldn't be surprised. I haven't had to deal with that situation) to tell windows always to create new instances of shared sections for it, and maybe that's what you are asking, but then you'd have to know that that's the mechanism that makes your app "single session." Maybe telling us what app are you trying to launch multiple instances of, and on what windows version would get more helpful responses? ;-) Happy Holidays, Regards, Bengt Richter From timothy.williams at nvl.army.mil Thu Dec 11 12:15:04 2003 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 11 Dec 2003 09:15:04 -0800 Subject: tkFileDialog.askopenfilenames not regonizing -multiple option References: Message-ID: timothy.williams at nvl.army.mil (Tim Williams) wrote in message news:... > I installed Tcl/Tk 8.4.5 and now I'm having a problem installing > Python 2.3.2: > > ######################################## > ranlib libpython2.3.a > c++ -pthread -Xlinker -export-dynamic -o python \ > Modules/python.o \ > libpython2.3.a -lpthread -ldl -lutil > -L/vps/pkg/Linux/lib -ltk8.4 -ltcl8.4 -lm > libpython2.3.a(posixmodule.o): In function `posix_tmpnam': > /vps/pkg/Linux/src/Python-2.3.2/Modules/posixmodule.c:5781: the use of > `tmpnam_r' is dangerous, better use `mkstemp' > libpython2.3.a(posixmodule.o): In function `posix_tempnam': > /vps/pkg/Linux/src/Python-2.3.2/Modules/posixmodule.c:5736: the use of > `tempnam' is dangerous, better use `mkstemp' > case $MAKEFLAGS in \ > *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG > -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ > *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g > -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ > esac > ./python: error while loading shared libraries: libtk8.4.so: cannot > open shared object file: No such file or directory > make: *** [sharedmods] Error 127 > > > ############################### > I found a post with this problem. After I modified LD_LIBRARY_PATH, everything is fine. From jepler at unpythonic.net Mon Dec 22 16:39:01 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 22 Dec 2003 15:39:01 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <16359.24377.5101.789601@montanaro.dyndns.org> References: <21bb8d55.0312221204.51d86182@posting.google.com> <16359.24377.5101.789601@montanaro.dyndns.org> Message-ID: <20031222213900.GC24252@unpythonic.net> On Mon, Dec 22, 2003 at 03:16:41PM -0600, Skip Montanaro wrote: > How about: > > def howmanyatstart(s, pfx): > return (len(s) - len(s.lstrip(pfx)))/len(pfx) > > ? This works for prefixes which are longer than a single character: > > >>> howmanyatstart(">>>>message1", '>') > 4 > >>> howmanyatstart("bobbobbob>>>>message1", 'bob') > 3 strip() doesn't work that way: >>> "bbbbbbbxxx".strip("bob") 'xxx' From http Tue Dec 30 07:41:11 2003 From: http (Paul Rubin) Date: 30 Dec 2003 04:41:11 -0800 Subject: Newbie: sort list of dictionaries References: Message-ID: <7xy8su7a1k.fsf@ruckus.brouhaha.com> Sven Brandt writes: > I have a list of dictionaries. I want the elements of the list to be > sorted by the value of a key of the dict . > > Excample: > my_list=[{'title': 'foo', 'id': 5, 'text': 'some text'}, > {'title': 'bar', 'id': 3, 'text': 'my text'}, > {'title': 'bla', 'id': 6, 'text': 'any text'}, ] > > my_list.sort("by the id value") The Pythonic way to do it may not be what you're used to, but once you understand it you'll be able to apply the understanding to other areas of programming. The list sort method lets you pass an optional comparison function, that takes two items and returns -1, 0, or 1, depending on what order the items are supposed to appear in. The comparison function takes exactly two args (the items to be compared). You can't pass a third arg to specify the field name. You could do something ugly like use a global variable, but the preferred way given a field name is to construct a brand new comparison function just for that name: def compare_by (fieldname): def compare_two_dicts (a, b): return cmp(a[fieldname], b[fieldname]) return compare_two_dicts What's that? Two nested function definitions. The outer function, compare_by, creates a new function called compare_two_dicts, which compares specifically based on the field that you passed to the outer function. compare_by then returns the new function, that's right, functions are values in Python! You can then can pass the new function to the sort method: my_list.sort (compare_by ('id')) And my_list is then properly sorted: [{'text': 'my text', 'id': 3, 'title': 'bar'}, {'text': 'some text', 'id': 5, 'title': 'foo'}, {'text': 'any text', 'id': 6, 'title': 'bla'}] From bokr at oz.net Mon Dec 29 17:12:16 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Dec 2003 22:12:16 GMT Subject: Some optimization tale References: Message-ID: On Sat, 27 Dec 2003 15:23:34 -0500, "Terry Reedy" wrote: > >"Stephan Diehl" wrote in message >news:bskcb0$36n$00$1 at news.t-online.com... >> All of this can be found at >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252177 >> >> What I was most surprised at was the inefficency of the trivial solutions >> (and that the right algorithm makes indeed a difference). > >A common surprise. The science of algorithms (including empirical testing) >gives real benefits. > >> -- >os.path.commonprefix -------------------------------------------------- >> >> def f1(m): >> "Given a list of pathnames, returns the longest common leading >> component" >> if not m: return '' >> prefix = m[0] > > prefix = m.pop() # avoids comparing prefix to itself as first item > >> for item in m: >> for i in range(len(prefix)): >> if prefix[:i+1] != item[:i+1]: > >I am 99% sure that above is a typo and performance bug that should read > if prefix[i:i+1] != item[i:i+1]: >since all previous chars have been found equal in previous iteration. > >> prefix = prefix[:i] >> if i == 0: >> return '' >> break >> return prefix > >Perhaps you could retest this with the two suggested changes. It will be >somewhat faster. > >> The problem with this algorithm is the copying of all those small >strings. > >Since Python does not have pointers, comparing characters within strings >requires pulling out the chars as separate strings. This is why using >C-coded comparison functions may win even though more comparisons are done. > >The reason f1uses slicing (of len 1 after my correction) instead of >indexing is to avoid exceptions when len(item) < len(prefix). However, all >the +1s have a cost (and I suspect slicing does also), so it may pay to >truncate prefix to the length of item first. The simplest fix for this >(untested) gives > >def f9(m): # modified f1 == os.path.commonprefix > "Given a list of strings, returns the longest common prefix" > if not m: return '' > prefix = m.pop() > for item in m: > prefix = prefix[:len(item)] > for i in range(len(prefix)): > if prefix[i] != item[i]: > if not i: return '' > prefix = prefix[:i] > break > return prefix > >> This can be easily fixed >> --- optimized >os.path.commonprefix ---------------------------------------- >> >> def f2(m): >> "Given a list of pathnames, returns the longest common leading >> component" >> if not m: return '' >> if len(m) == 1: return m[0] >> prefix = m[0] >> for i in xrange(len(prefix)): >> for item in m[1:]: >> if prefix[i] != item[i]: >> return prefix[:i] >> return prefix[:i] > >and easily messed up;-) If len(item) < len(prefix), item[i] throws >exception. For this approach to work, prefix should be set as shortest >string of m in preliminary loop. Also, you reslice m several times. Do it >once before outer loop. > >> It is just not nessesary to compare all strings in the list. > >Every string has to be compared to something at least once. > >> It is enough to sort the list first >> and then compare the first and the last element. > >Sorting compares all strings in the list to something at least once, and >most more than once. > >> Even though the 'sort' algorithm is coded in C and is therefore quite >fast, >> the order of runtime has changed. > >The C part is what makes f3 faster. In your timings, 128 is not large >enough for the nlogn component to be noticeable. > >> Michael Dyck then pointed out that instead of using 'sort', 'min' and >'max' >> should be used. While tests suggest that this is true, I have no idea why >> that should be, since finding a minimum or maximum uses some sorting >anyway > >No. max and min each do a linear scan. No sorting. But each does at >least as many character comparisons as modified f1 or f2. The speedup is >from looping and comparing in C, even though at least twice as many >compares are done. > >> You might have realized that the optimization so far was done one the >number >> of strings. There is still another dimension to optimize in and that is >the >> actual string comparing. >> Raymond Hettinger suggests using a binary search: > >Since this only affects the final comparison of min and max, and not the n >comparisons done to calculate each, the effect is minimal and constant, >independent of number of strings. > >Since this compares slices rather than chars in each loop, I wonder whether >this is really faster than linear scan anyway. I would like to see timing >of f5 with min/max of f4 combined with linear scan of f3. (Basically, f3 >with sort removed and min/max added.) Since you changed two parts of f3 to >get f4, we cannot be sure that both changes are each an improvement even >though the combination of two is. > >def f5(seq): > if not seq: return '' > s1 = min(seq) > s2 = max(seq) > n = min(len(s1), len(s2)) > if not n: return '' # not required since s1[0:0] == '' > for i in xrange(n) : > if s1[i] != s2[i] : > return s1[0:i] > return s1[0:n] > I wonder about this version for speed (not very tested ;-): >>> def f10(m): ... "return longest common prefix of strings in seq" ... if not m: return '' ... prefix = m.pop() ... ssw = str.startswith ... for item in m: ... while not ssw(item, prefix): prefix = prefix[:-1] ... if not prefix: return '' ... return prefix ... >>> f10('abcd abcd'.split()) 'abcd' >>> f10('abcd abce'.split()) 'abc' >>> f10('abcd abcd a'.split()) 'a' >>> f10('abcd abcd a x'.split()) '' Regards, Bengt Richter From jepler at unpythonic.net Sun Dec 28 18:09:32 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 28 Dec 2003 17:09:32 -0600 Subject: Special-purpose extension of Python -- new kinds of objects In-Reply-To: <6714766d.0312281442.78cd0a4b@posting.google.com> References: <6714766d.0312281442.78cd0a4b@posting.google.com> Message-ID: <20031228230932.GA22641@unpythonic.net> There have been lots of discussions on how to add domain-specific extensions to Python. You would do well to read these threads somewhere like google groups, they're relevant to the topic at hand. In your case, you could re-cast the "decision network" in terms of class definitions, and get pretty similar behavior if those classes have the right behavior in metaclasses: class my_example(DN): class X(Chance): cpd = gaussian(mean=25, std_dev=75) class Y(Chance): cpd = gaussian(mean=12, std_dev=19) Z = X + Y using the class statement, you can create a namespace with some values in it, and then do some processing of those values (for instance, to precompute the .nodes values). If you're very fond of your syntax, then consider using strings as the easiest way. Docstring abuse has been seen before, and would look something like this: class my_example(DN): """ chance X: cpd: gaussian [mean: 25, std_dev: 75] chance Y: cpd: gaussian [mean: 12, std_dev: 19] chance Z = X + Y """ either using docstrings or an external file, you'll need a parser. There is a languishing PEP about exposing the Python parser generator to Python code, so that you could write your own grammar with the same level of power as Python's grammar. There are lots of other package, such as yapps and spark which are also suitable for writing parsers. Once you have a parser and use external files, it's possible to extend Python's import system to load files of your type automatically with the import statement. This is an advanced topic, though. Jeff From raims at dot.com Sat Dec 13 09:54:36 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 13 Dec 2003 15:54:36 +0100 Subject: python2.3 upgrade References: <87ekv8vl39.fsf@mobile.foo> <5FFCb.88560$AX1.3685023@news1.tin.it> Message-ID: <87ad5wvkcz.fsf@mobile.foo> tudor writes: > I have pygtk-1.99 which I guess is too old.... > But I don't think I'm gonna find rpms for my rh8 of the new pygtk, so I'll > have to renew the whole gtk2 ! which kinda sounds scarry to me... I meant that you have to reinstall pygtk on the 2.3 distro... maybe you let it on the old one. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From rstephens at vectron.com Wed Dec 24 19:44:06 2003 From: rstephens at vectron.com (Ron Stephens) Date: 24 Dec 2003 16:44:06 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: "Russell E. Owen" wrote in message news: > > Well, I'm not sure how serious the problem actually is. I may have > overstated it. Hoping to hear soon. ... ... > Summary: both aqua and X11 versions of Python are working well for me. > > -- Russell Well, to summarize my experience, I have never had a Python problem on Mac OS X that wasn't related to a GUI in one way or another; and I have less of those issues on Panther (10.3) than on previous versions; and none of the issues was ever serious enough to make me regret for a moment using Mac OS X. Having the Unix command line shell available along with the nice Aqua user interface is really a treat, and most of my Python use is for command line stuff anyway. Now that I have both wxPython and Tkinter working acceptabley on Panther, I am happy indeed. ;-))) Ron Stephens From gerrit at nl.linux.org Wed Dec 17 07:28:21 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 17 Dec 2003 13:28:21 +0100 Subject: Cropping log files In-Reply-To: <9lKDb.12685$aw2.6770875@newssrv26.news.prodigy.com> References: <9lKDb.12685$aw2.6770875@newssrv26.news.prodigy.com> Message-ID: <20031217122821.GB1850@nl.linux.org> Robin Munn wrote: > Or if you really want to do it in pure Python, then have a look at the > source for 'tail' and see how it finds the last N lines. In most of my > experiments, I've found that 'tail' grabs the last 10 lines out of a > 1-gigabyte log file within milliseconds, while 'wc -l' takes a lot > longer to count the whole file. That's not very scientific evidence, of > course, but why don't you try it and see for yourself? Maybe it .seeks() to .getsize()? Gerrit. -- 258. If any one hire an ox-driver, he shall pay him six gur of corn per year. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From sombDELETE at pobox.ru Sat Dec 20 17:55:19 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 21 Dec 2003 01:55:19 +0300 Subject: Unicode from Web to MySQL References: Message-ID: "Francis Avila" wrote in message news:vu9epa99laks26 at corp.supernews.com... > In other words, there is no standard, 100% reliable method of getting the > encoding of a web page. There is a standard way. But you're right, it's not 100% reliable. > In an ideal world, the http header would have it, and that's that. That's actually is not a good idea, because it will force the http server writers to parse html header for the encoding. They will get away with configuration parameter forcing all server files to be in one encoding. But one day somebody will store a file in the wrong encoding *for sure*. http header encoding is a bad idea. > In the real world, you have to juggle various combinations > of information, missing information, and disinformation from the http > protocol header's info, the html file's meta info, and charset guessing > algorithms (look for Enca). It's not so bad. Web server and content editor writers are slowing getting a clue. It used to be very bad, I remember it. I think the peak of problems was in 98-99 years. But nowadays more than 99% of web documents get encoding right. So having a simple read_unicode() method of urlopener class would be very useful. From aahz at pythoncraft.com Mon Dec 8 09:09:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 8 Dec 2003 09:09:58 -0500 Subject: Quantify over all functions of a module References: Message-ID: In article , Fredrik Lundh wrote: >> something like this might work: >> >> for name, func in vars(test2): >> if not name.startswith("__") and callable(func): >> func_list.append(func) > >ahem. better make that: > > for name, func in vars(test2).items(): > if not name.startswith("__") and callable(func): > func_list.append(func) ...and if you wanna show off your Python 2.2+ knowledge, make that iteritems(). ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From a.clarke11 at ntlworld.com Tue Dec 2 06:24:43 2003 From: a.clarke11 at ntlworld.com (Tony Clarke) Date: 2 Dec 2003 03:24:43 -0800 Subject: I just want to say that python is a COOL language References: Message-ID: <3353cd1e.0312020324.3be05185@posting.google.com> "Posadas, Dennis" wrote in message news:... > Complete Object Oriented Language. > > COOL ! > > After years of not doing any programming, I've fallen in love > w/programming again. > > Dennis Ditto! Python is also FUN: Free, useful, and , er, non-problematic From ramen at lackingtalent.com Fri Dec 19 11:35:33 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 19 Dec 2003 16:35:33 -0000 Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> <93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: In article , Fredrik Lundh wrote: > A console program may use the Windows API to disconnect from the > console, or create a window, and a window program may use the API > to create a console if it needs one (a version of pythonw that did this > if/when the application prints to sys.stderr would be quite useful, btw) Yes! Especially if it paused afterwards, so you could actually read the error message! Speaking of which, is there any way to keep the console window on the screen after double-clicking on a .py file so that syntax errors don't result in a spead-reading test? Thanks, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From aaron at reportlab.com Wed Dec 10 06:13:21 2003 From: aaron at reportlab.com (Aaron Watters) Date: Wed, 10 Dec 2003 06:13:21 -0500 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha Message-ID: <3FD6FFD1.20004@reportlab.com> ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha Links: Home page with docs and other links: http://xsdb.sourceforge.net/ Sourceforge project with download links http://sourceforge.net/projects/xsdb/ Executive Summary: The xsdb package is an open source database implementation implemented in Python and hosted on SourceForge. The xsdb package provides fundamental concurrent database functionality with concurrency control and recovery. Fundamental characteristics include: - Extreme portability and ease of installation and use. - A simple semantics of objects with associated descriptions compatible with the relational model, object modelling methods, and other data organizations such as OLAP. - Multiple access paths and indices. - Timestamp based concurrency control for safe concurrent database access. - Commit/Rollback and recovery support. - A variety of underlying storage implementations with configurable features and performance characteristics. - No intrinsic database size limitations. The package is intended to provide what you really need from a database for most applications, without the other stuff (among other goals). General Technical Notes: The xsdb package is implemented in Python, and the server mode requires stackless python. An xsdb database (not in server mode) will run using standard C Python or Java Python (Jython). Please have a look and give it a try. Thanks very much! -- Aaron Watters [attempt 2] === Even in a perfect world where everyone is equal I'd still own the movie rights and be working on the sequel -- Elvis Costello "Every day I write the book" From ptmcg at austin.rr.com Sat Dec 20 15:41:02 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 20 Dec 2003 20:41:02 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: Is this language really necessary? I'm sure I've used these words myself, but they're certainly not appropriate in a public discussion. I do not know the answer to your question, it really seems more like a regexp question, rather than a problem with Perl. I hope someone who knows the answer can respond, hopefully in more civil language. From martin at v.loewis.de Mon Dec 8 18:10:47 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 09 Dec 2003 00:10:47 +0100 Subject: IMAP4 and deleting a message References: Message-ID: Wilfredo Sanchez writes: > Can someone hook me up? I think IMAP does not have the notion of immediately deleting messages. Instead, you should set the \Deleted flags, e.g. though M.store(num, "+flags", r"\Deleted") Then, deleted message will be expunged either as the result of invoking .expunge(), or as a result of invoking .close(). Regards, Martin From eddie at holyrood.ed.ac.uk Tue Dec 2 11:17:48 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 2 Dec 2003 16:17:48 +0000 (UTC) Subject: Can Python be run off of a CD-ROM? References: Message-ID: =?ISO-8859-1?Q?Gerhard_H=E4ring?= writes: >Eddie Corns wrote: >> [...] I was wondering whether there was a howto on running Python from Windows >> without it being in the registry [...] >Here's the HOWTO, in one sentence: >Grab a Python directory, copy the python{major}{minor}.dll from >%SYSTEMROOT%\system32 into this Python directory. >In there, Python now runs standalone, and you can burn the whole >directory on a CD if you like. >win32 Python does have module search paths in the registry, but they >aren't required. OK ta, I will try this out. A chance to play with my new CD rewriter too. Eddie From matt at killermookie.org Mon Dec 15 17:08:58 2003 From: matt at killermookie.org (Matthew Sims) Date: 15 Dec 2003 14:08:58 -0800 Subject: Jumping around when assigning elements Message-ID: <1e963607.0312151408.583221e6@posting.google.com> Python Newbie here. This is my first time learning object-oriented programming and trying to break out of the usual Korn/Perl/PHP style of programming. Having some difficulty understand some items. For lists, I understand this: C=["need","some","help"] print C[1] some But I can't seem to do this: C[3]="here" I know about C.append("here") but this brings me to my question... Is there anyway to assign to an element that wasn't defined in the beginning? Like if I wanted element 5 assigned but not element 4 without using "" or None? I'm currently re-writing a Perl script into Python and with Perl I was free to assign any element in the array without having to fill in the previous elements. I can't seem to do that in Python...unless I'm doing it wrong. Thanks --Matt From newsgroups at jhrothjr.com Sun Dec 7 19:08:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 7 Dec 2003 19:08:47 -0500 Subject: Base conversion method or module References: <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc@4ax.com> Message-ID: "Jeff Wagner" wrote in message news:jid7tvcfkf9hhc3vvut4gfbpl7i1g46t6o at 4ax.com... > On Sun, 7 Dec 2003 15:45:41 -0500, "Francis Avila" wrotf: > > > I am getting an error when I import this module and call it. > > #!/usr/bin/python > > import BaseConvert > print BaseConvert.convert(90,BASE10,BASE2) > > Name Error: name 'Base10' is not defined. > > This probably has something to do with namespaces which was biting me a while ago. I thought that > since the 'Base' definitions were global to this module (BaseConvert.py) by being defined outside > the function (convert), that when I imported this module, they would be global, too. > > From one of my books, it says, "An import statement creates a new namespace that contains all the > attributes of the module. To access an attribute in this namespace, use the name of the module > object as a prefix: import MyModule ... a = MyModule.f( )" which is what I thought I was > doing. > > What am I still missing? print BaseConvert.convert(90, BaseConvert.BASE10, BaseConvert.BASE2) John Roth > > Thanks, > Jeff From daniels at dsl-only.net Sun Dec 28 13:29:26 2003 From: daniels at dsl-only.net (sdd) Date: Sun, 28 Dec 2003 10:29:26 -0800 Subject: pointers In-Reply-To: References: Message-ID: <3fef2cef$1@nntp0.pdx.net> km wrote: > Hi all, > may i know if there is any plans of introducing the concept of pointers into python language as in C ? (atleast in future versions ?) > regards, > thanks KM Nope. I believe the official line is "YAGNI" (You Aint Gonna Need It). Pointers can be fun to create interesting code, bugs and hacks, but there is little to use them for. If you are wanting to use a familiar structure, it won't happen here. If you think you have a _real_world_ case for it here, we can often explain why you don't really need it. The _real_world_ bit means: find an example we can have intuitions about, not simply foos, frobs, and mumbles. By the way, you might think of python names as pointers to objects, or integers as list (or string or tuple or array)-based pointers where the list the pointer comes from is kept specific. If you want, you could even create a class named Pointer to hide the list the pointer is based on. We'd generally advise against this, but... -Scott David Daniels Scott.Daniels at Acm.Org From pinard at iro.umontreal.ca Wed Dec 17 10:42:06 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 17 Dec 2003 10:42:06 -0500 Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: <87ekv3frho.fsf@pobox.com> References: <87ekv3frho.fsf@pobox.com> Message-ID: <20031217154206.GA21073@alcyon.progiciels-bpi.ca> [John J. Lee] > Fran?ois Pinard writes: > [...] > > P.S. - If I'm using past instead of present, about ELSE, this is because > > not so long ago, I switched my habits away from Emacs (towards Vim). > Why? [...] But maybe you were originally a vi user, and have just had > a long emacs detour? No. You cannot imagine how much I could not stand `vi' for myself. On machines without Emacs or some form of Emacs clone, I was using `ed', or even `sed', just for avoiding finding myself stuck within `vi'. So, to see myself using Vim now, represents an astonishing conversion! :-) The "Why?" is a bit difficult to tell in a few words. Especially since I still consider Emacs as a wonder. I explained my reasons to a few friends and saved my notes, and I'll probably turn them into some Web page if I find some more free time. Let me post the URL here then... Let me say right away is that I would have never ever considered Vim if it did not offer proper Python support. Pymacs seems more powerful to me that Python in Vim, yet Python in Vim is neat and quite usable. Vim surprisingly has many functionalities, under paradigms which vary slightly or greatly, which I thought Emacs was alone to offer. This helped me to "swallow the snake", which admittedly has been rough :-). -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From newsgroups at jhrothjr.com Sat Dec 20 12:32:25 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 12:32:25 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Ville Vainio" wrote in message news:du7fzffmmiw.fsf at amadeus.cc.tut.fi... > "John Roth" writes: > > > > Most importantly, why would anyone even care? Ability to optionally > > > invoke a "call" operation on an object implicitly seems utterly > > > worthless to me. > > > > That may not be one of your common coding mistakes. > > It was when I started. Not after a while. > > > My mind doesn't quite get the point of inserting an > > otherwise useless pair of parenthesis, and consequently > > it's fairly high on the list of common coding errors I make > > that causes run time errors. Of course, rigidly applying > > Don't something like pychecker detect these things? Since I normally use TDD, using Pychecker would slow the flow down substantially. See the next paragraph. > > TDD will bring those errors up rapidly so they don't > > lurk to cause problems later, but not having them in the > > first place would be even better. > > Not if they go against the fundamental ideas of how the language > works. If a language makes opportunities for errors, then there is something wrong with the language that needs to be corrected. I'm not a fan of carrying a reasonable idea past the point where it starts showing its flaws. I'm also not a fan of the idea that there are any ideas that are flawless if carried to extreme. > > is looking at what it's doing right and asking if some of those > > things might not improve Python. > > Hasn't Alex Martelli done something like this recently? Alex? There was a mini-project to identify "warts" a year or two ago. Is this what you mean? > > As I said, my intent is not to inspire anyone to switch. My intent > > is to ask whether there is anything they're doing that would be > > (in concept if not in implementation) an improvement to Python. > > Sounds like a morally correct motive :-). > > -- > Ville Vainio http://www.students.tut.fi/~vainio24 John Roth From daniels at dsl-only.net Sat Dec 6 00:10:39 2003 From: daniels at dsl-only.net (sdd) Date: Fri, 05 Dec 2003 21:10:39 -0800 Subject: Lists and Tuples In-Reply-To: References: Message-ID: <3fd02df2$1@nntp0.pdx.net> Jeff Wagner wrote: > I've spent most of the day playing around with lists and tuples to get a really good grasp on what > you can do with them. I am still left with a question and that is, when should you choose a list or > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it > than just that. Everything I tried with a list worked the same with a tuple. So, what's the > difference and why choose one over the other? > > Jeff Here's the biggie: association = {} somevals = 1,2,6,'a' association[somevals] = 13 vs. association = {} somevals = [1,2,6,'a'] association[somevals] = 13 -Scott David Daniels Scott.Daniels at Acm.Org From a.schmolck at gmx.net Tue Dec 2 06:46:07 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 02 Dec 2003 11:46:07 +0000 Subject: Scientific Python References: Message-ID: "Lucas Raab" writes: > Is there a version of SciPy or Scientific (correct me if they're the same) > available for Python 2.3.2?? Yes (www.scipy.org), yes (http://starship.python.net/crew/hinsen/scientific.html), no (they are not the same). 'as From timr at probo.com Sun Dec 7 14:37:20 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Dec 2003 11:37:20 -0800 Subject: Binary number manipulation References: <350rsvkbsht8rgs1fsjjc7vkktf87sahi7@4ax.com> <9hkzb.52005$Vu5.3422581@twister.southeast.rr.com> <20031206154820.0c56455e.matt@satbp.com> Message-ID: "Matthew A. Berglund" wrote: > >Thanks everybody. > >I settled on the >((high << 8) | low) >As this fits my need for the moment. But this solves a very different problem from the one you originally posted, which was ((high << 16) | low). If you need to combine WORDS, then the solution you have settled on will produce the wrong answers. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jjl at pobox.com Sat Dec 27 07:15:19 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Dec 2003 12:15:19 +0000 Subject: Using python to check the status of a program References: Message-ID: <871xqqo3s8.fsf@pobox.com> Kamuela Franco writes: > I would like to use a Python script to periodically check to see if a > program is still running and if it isn't I want to start it up. Could > someone point me on the right path? Thanks in advance. Search the ASPN Python Cookbook for "watchdog" -- I remember a recipe there (search c.l.py with Google Groups too, of course). John From 9974331 at cvm.qc.ca Wed Dec 31 05:25:57 2003 From: 9974331 at cvm.qc.ca (Askari) Date: 31 Dec 2003 02:25:57 -0800 Subject: Try - Except : ignored! Message-ID: <104c369a.0312310225.551d4d16@posting.google.com> Hi, In my program (too long for cut-paste) : http://www.cvm.qc.ca/9974331/Temp/crypte.py When I run and click on the button "Crypter!", a thread is run for the method "def crypte():" (line 118). After, because the field "txtCode" is blank, I raise a error (line 136). The code continu in the except at line 353. In this except block, Python ignore (I don't know how!) one of two "try - except" (line : 354-360 or 362-365) and raise a error and go out of try-except (but it's in a try except!). When I run my code with no change, this error come : ============ Traceback (most recent call last): File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", line 363, in crypte os.remove(destination) OSError: [Errno 2] No such file or directory: '' ============ and if I remove the second try-except (lines 362-365), I have this error message : ============ Traceback (most recent call last): File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", line 355, in crypte fileDest.close() NameError: global name 'fileDest' is not defined ============ Askari Note : I try my code with python 2.3.3, 2.3.2 and 2.2.3. I have always this bug. From jjl at pobox.com Wed Dec 17 09:28:35 2003 From: jjl at pobox.com (John J. Lee) Date: 17 Dec 2003 14:28:35 +0000 Subject: Anyone use ELSE minor-mode in Emacs? References: Message-ID: <87ekv3frho.fsf@pobox.com> Fran?ois Pinard writes: [...] > P.S. - If I'm using past instead of present, about ELSE, this is because > not so long ago, I switched my habits away from Emacs (towards Vim). Why? Interesting to see an emacs 'power user' switch to vi. But maybe you were originally a vi user, and have just had a long emacs detour? John From rmunn at pobox.com Mon Dec 22 11:29:03 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 22 Dec 2003 16:29:03 GMT Subject: re troubles References: Message-ID: Evanda Remington wrote: > I'm trying to filter some rows of an html table out, based on their > contents. For input like: > """ > > > > << want to filter > << this out. > << > >
    Lasers17
    kittens8
    robots8
    > """ > I would like to completely remove the (3 line) table row that makes mention > of kittens. The regexp I have tried to use is: r".*?kittens.*?". > When compiled and used with subs("",data), strangely removes everything > from the first "" to the first "" after kittens. > > That is, the ".*?" notation works in the second half, but not in the first > half. It behaves the same as ".*" should. > > Any advice? Parsing HTML with regular expressions is notoriously tricky. Have you tried using HTMLParser yet? If you've tried it and it doesn't work for you for some reason, then you may have to deal with regexp's. But if you haven't tried HTMLParser, you may find it a lot easier than regexp's for this task. -- Robin Munn rmunn at pobox.com From nessus at mit.edu Fri Dec 5 02:37:22 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 05 Dec 2003 02:37:22 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: David Eppstein writes: > That's true, but another answer is: you should use tuples for short > sequences of diverse items (like the arguments to a function). You > should use lists for longer sequences of similar items. I disagree. You should use a tuple when you wish to not change the contents once you have constructed the sequence, and otherwise you should use a list. Using a tuple can make your code clearer by letting the reader know from the beginning that the contents won't be changing. Fredrik Lundh actually called me names a couple years back for asserting this, but Python luminary (and rude fellow) or not, he is dead wrong. You don't have to take my word for it, though, since Python itself uses tuples in this manner, in the form of the container used for excess arguments (excess arguments certainly don't have to be short, and they are generally homogeneous, not heterogeneous), and Python Mega Widgets (for example) is littered with code that looks like: optiondefs = ( ('initwait', 500, None), # milliseconds ('label_background', 'lightyellow', None), ('label_foreground', 'black', None), ('label_justify', 'left', None), ('master', 'parent', None), ('relmouse', 'none', self._relmouse), ('state', 'both', self._state), ('statuscommand', None, None), ('xoffset', 20, None), # pixels ('yoffset', 1, None), # pixels ('hull_highlightthickness', 1, None), ('hull_highlightbackground', 'black', None), ) In the above case we see tuples being used both as records *and* as an arbitrary-length sequence of homogenious elements. Why is a tuple being used in the latter case, rather than a list? Because the sequence isn't going to be modified. |>oug From FBatista at uniFON.com.ar Tue Dec 30 08:32:51 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 30 Dec 2003 10:32:51 -0300 Subject: function-arguments by reference Message-ID: De: EsC [mailto:christian.eslbauer at liwest.at] #- is it possible to pass function-arguments by reference? #- (for example in PHP you can use the "&" operator ... ) As long it's always by reference, yes, it's possible. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose-hates-spam at and-benfinney-does-too.id.au Thu Dec 18 22:09:44 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 19 Dec 2003 13:59:44 +1050 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: On Fri, 19 Dec 2003 11:42:49 +1100, Glen Wheeler wrote: > My program uses many millions of integers, and Python is allocating > way too much memory for these. How have you measured this? As pointed out by others, Python doesn't have duplicate occurrences of identical integers; it refers to the same object multiple times. Given this, I'm curious how you've measured the memory usage caused by your program using millions of integers, and why you think reducing the size of those integers will help significantly. -- \ "I like to fill my bathtub up with water, then turn the shower | `\ on and pretend I'm in a submarine that's been hit." -- Steven | _o__) Wright | Ben Finney From boydrobh at yahoo.com Tue Dec 30 10:28:30 2003 From: boydrobh at yahoo.com (Rob Boyd) Date: Tue, 30 Dec 2003 07:28:30 -0800 (PST) Subject: build problems on Solaris 9 Message-ID: <20031230152830.82136.qmail@web42004.mail.yahoo.com> Hi, I am having problems building Python 2.3.3 on Solaris 9, on a SunFire SPARC. I am using gcc 3.3.2, and apparently don't have binutils (but have ld, as, ar, and the like). I have set LD_RUN_PATH appropriately. During 'make', I get many warnings such as: "WARNING: renaming "regex" since importing it failed: ld.so.1: ./python: fatal: libgcc_s.so.1: open failed: No such file or directory". I can still subsequently install Python, but it is broken. Despite the warning, libgcc_s.so.1 is in /usr/local/lib. Plus, I did not get these errors when building Python 2.3.2, and it does not fail to find libstdc++.so.5 (which fails if LD_RUN_PATH is not set). Any help is greatly appreciated. Sorry if this is in a FAQ or prior posts, but my searches, and the Solaris section in the README have not helped resolve this. Rob Boyd __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From jnc at ecs.soton.ac.uk Wed Dec 10 11:12:45 2003 From: jnc at ecs.soton.ac.uk (John Carter) Date: Wed, 10 Dec 2003 16:12:45 +0000 Subject: Using PIL with py2exe (part II) Message-ID: Following up my previous post, including all ige *ImagePlugin.py files seems to work. Its a bit of a kluge as I'm trying to avoid distributing python with this application. Better, more sanitary solutions welcome. John Carter jnc at ec.soton.ac.uk From jdhunter at ace.bsd.uchicago.edu Fri Dec 5 16:13:00 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 05 Dec 2003 15:13:00 -0600 Subject: memory leak - C API In-Reply-To: ("Tim Peters"'s message of "Fri, 5 Dec 2003 14:41:03 -0500") References: Message-ID: >>>>> "Tim" == Tim Peters writes: Tim> Where did that understanding come from? It's important to Tim> track it down, because whatever source you got it from is Tim> unreliable. This one is such a common misconception that the Tim> docs (Python C/API Reference Manual, section "Reference Count Tim> Details") point it out explicitly: Argg... I got it from reading the API for PyList_GetItem and *assuming* it worked the same way for PySequence_GetItem. I was using the PyList API as a stand-in for the sequence API because I didn't find the PySequence API. I ended up at http://www.python.org/doc/current/api/sequenceObjects.html by googling. Perhaps the best way to help others avoid making the same mistake is to make a link on the http://www.python.org/doc/current/api/sequenceObjects.html page to http://www.python.org/doc/current/api/sequence.html page, which I only found after reading your post. Eg, on http://www.python.org/doc/current/api/sequenceObjects.html, something like For generic operations on sequence objects, see the sequence protocol
    PySequence; this section deals with the specific kinds of sequence objects that are intrinsic to the Python language. The link "PySequence" would have caught my eye (since I was looking for it), but the bland Generic operations on sequence objects were discussed in the previous chapter; this section deals with the specific kinds of sequence objects that are intrinsic to the Python language. did not. Thanks for the help, John Hunter From g2h5dqi002 at sneakemail.com Thu Dec 18 23:01:36 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Fri, 19 Dec 2003 17:01:36 +1300 Subject: Default parameters In-Reply-To: <7x4qvysnrr.fsf@ruckus.brouhaha.com> References: <3fde309f$0$19285$626a54ce@news.free.fr> <7x4qvysnrr.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Greg Ewing (using news.cis.dfn.de)" writes: > >>Changes are rarely if ever made to Python for the sole reason >>of reducing newbie mistakes. > > > print 3/2 That's not a counterexample! There are sound non-newbie-related reasons for wanting to fix that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From JTesser at nbbc.edu Fri Dec 26 10:16:13 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Fri, 26 Dec 2003 09:16:13 -0600 Subject: dynamic typing question Message-ID: <04875CB4331F0240A0AD66F97097865101137723@paul> Hi, > Along with everything others have already written--that > you want to focus on test-driven development, that Python > is a proven success in Serious Applications, and so on-- > your description raises a few concerns in my mind: > 1. Why, in your mind or your teammate's, > is dynamic typing a "lack"? What, pre- > cisely, is the benefit of static typing? > There are a number of legitimate > answers. It occurs to me that, without > precision on which interest you, we > might be missing an opportunity to > clarify "The Python Way" significantly. The typing errors that would not be found until runtime. >2. Most application-level Python code > doesn't--and shouldn't!--employ dynamic > typing in any material way. Does that > help? >3. Postgres is good stuff. Its support for > Python has improved quite a bit over the > past few years. >4. My instinct tells me that, yes, you can > produce quality results quicker with Py- > thon. >5. In writing, "the GUI is clunky" about > Java, what do you mean? Are you refer- > ring to a particular IDE, or a specific > GUI toolkit? Java has several of each; > perhaps alternatives would suit you > better. Java's main gui. Swing it is slow. >6. Are there alternatives to having the > two of you write a "package" from > scratch? A LOT of software for college > administration has been written already; > is none of it appropriate for your situ- > ation? $500,000 to get the level of a product that we need as a complete solution. There are a lot of little programs that would meet individual needs, many of which we now use but we need a complete integrated solution at this point. We are a Bible college and do have some unique needs for our students also. Cameron Laird Business: http://www.Phaseit.net -- http://mail.python.org/mailman/listinfo/python-list From hungjunglu at yahoo.com Thu Dec 11 13:11:24 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 11 Dec 2003 10:11:24 -0800 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> <3fd7bf36$0$28702$626a54ce@news.free.fr> Message-ID: <8ef9bea6.0312111011.6a49053d@posting.google.com> Bruno Desthuilliers wrote in message news:<3fd7bf36$0$28702$626a54ce at news.free.fr>... > > You may want to have a look at Io > http://www.iolanguage.com/ > Thanks. That was a good dose of adrenaline shot. :) It's amazing to see how people are converging. It's also refreshing to see some brains out there. I am over 1 year late in knowing about the existence of Io (it came out last year) and over 2 years late in hitting upon some concepts. But that's all right. Better catch up late than never. :) When I saw that Io was prototype-based, I told myself: "OK, smart". When I saw statements were message-based, I told myself: "OK, more than smart". When I saw that it was designed with full awareness of Python and Ruby, I told myself: "OK, very smart". When I saw that it has codeblocks ("block" in Io syntax) and weaklinks, I told myself: "OK, really smart". When I saw that it can print the source code of a block, I told myself: "OK, extremely smart". :) Of course, all the fundamentals have been out there before. But it is refreshing to see people heading in the right direction. regards, Hung Jung From pje at telecommunity.com Fri Dec 5 09:57:07 2003 From: pje at telecommunity.com (Phillip J. Eby) Date: Fri, 05 Dec 2003 09:57:07 -0500 Subject: PyProtocols 0.9.2 Bug fix release Message-ID: <5.1.0.14.0.20031205095450.02a75260@mail.telecommunity.com> I goofed, missing a unit test for one of the new features: 'protocols.Variation' was broken in the 0.9.1 release. 0.9.2 fixes the bug. Sorry for the inconvenience. PyProtocols Resources --------------------- * Project home page: http://peak.telecommunity.com/PyProtocols.html * Detailed Changes since the 0.9 release: http://peak.telecommunity.com/protocol_api/CHANGES.txt.html * Release notes, installation instructions, and browsable API docs: http://peak.telecommunity.com/protocol_api/ * Source and Binary Releases: http://peak.telecommunity.com/dist/ * Reference Manual (HTML): http://peak.telecommunity.com/protocol_ref/module-protocols.html * Reference Manual (PDF): http://peak.telecommunity.com/protocol_ref.pdf * Browsable CVS Repository: http://cvs.eby-sarna.com/PyProtocols/ From reply.in.the.newsgroup at my.address.is.invalid Sat Dec 6 12:42:35 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 06 Dec 2003 18:42:35 +0100 Subject: Reading pipes in Python References: Message-ID: Jeroen van der Ham: >f=open('/tmp/myfifo','r') >while 1: > print f.readline() This loop is endless, so don't complain to us that it doesn't end :-) >what can be done to make it work? f=open('ff','r') while 1: li = f.readline() if not li: break print li, -- Ren? Pijlman From dkuhlman at rexx.com Mon Dec 15 20:01:04 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 15 Dec 2003 17:01:04 -0800 Subject: Spell checking and Python References: Message-ID: Gilles Lenfant wrote: > Hi pythonists, > > Any experience or pointer on using a spell checker (aspell, ispell > ?) with a Python app ? > > Many thanks by advance Here is one way for UNIX/Linux running with X Windows: def check(content): file = open('ispell.tmp', 'w') file.write(content) file.close() os.system('xterm -e ispell ispell.tmp') file = open('ispell.tmp', 'r') content = file.read() file.close() return content You might want to use the tempfile module in the Python standard library to create the temporary file, though. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From martin at v.loewis.de Wed Dec 3 14:23:00 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Dec 2003 20:23:00 +0100 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> <43e3984e.0311230527.74eed7a3@posting.google.com> <43e3984e.0312030436.3640d21b@posting.google.com> Message-ID: ulysses_dm at yahoo.com.cn (ulysses) writes: > > Can you please post a bug report to SourceForge then? Please include > > the .mo file, and a small Python script showing the error. > Do you mean http://gettext.sourceforge.net/ ? No, sf.net/projects/python > Can I Email to you , sample script and MO file. > I promise It's very small . I don't how to write to SF. Please don't. Just request an SF account, and submit a bug report. Regards, Martin From gh at ghaering.de Thu Dec 4 04:13:15 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2003 10:13:15 +0100 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 In-Reply-To: <3FCEFA8F.4060103@geochemsource.com> References: <9b849915.0312040054.66484ff1@posting.google.com> <3FCEFA8F.4060103@geochemsource.com> Message-ID: <3FCEFAAB.8040303@ghaering.de> Gandalf wrote: > Use PySerial > > http://pyserial.sourceforge.net/ I'd recommend PyParallel instead: http://pyserial.sourceforge.net/pyparallel.html ;) -- Gerhard From duncan at NOSPAMrcp.co.uk Thu Dec 11 09:03:35 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 11 Dec 2003 14:03:35 +0000 (UTC) Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312110538.568014ef@posting.google.com> Message-ID: aaron at reportlab.com (Aaron Watters) wrote in news:9a6d7d9d.0312110538.568014ef at posting.google.com: > regarding the use of stackless in > http://xsdb.sourceforge.net > "Fredrik Lundh" wrote in message > news:... >> Aaron Watters wrote: >> > 5) use an event loop and use a generator for the relevant code; >> when you discover that you need to pause, yield to the framework. > > Please tell me I'm missing something, but I don't think > this will really help. The problem is that I need to "yield" > or "suspend" or "send something across a channel" from about > 45 places in the code some of which are arbitrarily deep into > multiple recursions. The generator thing will only allow > me to go one level deep into a single call -- no? By contrast > the stackless.channel mechanism is a far more general construct, > allowing me to "yield" at any point without restructuring the > code at all. Stackless rules. The generator solution may not be appropriate for your task, but it isn't entirely accurate to say that you can only go one level deep. You can (sort of) yield from arbitrarily deep function nesting, or even from recursive functions. The catch though is that you do have to write the code in a slightly contorted manner in order to yield from below the first function. The rule to follow is simply: any function which wants to yield, or which calls a function that wants to yield has to be a generator and has to be called from a 'for' loop which itself yields. e.g. A generator that walks a tree recursively: def inorder(t): if t: for x in inorder(t.left): yield x yield t.label for x in inorder(t.right): yield x -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From http Wed Dec 10 21:06:04 2003 From: http (Paul Rubin) Date: 10 Dec 2003 18:06:04 -0800 Subject: Python progamming certification References: <87fzfuszsq.fsf@pobox.com> <3FD7C8ED.3000501@_._> Message-ID: <7x3cbsw1kj.fsf@ruckus.brouhaha.com> Apollo <_ at _._> writes: > But how can I convince employers that I know Python I have not > programmed using Python in career before? Why that's the simplest of all. Write an interesting program and release it as free software. From hwlgw at hotmail.com Thu Dec 4 12:34:39 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 4 Dec 2003 09:34:39 -0800 Subject: HTTP Location: supported by HTTPServer? Message-ID: I have a CGI server written in Python, useful for offline CGI testing. One of my CGI scripts ends with: print 'Location: http://myresourcelocation' print But this does not work with the Python CGI server...and the same script *does* work via internet with the Apache server at my work. Does the BaseHTTPServer.HTTPServer not support the HTTP Location header or something like that? >From my Python CGI server program: PORT = 8000 class Handler(CGIHTTPServer.CGIHTTPRequestHandler): ## # Put subdirectories BEFORE their parent directories or else HTTP # error 403 (no permission). cgi_directories = ["/cgi-bin/mystuff", "/cgi-bin"] ## # A hack for quiet mode: don't want messages (what IP reads what # URL) to the console box def log_message(self, *msg): pass def serve(): httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever() class CGIServer(threading.Thread): def run(self): serve() if __name__=='__main__': CGIServer().start() From hwlgw at hotmail.com Sat Dec 20 03:34:31 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 20 Dec 2003 00:34:31 -0800 Subject: PNG to EPS with Python? Message-ID: I have .PNG image I would like to convert to .EPS (Enhanced PostScript), for inclusing in LaTeX documents. I feel that a portable tool for this would be very welcome in the scientific community, where they still LaTeX a lot! There is a png2eps tool for linux/unix, but I can't find something that works on Windows. Perhaps somebody with Cygwin can produce an .exe (I don't use Cygwin anymore myself)? I wonder if this would be possible to do with Python, or maybe somebody already did this? Instead of PNG also JPG, GIF, TIFF, etc. would be welcome, as it is easy to convert PNG back and forth to those, even on Windows :-) From fredrik at pythonware.com Sun Dec 7 06:40:17 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 12:40:17 +0100 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > >> Fredrik Lundh actually called me names a couple years back for > >> asserting this, but Python luminary (and rude fellow) or not, he is > >> dead wrong. > > > I'm never dead wrong. > > You were dead wrong to insult me in a debate over subtle programming > aesthetics, where my opinion is just as well-founded as anyone's. I actually had to dig up the thread that has caused you such grief over the years. as expected, you spent that thread attacking everyone who dis- agreed with you, misrepresented other people's arguments, referred to implementation artifacts and design mistakes as "proof", and used the same muddled thinking as you've shown in this thread. heck, Tim even introduced the term "douglas-sequences" in contrast to "python-sequences" in order to make any sense of what you were arguing about that time. not the kind of behaviour I'd expect from anyone who wants to be taken seriously. two years later, you haven't learned a thing; that's pretty tragic. From andreif at mail.dntis.ro Tue Dec 23 07:35:50 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 23 Dec 2003 04:35:50 -0800 Subject: Storing pairs of (int,int) in a database : which db to choose ? Message-ID: <21bb8d55.0312230435.49cad73c@posting.google.com> Hi, I want to implement a fulltext search for messages in a forum. More exactly for each message I store pairs (wordId, msgId) for each identified word and when I search something I want to be able to retrieve very quickly all msgId for a given wordId. For starters I used PySqLite, using a table with index on wordId. It works fine but it consumes way too much space on the disk. For example for 19103 pairs it takes 1686528 bytes, which amounts to around 88 bytes per pair of integers, way too much in my opinion (especially considering the range of those integers - one is in the range 1..100000 and the other in the range 1..500000). So my problem now is what should I use to store my data and still be able to retrieve all messages for a given word very quickly. Either I find a workaround in sqlite to make it store values on less bytes, or I use something else. I looked at the (g)dbm family but they store one entry per word and both must be strings. To use it would mean to store a list of messages for a word as a string, then when I find a new message containing this word to replace this string with old string + the new message id -> and I think this is inefficient. At the moment I am looking at BerkeleyDB - still checking if this will suit my needs. Any advices and hints ? I'm looking only for embedded solutions like PySqLite, if a database needs to install a server then it's not an option. Thanks in advance, Andrei From dw-google.com at botanicus.net Sun Dec 14 14:17:40 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 14 Dec 2003 11:17:40 -0800 Subject: Shell quoting as part of the standard library? References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: <99dce321.0312141117.1a6b48f5@posting.google.com> Oren Tirosh wrote... > The best solution is often to bypass the shell (os.system) and execute > the external command you want directly with os.spawnv. In this case the > arguments are passed as a list of strings rather than a space-separated > string and therefore need no quoting. That would be a fine solution, except again it does not solve my problem. In the latest application of shell quoting, I needed to insert filenames into a shell excerpt provided by a user who is knowledgeable in shell. They could write, for instance: process_app %(input_filename) || something %(blah) [ -s %(output_filename) ] && ... But it would be above them to express that in Python, so bypassing the shell is not an option. Thanks, David. From claird at lairds.com Sun Dec 14 08:24:43 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 14 Dec 2003 13:24:43 -0000 Subject: intro to python books References: Message-ID: In article , Kamus of Kadizhar wrote: >I'm looking for a good intro to python book. I'm very familiar with >programming, but know nothing of OOP or systems (OS type) programming. >All of my programming experience is in number crunching and generic >graphics engines (read: gobs and gobs of matrix manipulations and >super-efficient sorts), all of it in C. > >I've written exactly one program in Python. > >So, I need something that covers the finer points of Python - difference >between ' and " for example - and the greater things beyond that, like >implicit lists and classes. . . . I applaud you for the care with which you've described your situation and requirements. There are several worthwhile Python books that I think you'll like, some of them on-line. It's quite likely your question will attract follow-ups that mention a half-dozen of these. The first ones that come to my mind are , http://www.pythonware.com/people/fredrik/librarybook.htm >, and . -- Cameron Laird Business: http://www.Phaseit.net From exarkun at intarweb.us Mon Dec 22 09:33:04 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 22 Dec 2003 09:33:04 -0500 Subject: How do I test if an object is a sequence? In-Reply-To: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: <20031222143304.GC21664@intarweb.us> On Mon, Dec 22, 2003 at 03:11:55PM +0100, Max M wrote: > Is there a common idiom for testing if an object is a sequence? > Define sequence more thoroughly. I was with your description, up to the point where you said you didn't think strings qualified. Now I'm not sure what you're looking for. For example, do arrays count (array.array)? I guess unicode is out, if strings are, but what about other kinds of strings (UserString or subclasses of StringType)? Or maybe a better question would be this - *why* do you want a function that returns True when passed a list or a tuple or one of these mysterious "non-standard objects", but False when passed a string, an integer, or something else of that variety? Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From logan at phreaker.nospam Thu Dec 4 07:44:14 2003 From: logan at phreaker.nospam (Logan) Date: Thu, 04 Dec 2003 13:44:14 +0100 Subject: diferences between 22 and python 23 References: Message-ID: On Wed, 03 Dec 2003 18:15:15 +0100, Enrique wrote: > running a script that works fine in python 22 in python 23 i find something > like: > > unicodedecodeerror: "ascii" codec dan+t decode byte 0xed in position > 37:ordinal not in range (128) (You should post the code snippet which causes the error.) Just one possibility: maybe you used sitecustomize.py in Python 2.2 to set your default character set to something else than ASCII (e.g. ISO-8859-1 resp. Latin-1) and now - with Python 2.3 - you do not use this option any more!? HTH, L. -- mailto: logan at phreaker(NoSpam).net From mwh at python.net Mon Dec 29 09:08:14 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Dec 2003 14:08:14 GMT Subject: just another default argument value gotcha References: Message-ID: fBechmann at web.de (Frank Bechmann) writes: > Eventually most of you will not learn much from this because it's just > another event in the 'default argument value gotcha' series, but > because it cost me some hours yesterday to spot this 'error' in a > famous python tool I thought it might still help other people to save > some time. > > I tried to use some method which was documented to write to > 'sys.stdout' per default so that changing 'sys.stdout' to bind to > another object should allow to get grip on the method's output. but > that didn't work - reason was that that 'sys.stdout' was used as > default argument value for the method. FWIW, I think this is precisely the reason that "print >>None, ..." prints to sys.stdout. It lets you write > The following code describes it better then my english can do, so as > it seems for me, one should make sure to use the 'f2' variant. > > import StringIO, sys > > def f1(msg, out=sys.stdout): > out.write("%s\n" % msg) > > def f2(msg, out=None): > if not out: > out = sys.stdout > out.write("%s\n" % msg) either of these as def f3(msg, out=None): print >>out, msg Cheers, mwh -- For their next act, they'll no doubt be buying a firewall running under NT, which makes about as much sense as building a prison out of meringue. -- -:Tanuki:- -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From francisgavila at yahoo.com Tue Dec 23 04:04:25 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 23 Dec 2003 04:04:25 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: Andrew Dalke wrote in message ... >Francis Avila: >> I can't understand the syntax in the example code that shows how you'd get >a >> Method object. The "messaging" concept was clear, but I didn't understand how one got a method out of a message. >m = obj.method(:methname) >m.call(param1, param2) > >where 'method' is a method of the base object type which >takes the method name and returns a bound Method object. It's the colon syntax I didn't get. I think it's clearer to me now. Python also has a call "message": obj.__call__(). This can be viewed as a shorthand for obj(). So we can claim this "feature" if we like. :) It doesn't completely cover over the messaging v. attribute access distinction, but it's close. >Any better? It really does help if you think of Ruby as sending >message and not as getting callables.) > >> Of course, the typical Ruby accusation against Python is that it (Ruby) is >> "purer OO". I don't know what they mean by "purer". > >It is in part because of Python's old class/type dichotomy. > >It's also because Python lets you create instances which are >not part of any class or instance. For example, Python has >functions, like > >def spam(count): > print "Spam " * count > >These are not part of any object. (Well, perhaps the module >object, but it isn't a method of the module type.) To my mind, it's a function object, and functions are a base type. What it's a "part" of is almost meaningless. It's an object floating in the void, and there's a name, belonging to the module object (a different object), that points to that object. But a name is part of an object. So objects are still essential, but they possess means of referring to one another (names). Namespaces arise from objects possessing names. This is why I can't see how names can be objects in Python: they are incapable of existing independent of an object. >Philosophically then, while you could think of everything in >Python as OO it isn't as "pure" as Ruby because we tend >to think of modules, instances, attributes, variables, and >classes as different things, while Ruby doesn't make that >strong of a distinction between them. This I don't understand. It's a different view of things, but it seems to me that Python is more concrete, rather than less "pure" (neither seems more pure to me, at this point). A Pythonista says "everything is an object", and that means that everything an entity with names that point to other entities. A Rubyite (?) says "everything is an object", they mean something different. What precisely do they mean? Everything is an instance of one fundamental essence? We can claim this too, although it's not really how we think. Can the Rubyite say that they have fewer fundamental concepts? We have two: names and objects. Ruby has two: objects and messages. So both have a thing, and a way of relating things. It's just that Ruby's relations point in the opposite direction from ours. >Perhaps this is a good way to think of the difference. > Python thinks namespaces are one honking great idea > Ruby thinks OO is one honking great idea Rather, "Ruby thinks messages are one honking great idea"? They're both OO. I fail to see how namespaces are possible without OO. >Python's modules, classes, instances, and locals are all >namespaces. They happen to be specific types in a >type system which is nearly unified. > >Ruby's modules, classes, instances, and locals are all >instances, each of which defines its own namespace. Hmm, I think Python and Ruby both have both, although the emphasis may be different. In Python, an instance presupposes three entities: the instance, the name pointing to the instance, and the object that possesses the name, and in a sense "contains" it. (The nesting is artificial and accidental, though; really all objects are floating in a void, but only names make them accessable to one another--whence the structure arises.) Perhaps we can say the difference is that Python objects are extroverted (name points to another object; object possessing the name is transparent to itself), while Ruby objects are introverted (object possesses a message interface, which other objects talk to from the "outside")? I see a clear parallel between Python and analytic philosophy's approach to objects and accessing objects. (Their maxim is "a name is an idea that points to a thing", and of course since the thinker is a thing himself, names adhere in things, like people, books, etc.) I don't know what Ruby corresponds to, but it's not the name/thing duality, that's for sure. >(NB: I've never coded Ruby only read the docs and followed >the newsgroup for a couple of months, so my perception >can be wrong, but I suspect it isn't that wrong.) It's more insightful than my thoughts. However, I can't think of what the underlying difference is between messages vs. names. I don't think your proposal of Namespaces/OO quite works, because names are attached to objects. Objects are equally fundamental to both. What's different is how they concieve of the *relation* between objects, and how this difference is relating objects makes one conception "purer" OO than the other escapes me completely. -- Francis Avila From nospam at nospam.yes Wed Dec 3 05:45:15 2003 From: nospam at nospam.yes (Jon Arter) Date: Wed, 03 Dec 2003 11:45:15 +0100 Subject: redirecting Stdin References: <3FCDB2C3.B87DE2BE@alcyone.com> Message-ID: assume we have a file : after redirection sys.stdin = file('newinput') ----------------------------------- #newinput file import socket def detectip(): buf = socket.gethostname() remotehost = socket.gethostbyname(buf) return remotehost if __name__ == "__main__": print "Your IP address is", detectip() raw_input() ------------------------ using line=sys.stdin:readline() exec line This results in a parsing error when the file reading reaches the def detectip(): sentence . You can execute the command line as long as it is a single line command How to Get arround this ? With regards JON On Wed, 03 Dec 2003 01:54:11 -0800, Erik Max Francis wrote: >Jon Arter wrote: > >> Is is Possible to redirect the Python stdin in order to receive stdin >> commands from a file ? >> The time of redirection can last until exiting the Python and should >> be transparent for python it self. > >Sure: > > sys.stdin = file('newinput') From http Wed Dec 24 09:10:09 2003 From: http (Paul Rubin) Date: 24 Dec 2003 06:10:09 -0800 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: <7xfzfaqpby.fsf@ruckus.brouhaha.com> Christian Tismer writes: > > Sheesh, Aaron announces a database system that looks really spiffy from the > > examples, like ZODB without the pain of ExtensionClass, and the first two > > responses are griping about one aspect of it. Sometimes folks don't know > > when they're well-off. (Now if only he'd released it before I wrote the > > PyCon proposal tracker using PostgreSQL...) > > Yes, too bad. By that, Stackless would sit in the PyCon proposal > tracker. (and I want to have it everywhere) I think I started the griping; the issue is having to install a special Python implementation built around a feature with just one maintainer. On technical grounds Stackless is great and I hope PyPy can implement something like it. From http Tue Dec 2 21:03:07 2003 From: http (Paul Rubin) Date: 02 Dec 2003 18:03:07 -0800 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> <3fcc9577$0$7676$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <7xr7zmwtd0.fsf@ruckus.brouhaha.com> lutz at rmi.net (Mark Lutz) writes: > The Zaurus runs Qt directly on the frame buffer, so > there is nothing like X11 in the mix. Because of that, > the Tk library, and hence Tkinter, won't run out of > the box, afaik. I think that the OpenZaurus OS runs X11. At least for the SL5000/5500, lots of folks are replacing the Embedix/QT OS and Opera browser with OpenZaurus and Konqueror. From paul at boddie.net Wed Dec 17 06:34:22 2003 From: paul at boddie.net (Paul Boddie) Date: 17 Dec 2003 03:34:22 -0800 Subject: Is anyone using Python for .NET? References: Message-ID: <23891c90.0312170334.2cee015@posting.google.com> "Brandon J. Van Every" wrote in message news:... > It's a rare case where Microsoft is actually leading the industry > rather than cloning and conquering. The clone is now Mono, in the Unix > world. >From "Contracts and Interoperability - A Conversation with Anders Hejlsberg, Part V" [1]: "Anders Hejlsberg, a distinguished engineer at Microsoft, led the team that designed the C# (pronounced C Sharp) programming language... In 1996, after 13 years with Borland, Hejlsberg joined Microsoft, where he initially worked as an architect of Visual J++..." I'm no big fan of Sun or Java, but that's quite some industry leadership you're showing us, Brandon. ;-) Paul [1] http://www.artima.com/intv/interop.html From marc.lentz at ctrceal.caisse-epargne.fr Wed Dec 3 11:03:50 2003 From: marc.lentz at ctrceal.caisse-epargne.fr (marco) Date: Wed, 3 Dec 2003 17:03:50 +0100 Subject: Adding attribute to object Message-ID: hi I've got a class "myClass" ... and i CAN'T EXTENDS this class! But i can add NEW methods to "myClass", like that : method = new.instancemethod( myNewMethod , None, myClass) myClass.__dict__[method.__name__] = method i'd like to add NEW attributs to "myClass" ... i'm pretty sure it's possible (with "get/set-attr") ... but i don't know how to do that in fact, i'd like to wrap an newAttribut to an existingAttribut ... can anyone drop me 3 lines on how to do that ? From imbosol at aerojockey.invalid Sun Dec 14 22:03:52 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 15 Dec 2003 03:03:52 GMT Subject: continue and break frustration References: Message-ID: Glen Wheeler wrote: > Hello All. > > I've been coding in python for a reasonable amount of time now > (coding in total for approx. 20 years) and am writing a performance > intensive program in python. > The problem I'm having is I want to use break and continue to get > out from more than one level of loop. If I set a variable and then > check it my program will take too much of a performance hit. > Are there any alternatives people can think of? One thing you can do is use an else clause on your inner loop(s) to continue the surrounding loop. Then, following the else statement, put in a break. Then, a break in the innermost loop will cascade back to the top level. To illustrate: for i in xrange(100): for j in xrange(100): if (i,j) == (45,55): # Found a match. # Break out of the inner loop. break else: # No match was encountered in the inner loop. # Continue the outer loop. continue # The inner loop must have found a match. # So, break out of the outer loop, too. break For the above example, this gave me a not-quite-one-percent speed increase over the version using a variable. YMMV. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From duanek at chorus.net Wed Dec 17 17:56:04 2003 From: duanek at chorus.net (Duane Kaufman) Date: 17 Dec 2003 14:56:04 -0800 Subject: Solved: pyUNO Converter References: Message-ID: <59023571.0312171456.4948051a@posting.google.com> "Thomas Guettler" wrote in message news:... Nice work! One question though, doesn't this work only for OOo writer files (not Draw or Calc files)? I tried hacking it, and in the end, simply tried all output filters that put out PDF in succession, until one worked. I _know_ this is a hack, but I couldn't find any information on how to use pyUNO to query OO and return what _type_ of file it had opened..... How _does_ one do that, anyway? Thanks, Duane > Hi! > > This script will convert files to PDF with OpenOffice. > Other formats (html, doc ...) should be possible, too. > > Have a nice day, > thomas > > > # OpenOffice1.1 comes with its own python interpreter. > # This Script needs to be run with the python from OpenOffice.org: > # /opt/OpenOffice.org/program/python > # Start the Office before connecting: > # soffice "-accept=socket,host=localhost,port=2002;urp;" > # > > > # pyUNO Imports > > import uno > from com.sun.star.beans import PropertyValue > > # Python Imports > > import os > import sys > > > > # For a list of possible export formats see > # http://www.openoffice.org/files/documents/25/111/filter_description.html > # or > # /opt/OpenOffice.org/share/registry/data/org/openoffice/Office/TypeDetection.xcu > > export_format="writer_pdf_Export" > export_extension="pdf" > > def usage(): > print """Usage: %s in_dir out_dir > All files in in_dir will be opened with OpenOffice.org and > saved to out_dir > You must start the office with this line before starting > this script: > soffice "-accept=socket,host=localhost,port=2002;urp;" > """ % (os.path.basename(sys.argv[0])) > > def do_file(file, desktop, out_url): > # Load File > file=os.path.abspath(file) > url="file:///%s" % file > properties=[] > p=PropertyValue() > p.Name="Hidden" > p.Value=True > properties.append(p) > doc=desktop.loadComponentFromURL( > url, "_blank", 0, tuple(properties)); > if not doc: > print "Failed to open '%s'" % file > return > # Save File > properties=[] > p=PropertyValue() > p.Name="Overwrite" > p.Value=True > properties.append(p) > p=PropertyValue() > p.Name="FilterName" > p.Value=export_format > properties.append(p) > p=PropertyValue() > p.Name="Hidden" > p.Value=True > basename=os.path.basename(file) > idx=basename.rfind(".") > assert(idx!=-1) > basename=basename[:idx] > url_save="%s/%s.%s" % (out_url, basename, export_extension) > try: > doc.storeToURL( > url_save, tuple(properties)) > except: > print "Failed while writing: '%s'" % file > doc.dispose() > > def main(): > if len(sys.argv)!=3: > usage() > sys.exit(1) > in_dir=sys.argv[1] > out_dir=sys.argv[2] > out_url="file://%s" % os.path.abspath(out_dir) > print out_url > # Init: Connect to running soffice process > context = uno.getComponentContext() > resolver=context.ServiceManager.createInstanceWithContext( > "com.sun.star.bridge.UnoUrlResolver", context) > try: > ctx = resolver.resolve( > "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") > except: > print "Could not connect to running openoffice." > usage() > sys.exit() > smgr=ctx.ServiceManager > desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx) > > files=os.listdir(in_dir) > files.sort() > for file in files: > print "Processing %s" % file > file=os.path.join(in_dir, file) > do_file(file, desktop, out_url) > > if __name__=="__main__": > main() From belred1 at yahoo.com Sat Dec 6 13:07:38 2003 From: belred1 at yahoo.com (Bryan) Date: Sat, 06 Dec 2003 18:07:38 GMT Subject: Reading pipes in Python In-Reply-To: References: Message-ID: Rene Pijlman wrote: > Jeroen van der Ham: > >>f=open('/tmp/myfifo','r') >>while 1: >> print f.readline() > > > This loop is endless, so don't complain to us that it doesn't end :-) > > >>what can be done to make it work? > > > f=open('ff','r') > while 1: > li = f.readline() > if not li: break > print li, > wouldn't this work too? for line in file('/tmp/myfifo'): print line From fumanchu at amor.org Sun Dec 7 16:27:09 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 7 Dec 2003 13:27:09 -0800 Subject: Lists and Tuples Message-ID: Yup; as long as the docs are correct, it's not a huge issue. FuManChu > -----Original Message----- > From: Fredrik Lundh [mailto:fredrik at pythonware.com] > Sent: Sunday, December 07, 2003 1:30 PM > To: python-list at python.org > Subject: Re: Lists and Tuples > > > Robert Brewer wrote: > > > Now if somebody can just figure out why: > > > > threading.Thread(args=()) > > > > but: > > > > threading.Timer(args=[]) > > > > we'll have this topic nailed down pretty well. ;) > > different authors; the threading module itself is really old (1.5?), > but the Timer class was added in 2.2, and nobody spotted the > inconsistency at that time. > > not sure if this can/should be fixed; there might be someone out > there doing: > > t = threading.Timer(interval, function) > t.args.append(value) > t.start() > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From sandeep182 at hotmail.com Mon Dec 8 19:40:38 2003 From: sandeep182 at hotmail.com (Sandeep Gupta) Date: 8 Dec 2003 16:40:38 -0800 Subject: Converting a python script into a standalone application Message-ID: Hi, I've written a commercial application that uses Python scripts for some of the functionality. Installing the Python portion of the application requires me to first install Python, and then install the scripts. I'm looking for an easier way to install the Python portion. I've been referred to: http://www.mcmillan-inc.com/install1.html Which application would people recommend for creating a standalone executable? Are there any licensing issues I need to consider wrt including a "Python runtime" with my distribution? Thanks From tismer at tismer.com Mon Dec 15 21:25:57 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 16 Dec 2003 03:25:57 +0100 Subject: Does anybody really use frame->f_tstate ? Message-ID: <3FDE6D35.3090100@tismer.com> Hi colleagues, this is my second attempt to get rid of the f_tstate field in frames. I need to find every user of this field. What am I talking about? Well, Python always has a thread state variable which is a unique handle to the current thread. This variable is accessed in many places, and there exists a fast macro to get at it. Every executing Python frame also gets a copy on creation. In some cases, this frame->f_tstate field is used, in other cases the current tstate variable is used. If this sounds foreign to you, please stop reading here. ------------------------------------------------------------- I would like to get rid of the frame->f_tstate, and I'm trying to find out if there is a need for it. I don't need it, for Stackless, it is the opposite, it disturbs. There was a small thread about this in June this year, where Guido convinced me that it is possible to create a traceback on a frame that comes from a different thread. http://mail.python.org/pipermail/python-dev/2003-June/036254.html Ok, this is in fact possible, although I don't think anybody has a need for this. My question to all extension writers is this: If you use frame->f_tstate at all, do you use it just because it is handy, or do you want to use it for some other purpose? One purpose could be that you really want to create a traceback on a different than the current thread. I have never seen this, but who knows, so that's why I'm asking the Python world. In most cases, a traceback will be created on a frame that is currently processd or just has been processed. Accessing a frame of a different thread that is being processed might make sense for special debugger cases. My proposal is -------------- a) change semantics of PytraceBack_Here to use the current tstate. b) if such a special purpose exists, create a new function for it. c) if urgent, different needs exist to keep f_tstate, then let's forget about this proposal. Especially for Stackless, I'd be keen of getting rid of this. thanks for input -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From edreamleo at charter.net Sun Dec 7 13:15:50 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Sun, 7 Dec 2003 12:15:50 -0600 Subject: Leo 4.1 beta 5: An outlining editor References: Message-ID: > For the first time in months there are no serious bugs outstanding. I spoke too soon. There is an extremely serious bug that arises when cutting from 3.x versions of Leo and pasting to 4.x versions of Leo. The entire .leo file can get corrupted. The workaround is to convert all .leo files to 4.1 format. My apologies for this bug; it will be fixed in 4.1 beta 6, due in about a week. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jsbenson at bensonsystems.com Sat Dec 13 15:34:45 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 13 Dec 2003 12:34:45 -0800 Subject: Lua, Lunatic and Python Message-ID: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Hi, I checked out Lua as much out of curiosity about its Brazilian background as for any other reason. It seems to be a project centered in the PUC (Pontifical Catholic University of Rio de Janeiro). Since Brazil produced Ant?nio Carlos Jobim, I figured I better check out Lua. After checking out www.lua.org and searching for comparisons with Python, the most informative document I ran across was this: http://lua-users.org/wiki/LuaVersusPython I'll just sum up what I think I found out about Lua and let people comment if I've gotten anything wrong: Lua is an embeddable scripting language popular with game developers who are very sensitive to footprint and speed. In Python, we tend to get most excited about elegance and conceptual efficiency. When speed becomes important, someone goes out and reimplements useful things as C extensions (as in pickle/cpickle). There seems to be a Lispy background to Lua, as there is to Python. The Lua community sounds pretty excited, and seems to be recapitulating the fervor of early Python adopters. We'll probably have to sit up and take notice once there's an O'Reilly animal book on it, or if we need to write a game. I'll make some predictions now: in a few years there will be flame wars at lua.org between the people wanting to keep distinguishing characteristics of Lua (fooprint and speed) intact, versus the incorrigible programmers who will inevitably add feature after feature to their favorite language until it approaches Pythonesque proportions. Among these features, of course, will be memory- and infrastructure-intensive operations leading to language bloat. In short, there is (and will most likely be) nothing new under the sun as far as evangelical fervor and the dynamics of programming language evolution go. I'll cross post to lua.org and see what happens: Um f? de Python deseja boa sorte ? turma de Lua! From TyBriD at si.rr.com Fri Dec 19 06:28:48 2003 From: TyBriD at si.rr.com (TyBriD) Date: Fri, 19 Dec 2003 11:28:48 GMT Subject: The Truth? Message-ID: i have 100% no programming experience but i have read some VB6 and parts of C++ books never stuck with it because it was to confusing, but i was told python is a great place to start is that true?. if so is there specifi parts to learn and start off with n why links would be great thanks. From peter at engcorp.com Fri Dec 5 23:16:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 23:16:40 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> <213df9a1.0312051515.75541432@posting.google.com> Message-ID: <3FD15828.BB14FC0F@engcorp.com> Arthur wrote: > > "Fredrik Lundh" wrote in message > > I'm never dead wrong. [snip] > > I should know better than to have anything to say here. [snip] > But am surprised to see a point trumped here, simply by quoting Guido. "Simply" being the operative word, or perhaps "trumped"... I think you're missing context, which was an apparent(*) claim that point of view A was _universally correct_ while B was "dead wrong". By referring the Guido's comment, I believe Fredrik was "simply" indicating that he couldn't have been "dead wrong" by any usual definition of that term, as at least one other person (perhaps only coincidentally the BDFL) shared the same view. -Peter (*) As was clarified later, the "dead wrong" comment was actually intended to be a sort of rudeness objection, and not at all a contradiction of the B point of view, as it appeared to be. From j.r.gao at motorola.com Tue Dec 16 22:43:57 2003 From: j.r.gao at motorola.com (J.R.) Date: Wed, 17 Dec 2003 11:43:57 +0800 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: > As penance for having failed to do this, > I assign a more mysterious problem to you: > > def f(d=[]): > d.append(0) > print d > f() > f() > > Explain results. When is d bound? > I found that the "problem" showed above is caused by the python principle "everything is object". Here the function "f" is an object as well, the object function f is created once this function is defined. And there is tuple attribute(func_defaults) inside function object to record the default arguments. >>> def f(d=[]): print id(d) d.append(0) print d >>> f.func_defaults ([],) >>> id(f.func_defaults[0]) 11279792 >>> f() 11279792 [0] >>> f() 11279792 [0, 0] >>> f([1]) 11279952 [1, 0] 1. There is no value passed to the default argument The name "d" is bound to the first element of the f.func_defaults. Since the function "f" is an object, which will be kept alive as long as there is name (current is "f") refered to it, the list in the func_defaults shall be accumulated by each invoking. 2. There is a value passed to the default argument The name "d" will be bound to the passed object, it's proven from the different identity showd above. I think we could eliminate such accumulation effect by changing the function as follow: >>> def f(d=[]): d = d+[0] print d J.R. From shoot at the.moon Fri Dec 19 16:38:32 2003 From: shoot at the.moon (Steve Horsley) Date: Fri, 19 Dec 2003 21:38:32 +0000 Subject: Newbie Question HELP! In-Reply-To: References: Message-ID: TyBriD wrote: > hello guys i am new top programming and was told python is the best place to > start i so far understand variables ex: > print ("Fill In Below") > name = raw_input("Enter Your Name Please: ") > age = input("Enter Your Age Please: ") > print "Your Name Is", name > print "Your Age Is", age > > but i was wondering if there was a way to compile a EXE file to display the > print because this only seems to run in python shell, or is there a way to > create my own interface for my program in python thanks in advanced > > I think you can make a windows shortcut that launches a command something like: command \c python myapp.py which will give you a clickable launcher. If you're after a proper GUI, this is a much bigger thing and I suggest that you avoid it for some months until you are more familiar with the programming basics. HTH Steve From jcollins_boulder at earthlink.net Tue Dec 9 18:56:01 2003 From: jcollins_boulder at earthlink.net (Jeffery D. Collins) Date: Tue, 09 Dec 2003 16:56:01 -0700 Subject: Dec 15, 2003 -- FRPythoneers Meeting Message-ID: <3FD66111.2060202@earthlink.net> We will be meeting this month informally (i.e., no speaker) at Caffe Sole' in Boulder on monday, December 15. Join us for coffee and Python (and other techie) conversation! Wireless access is available, so bring your laptop/notebook. Where: Caffe Sole', 637 S. Broadway, Boulder, http://www.caffesole.com When: Monday Dec 15, 7pm -- See you there! -- Jeffery Collins Front Range Pythoneers From jepler at unpythonic.net Wed Dec 17 08:09:18 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 17 Dec 2003 07:09:18 -0600 Subject: why are these exec times so different? In-Reply-To: References: Message-ID: <20031217130910.GB2664@unpythonic.net> On Wed, Dec 17, 2003 at 01:09:06AM +0000, r.e.s. wrote: > Should one expect the following execution times > to be so different? ... No reason comes immediately to mind. Usually, def f(): suite f() will run a little faster than suite because LOAD_FAST variable references, which are used inside functions for function-scope variables but not at the module top-level scope, are speedier than LOAD_NAME and LOAD_GLOBAL codes. So it's safe to say that the real reason for this huge difference in the favor of the "global scope" version lies in your code somewhere. The part you didn't post. Jeff From db3l at fitlinxx.com Thu Dec 11 19:47:03 2003 From: db3l at fitlinxx.com (David Bolen) Date: 11 Dec 2003 19:47:03 -0500 Subject: exit code on windows References: Message-ID: Mark McEahern writes: > Is there a straightforward way to get the exit code from a windows > process? It's the result of the close on the handle returned from the os.popen* calls. For Windows, in the case of the variants returning more than a single handle, you'll get the exit code when you close the last handle, and unlike Unix, it's not a "wait"-encoded value but just the actual result code from the child process. > I want to write a script that runs a bunch of .sql files against SQL > Server using osql. I want it to stop if there's an error; e.g., > > import os > import glob > > server = 'foo' > database = 'bar' > template = 'osql -s%(server)s -d%(database)s -f%(name)s' > for name in glob.glob('*.sql'): > cmd = template % locals() > stdin, stdout = os.popen2(cmd) > output = stdout.read() > print stdin.close() > print stdout.close() > # On Unix I'd use the return value from the fd.close() > # to get the exit code, but on Windows the return values > # here are: > # None > # None The above should work fine, although actually I'm interested in your Unix comment since I thought under Unix you had to use popen2.Popen3/4 and then use wait() on the resulting objects to get an exit code. But in any event, it should be fine under Windows (with the final child process result coming back from the stdout.close() in the above example). Are you sure that osql is returning a non-zero result? Zero result codes are translated to a None return. A quick test for me seems to work: rc.py import sys sys.exit(10) rctest.py import os stdin, stdout = os.popen2('python rc.py') output = stdout.read() print stdin.close() print stdout.close() > python rctest.py None 10 Now this is with Win2K (or NT/XP). The Win9x series do have a bit of an issue bubbling up result codes in general, but Python has a helper module (w9xpopen.exe) that should work around that. One except in either case can be if you explictly use a top level command.com/cmd.exe since I think they end up absorbing the exit code of the command they run. -- David From fredrik at pythonware.com Tue Dec 16 09:48:48 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Dec 2003 15:48:48 +0100 Subject: Converting integer to binary representation References: <200312161526.25612.m.dufour@student.tudelft.nl> Message-ID: "Mark Dufour" wrote: > I need to convert an integer into some binary representation. I found the > following code in the online cookbook (adapted to return a list): > > binary = lambda n: n>0 and [n&1]+binary(n>>1) or [] > > This is sure nice, but I'm wondering why something like this doesn't seem to > be in the standard library, for example by formatting with '%b' % number. I > can't think of a any reason for not doing it this way, as working with binary > representations is quite common in programming, really? what kind of programs are you writing? (in my experience, binary numbers only appear in programming text books. humans tend to use decimal numbers, and programmers use octal or hexadecimal numbers when they need to "access the bits"). From christian.eslbauer at liwest.at Tue Dec 30 08:21:46 2003 From: christian.eslbauer at liwest.at (EsC) Date: Tue, 30 Dec 2003 14:21:46 +0100 Subject: function-arguments by reference Message-ID: <1072788957.24786@news.liwest.at> Hy! is it possible to pass function-arguments by reference? (for example in PHP you can use the "&" operator ... ) thx iolo From bvdpoel at kootenay.com Mon Dec 8 13:41:27 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Mon, 08 Dec 2003 11:41:27 -0700 Subject: Nub needs help withTkinter In-Reply-To: <1cca69c7.0312081017.27140c39@posting.google.com> References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> <1cca69c7.0312081017.27140c39@posting.google.com> Message-ID: <3fd646b2_1@dns.sd54.bc.ca> Agency wrote: >>You will need to __bind__ a callback to the key press on a widget. >>something like :- >> >> >> >>from Tkinter import * >> >> >>root=Tk() >>lab = Label(root, text = "Beat Counter : ") >>lab.pack() >> >>beats = 0 >> >> >> >>def beatCounter(event): >> print "increment counter" >> global beats >> beats = beats + 1 >> lab.config(text = "Beat Counter : %d" %beats) >> >>def beatReset(event): >> print "reset counter" >> global beats >> beats = 0 >> lab.config(text = "Beat Counter : %d" %beats) >> >> >>root.bind("", beatCounter) >>root.bind("", beatReset) >> >> >>root.mainloop() >> >> >>You should rewrite the above so it does not use the global statement >>('cause thats cheating!) >> >> >> >>HTH >>Martin > > ------------------------------------------------------------------------- > Wow. Thats perfect. I'm not sure what you meant about the global > statement, this is my first time trying to program anything, but I'll > look through the docs and see if I find something out. Now, I just > have figure out how this codes works and have it correspond to a clock > function on a display, which gives the bpm. > > Thanks, I was getting rather frustrated. I'll post back if I get > stumped. Or look on my website for the countbeats program I wrote awhile ago. I think this is what you're trying to do ... but no reason not to reinvent the wheel if you want :) -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From dennis.posadas at intel.com Wed Dec 10 01:56:46 2003 From: dennis.posadas at intel.com (Posadas, Dennis) Date: Wed, 10 Dec 2003 14:56:46 +0800 Subject: how do i get a "wide build" precompiled python w support unicode higher than 'ffff' Message-ID: I don't want to have to compile python, but I need one ready to support unicode that includes CJK. Dennis From enrique.palomo at xgs-spain.com Thu Dec 11 04:46:41 2003 From: enrique.palomo at xgs-spain.com (Enrique) Date: Thu, 11 Dec 2003 10:46:41 +0100 Subject: seek in a zip file?? Message-ID: <000b01c3bfcb$ae8f7790$7a010a0a@epalomo> hello all! i?m working with big size files, to maintain them, it would be better to compress the files. to recover a little part of the big file, how can i extract that little parte instead of the whole file that will bring a lot of time? Can i know the offset in a zip file?? i know the offset in the big one. Any idea will be welcome. Thanks. Enrique Madrid- Spain **AVISO DE CONFIDENCIALIDAD** La informaci?n contenida en este mensaje y archivos es privada y confidencial estando dirigida solamente al destinatario. Si Ud. ha recibido esta informaci?n por error, por favor, proceda a su inmediata destrucci?n. Cualquier opini?n o punto de vista contenido en este mensaje corresponde al remitente y necesariamente no representa la opini?n del GRUPO XEROX. From youdontneedtosendme at email.com Mon Dec 15 17:34:20 2003 From: youdontneedtosendme at email.com (Gouda Man) Date: Mon, 15 Dec 2003 22:34:20 GMT Subject: Weirdness when trying to use Boost.python Message-ID: I'm planning to write a large program that will have advanced scripting in python in which the scripter will subclass c++ objects to add functionality. this leads me to boost.python (if you dont already know about boost.python dont bother reading farther cause its a kind of a technical question) anyways i embeded python in a litte c++ test app i wrote and got it working fine. eg: i could write a little python program and my app would load and run it. then i added boost.python to expose a sample class to the python code. i think i know how to use boost cause i basically followed the tutorial and the code compiles fine but the module boost is supposedly creating doesn't exist when the code (python code) is run . now if i use just the C python API can can interface some simple functions but not classes. there is an api which creates the module based on a object returned from another api. Now i cant get boost to give me that object. since there is no readily apparent way of doing this i assumed that boost did i t automatically but this apears not to be true. Also looking at the boost source was just more confusing. everyting uses INSANE macros which call other macros though 50+ include files so no help there. the boost documentation talks about exposing classes and embedding python but not the two together. Any ideas? Oh also just FYI: I'm running XP Prof, using VC++ 6 SP5, Python 2.3.2, and the current CVS of Boost cause the release only supports python 2.2.x. From m.dufour at student.tudelft.nl Wed Dec 17 05:41:16 2003 From: m.dufour at student.tudelft.nl (Mark Dufour) Date: Wed, 17 Dec 2003 11:41:16 +0100 Subject: Python as a numerical prototyping language. In-Reply-To: <20031217095358.GA34626@hishome.net> References: <20031217095358.GA34626@hishome.net> Message-ID: <200312171141.16254.m.dufour@student.tudelft.nl> > When operations are done on individual objects Python is significantly > slower than compiled languages but psyco is making great progress in this > area. It already approaches the performance of C for simple code using > only integers and floats. What are the opinions about Psyco being able to achieve the same great speedups for non-simple code at some point in the future? Is the looking up of methods/attributes during run-time the biggest problem here? I would assume that with ever-increasing computer speeds there's no theoretical limit to what might be possible here.. exciting stuff, this! Mark Dufour. -- "The employment agency has selected an immature and unproven software package and its functionality is at the best close to Office 97," said Microsoft representatives. From http Tue Dec 16 04:09:26 2003 From: http (Paul Rubin) Date: 16 Dec 2003 01:09:26 -0800 Subject: More info on my Python problem.... References: Message-ID: <7x7k0x86yh.fsf@ruckus.brouhaha.com> JD writes: > If my code causes Python to just hang up, and not allowing me > to break out with control-C or control-D, is there a way to > find out what's going on? I don't think it's going into some > infinite loop, because I can usually break out of them with > control-C. What would cause the Python run-time system > to just loose things? The console is dead, but it echo's > carriage returns but that's all it does. Can you hit ^Z and escape to the shell? Can you switch to another virtual console and see what's going on? What does the program do? > Is there someone who I might contact > via phone to walk me through this? (Assuming I can't get adequate > information here? Or does anyone care about Python bugs?) Yes of course people care about Python bugs, but if you want personalized phone consulting you'll probably have to pay for it. If you're willing to do that, I'm sure plenty of us here are available. > How should I approach debugging this? Are there Python tools? Or > should I use gdb? ktrace? systrace? I'm assuming I have to do this, > as a bug report which reads "Python locks up" isn't too useful. If worse comes to worse you may have to run Python under gdb. Is your program using multiple threads? From tjreedy at udel.edu Sun Dec 21 12:45:46 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 12:45:46 -0500 Subject: dynamic typing questions References: Message-ID: <0r6dnWS30NLVQXiiRVn-uw@comcast.com> "Jason Tesser" wrote in message news:mailman.352.1071846222.9307.python-list at python.org... > The other programmer here is very concerned about > dynamic typing though in Python. He feels like this > would be too much of a hinderance on us and too easy > for us to make a mistake and not catch it until > runtime making debugging harder. One problem with static typing is that the type you want is too often not one of the types you have immediately available. It may be a subset or union thereof. If log(-1.0) passes the compiler, then you get a runtime crash that is at most as graceful as Python's default traceback. If log(1) does not pass the compiler (if it does not autocast to float), then you are delayed until you stick in the 'missing' decimal point. The corresponding advantage of Python's dymanic typing is that functions are generic; they work with any data that works and is not specifically excluded. C preprocessor text macros such as (untested, written from years ago memory) #define max(a,b) ((a) > (b) ? (a) : (b)) /* beware of double side-effects */ that implement generic pseudofunctions testify to the usefulness of this. Terry J. Reedy From r.s at XXmindspring.com Wed Dec 17 15:49:35 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Wed, 17 Dec 2003 20:49:35 GMT Subject: why are these exec times so different? References: Message-ID: To show that what I'm seeing isn't because of local/global differences, here are dummy functions that exhibit the same behavior. (And I've tried to minimize os background activity, etc, when testing.) The results are consistently repeatable: For the given string s, f1(s) takes >10 times longer to run than f2(s) -- f1(s) and f2(s) return the same value, and contain essentially the same code, except that f2 calls function g to do the common inner loop: def f1(s): """ do outer & inner loop """ D = {} for i in xrange(len(s)): for j in xrange(len(s)-i+1): D[s[j:j+i]] = True return len(D) def f2(s): """ same as f1, but call g to do inner loop """ count = 0 for i in xrange(len(s)): count += g(s,i) return count def g(s,i): """ the common inner loop """ D = {} for j in xrange(len(s)-i+1): D[s[j:j+i]] = True return len(D) def string01(n): """Return first n chars of a fixed pseudorandom string.""" random.seed(0) return ''.join([ random.choice('01') for i in xrange(n) ]) import random, time s = string01(1000) t0 = time.clock() test, count = 'f1:', f1(s) #test, count = 'f2:', f2(s) t1 = time.clock() print test, count, t1-t0 From try_vanevery_at_mycompanyname at yahoo.com Wed Dec 17 23:27:16 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 17 Dec 2003 20:27:16 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: "Paul Boddie" wrote in message news:23891c90.0312170334.2cee015 at posting.google.com... > "Brandon J. Van Every" wrote in message news:... > > It's a rare case where Microsoft is actually leading the industry > > rather than cloning and conquering. The clone is now Mono, in the Unix > > world. > > From "Contracts and Interoperability - A Conversation with Anders > Hejlsberg, Part V" [1]: > > "Anders Hejlsberg, a distinguished engineer at Microsoft, > led the team that designed the C# (pronounced C Sharp) > programming language... In 1996, after 13 years with > Borland, Hejlsberg joined Microsoft, where he initially > worked as an architect of Visual J++..." > > I'm no big fan of Sun or Java, but that's quite some industry > leadership you're showing us, Brandon. ;-) *I'm* showing you? Since when was I Microsoft? I guess your point is whether you think Java or .NET is responsible for the interop principles of .NET. I'd say the latter, since otherwise, it would be Java and we'd all be doing our language interop in Java. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From claird at lairds.com Thu Dec 11 11:31:12 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 16:31:12 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: In article <7xad5z1jq5.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >Brian Kelley writes: >> Why forget Tkinter? I've seen Tkinter applications that look >> incredibly fabulous. > >Got any url's for screen shots? . . . is an easy almost-answer. Tkinter-based ones will take just a bit longer ... -- Cameron Laird Business: http://www.Phaseit.net From newsgroups at jhrothjr.com Wed Dec 24 08:11:50 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 24 Dec 2003 08:11:50 -0500 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: "Moosebumps" wrote in message news:%QbGb.2109$1f6.732 at newssvr25.news.prodigy.com... > I've googled all over for this but can't find an answer... > > I'm fairly new to Python, and wondering if you can just list a bunch of > objects as data. For example, in C you would just do something like this: > > struct > { > int a; > float b; > } mystruct; [rest snipped] As Francis Avila said in another response, why would you really want to do this? However, if you do, there are a couple of easy ways. [untested code] class someData: pass a = someData() a.__dict__.update({item1: "Hi", item2: "there"}) print "%s %s" % (a.item1, a.item2) --> "Hi there" However, frankly it's easier (and much clearer) to use a dictionary: a = {} a.update({item1: "Hi", item2: "there"}) print "%(item1)s %(item2)s" % a --> "Hi there" HTH John Roth > > thanks, > MB > > From claird at lairds.com Thu Dec 4 13:44:11 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Dec 2003 18:44:11 -0000 Subject: SUSPECT: Re: Python, xml, databases, ... References: Message-ID: In article , Pieter Claerhout wrote: >SQLite is easier to embed since you don't need to install anything >seperately. Include the neccesary Python modules and shared libraries, and >you can create databases. With Firebird, MySQL and PostgreSQL, you need to >install separate software. If I'm not mistaking, performance wise, SQLite >will be faster, but I'm not sure how it handles large databases (let's say >100 MB or more). . . . I'm working with production SQLite databases of over 80 MB, and its performance is just great. -- Cameron Laird Business: http://www.Phaseit.net From skip at pobox.com Thu Dec 18 15:01:04 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 14:01:04 -0600 Subject: Broken python-model.el In-Reply-To: References: <877k0uhrlv.fsf@pobox.com> Message-ID: <16354.1920.405789.548101@montanaro.dyndns.org> Peter> Initial impressions is that I will re-download the 4.6 version Peter> available from the python web-site. One of the annoying things Peter> that hits you right in the face (and this is terribly unfair to Peter> the sourceforge team working on it! - it hasn't been released Peter> after all :-)) is the "blind" fontification of what are believed Peter> to be Python keywords by the authors. Peter> This list includes words such as "Exception", "ord", "self" plus Peter> a host of others. So variables that I have such as "swimrecord" Peter> has the "ord" portion font coloured differently from the rest of Peter> the string, "ChildException" has the "Exception" differently Peter> coloured than the "Child" portion, "self" is a different colour Peter> from the rest of the variable usage i.e. self.Name has "self" and Peter> "Name" colourised differently - extremely annoying and *not* what Peter> I expect the authors want to achieve! Certainly not what I want Peter> in an edit session! :-) That's a feature I added recently. It's intended to highlight variables which might be shadowing builtins. Eventually, it should be a user-configurable feature. I checked in a fix to the "trailing builtin" problem a couple days ago. Have you tried that yet? Skip From aahz at pythoncraft.com Tue Dec 30 09:42:47 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2003 09:42:47 -0500 Subject: Python 2.3 startup is slow (was Re: [Mailman-Developers] python is slow) References: Message-ID: In article , Andrew MacIntyre wrote: > >Pity that the startup phase took a hit, which impacts some usage (eg CGI >scripting) negatively in spite of the gains once the interpreter is >running :-( In theory that's fixable; that all comes from the fact that 2.3 is now loading more modules at startup. In fact, last June Guido declared that a must-fix bug, but it dropped below the radar and we had to punt when Apple needed 2.3 quickly. Anyone who wants to take a stab at working on it would be most welcome. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From stephen at dino.dnsalias.com Thu Dec 18 21:20:08 2003 From: stephen at dino.dnsalias.com (Stephen J. Bevan) Date: Fri, 19 Dec 2003 02:20:08 GMT Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> <3FE1C42D.6050505@steinkuehler.net> Message-ID: Charles Steinkuehler writes: > Stephen J. Bevan wrote: > > Charles Steinkuehler writes: > > >> Using a forth-based solution to create the root ramdisk image would > >> drastically reduce the footprint of the initial ramdisk image, remove > >> reliance on a particular C runtime library (allowing folks to build > >> runtime root images based on uClibc, glibc, or whatever), and provide a > >> *VERY* powerful yet tiny runtime scripting/programming language for > >> extending the system. > > IMHO what drastically reduces the footprint is not using glibc at > > all. > > Which is why I think that a small Forth kernel talking directly to the > linux kernel is the best solution. It is probably the smallest solution. Whether it is best depends on which languages you prefer to use and how much you are willing to trade space for time to use that language. Given a choice between siod and my own Forth (3.4KB under Linux) I'd probably take siod for scripting tasks unless I was really desperate for the 90KB that I could save by using my Forth. That's because all else being equal I prefer to write in Scheme rather than Forth, though things aren't always equal which is why I use Forth for some tasks From mwh at python.net Thu Dec 18 09:17:23 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Dec 2003 14:17:23 GMT Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: Gerrit Holl writes: > Tim Churches wrote about the Zen of Python: > > It is entirely possible to do programming in Perl, but the results bear > > little resemblance to these desiderata. > > Ok. > > So the Zen of Python shouldn't *be called* the Zen of Programming. No, it should be called "19 Pythonic Theses", which has the advantage of being vaguely accurate... -- > so python will fork if activestate starts polluting it? I find it more relevant to speculate on whether Python would fork if the merpeople start invading our cities riding on the backs of giant king crabs. -- Brian Quinlan, comp.lang.python From mcfletch at rogers.com Wed Dec 3 15:22:07 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Dec 2003 15:22:07 -0500 Subject: diferences between 22 and python 23 In-Reply-To: References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE3352.2040504@rogers.com> Message-ID: <3FCE45EF.5010600@rogers.com> Fredrik Lundh wrote: >Mike C. Fletcher wrote: > > > >>>0xED has never been a valid 7-bit ASCII character. >>> >>> >>Sure, but Python used to accept 8-bit characters in the platform's >>default encoding as part of string characters... >> >> > >all 2.3 installs I have give me a DeprecationWarning when I do that, >not a UnicodeDecodeError. > >what version are you using? > > Hmm, obviously none of 2.3. Oops! Sorry about that. I had to change resourcepackage to support this change (user error reports) and hadn't cottoned on to the fact that it's just a warning. I haven't upgraded to 2.3 for my general development, so I didn't realise this wasn't yet a hard error. I had thought there was a way to get an ASCII decoding error from the above... hmm. Guess not... strange... I've *seen* those errors show up when testing code for a new version (and I'd though it was of Python). Enrique, by any chance are you working with a library (such as wxPython) where the version under 2.2 is a non-unicode build and the version under 2.3 is a unicode build? Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From http Sun Dec 14 00:44:52 2003 From: http (Paul Rubin) Date: 13 Dec 2003 21:44:52 -0800 Subject: continue and break frustration References: Message-ID: <7xiskk6jhn.fsf@ruckus.brouhaha.com> Glen Wheeler writes: > I've been coding in python for a reasonable amount of time now > (coding in total for approx. 20 years) and am writing a performance > intensive program in python. > The problem I'm having is I want to use break and continue to get > out from more than one level of loop. If I set a variable and then > check it my program will take too much of a performance hit. > Are there any alternatives people can think of? Raise an exception and catch it. However, if your function is that sensitive to a little thing like that, maybe you need to write it differently, for example in Pyrex or as a C extension. You could also try the Psyco compiler. From tjreedy at udel.edu Fri Dec 19 10:04:53 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Dec 2003 10:04:53 -0500 Subject: [Python-Dev] rexec.py unuseable References: <20031215191023.GB26055@lkcl.net><1071524194.15985.660.camel@localhost.localdomain><20031215233639.GE26055@lkcl.net><20031216195525.GJ17021@lkcl.net><20031216212312.GL17021@lkcl.net><20031218092922.GF6324@lkcl.net> Message-ID: "Luke Kenneth Casson Leighton" wrote in message news:mailman.327.1071788246.9307.python-list at python.org... [technical proposal snipped] I do not have the techical knowledge to evaluate this > I simply don't > have enough knowledge of the python codebase to do that on my own. > [unless someone was happy to pay me for long enough to find out, > of course]. But I can offer these thoughts for your consideration: * The money issue applies in one way or another to all the developers: at the moment, I don't believe anyone is employed specifically to develop Python and just do that. * The main developers are, generally, people who find Python useful as it is. Their motivation for student/volunteer/bootleg/when-possible work is mostly to make it more useful for the things it can currently do. * Safely running untrusted and quite possibly antagonistic code is a small part of the usage universe. The impetus for extending current or future Python to do this effectively will have to come from people from whom this is important enough to donate time, effort, expertise, and possibly money. (Yes, you are doing some of this, but you seem to expect someone else to pick up and run with the ball you have tossed on the field.) > in some ways, the longer this is left, the harder it is going to > be to retrospectively bolt on. > there's an adage that says security cannot be easily added in, it > has to be designed in from the start. > fortunately, i think there are a lot of smart people about :) Some of them have started the PyPy project to rewrite the interpreter in Python. If successful, this will make interpreter experimentation easier for Python programmers. It might even become the reference implementation for Python 3. Since this project is (officially) just a year old (versus about 15 years), you might be able to help design security 'in from the start'. Terry J. Reedy From pythonguy at Hotpop.com Tue Dec 23 01:03:26 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 22 Dec 2003 22:03:26 -0800 Subject: Count Files in a Directory References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: <84fc4588.0312222203.201c7ac3@posting.google.com> os.walk() does not follow symlinks to avoid infinite recursions. This could be the reason for the difference in reported count. Qouting from python docs for 2.3, """Note: On systems that support symbolic links, links to subdirectories appear in dirnames lists, but walk() will not visit them (infinite loops are hard to avoid when following symbolic links). To visit linked directories, you can identify them with os.path.islink(path), and invoke walk(path) on each directly.""" You can do something like this. dir_count, file_count = 0, 0 #untested code! def dircount(path): for root, dirs, files in os.walk(path): dir_count += len(dirs) file_count += len(files) if os.path.islink(path) and os.path.isdir(path): dircount(path) HTH. -Anand Peter Otten <__peter__ at web.de> wrote in message news:... > hokieghal99 wrote: > > > The os thinks there are 12,204 objects in the path while Python > > thinks there are 12,205 objects. > > If it's always one more directory then it could be the initial directory > setpath (ugly name, by the way) that is counted by the os but not by your > function. To fix it, you could initialize > > dir_count = 1 # instead of 0 > > Peter From Markus.Franke at informatik.tu-chemnitz.de Tue Dec 30 04:56:24 2003 From: Markus.Franke at informatik.tu-chemnitz.de (Markus Franke) Date: Tue, 30 Dec 2003 09:56:24 +0000 (UTC) Subject: Python and Tk: Error on Memory Access Message-ID: Hi, i have a problem using Tk with python. Here is a simple script: import Tkinter root=Tkinter.Tk() button=Tkinter.Button(root,text="Click") button.pack() I can see a Window with a Button in it. But the problem now is that every time I enter the Button with the Mouse-Arrow, the Program stops with a "Failure on Memory Access"... in German "Speicherzugriffsverletzung". I have tried several versions of python, Tk and Tkinter but without success. My System: Red Hat 9(Severn), Kernel 2.4.21-20.1.2024.2.1.nptl python 2.2.3 / I tried also version 2.3.2 Tk-8.3.5-88 Tkinter 2.2.3-26 Hope anyone can help me. Thanx, Markus From tjreedy at udel.edu Sun Dec 21 12:02:04 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 12:02:04 -0500 Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: "Bengt Richter" wrote in message news:bs1lov$3vu$0 at 216.39.172.122... > That's useful, but IMO not the optimal syntax, because cache here is really not > being used as a parameter. That's why I would like a way to bind locals similarly > without being part of the calling signature. E.g., > > def _tento(n)( > # preset bindings evaluated here at def-time > cache={} > ): > try: > return cache[n] > except KeyError: > answer = cache[n] = 10L ** n > return answer I have also thought of using a ';' as in def _tento(n; cache = {}): [etc] to indicate a def-time initialized non-parameter. Terry J. Reedy From brian at zope.com Thu Dec 4 10:15:03 2003 From: brian at zope.com (Brian Lloyd) Date: Thu, 4 Dec 2003 10:15:03 -0500 Subject: Any interest in a Python for .NET sprint at PyCon 04? Message-ID: Hi all - It looks like there is the possibility of having a Python for .NET sprint at PyCon '04 - if you would be interested in attending, pls reply to me directly and let me know. Some possible sprint ideas could be: - Work on the embedding api - Implement more demos in Python for the distro - Allowing Python code to implement abstract .NET classes and interfaces - Preparing for generics and other CLR 2.0 features Brian Lloyd brian at zope.com V.P. Engineering 540.361.1716 Zope Corporation http://www.zope.com From jjl at pobox.com Fri Dec 5 12:13:50 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Dec 2003 17:13:50 +0000 Subject: When is bare except: justified? Message-ID: <873cbzmbld.fsf@pobox.com> Bare "except:", with no exception specified, is nasty because it can easily hide bugs. There is a case where it seemed useful to me in the past. Now it seems like a bad idea to me (but I think I might still be confused about it, hence this post). It's this: When you're processing a input from a file-like object connected to an external source like a network connection, disk file etc, you have to expect broken, and often malicious, data (especially from data that arrived from the internet, of course). except: seemed to me like a good way of dealing with data that tripped up tacit assumptions in my code about the data. First example: I have a method that reads cookie data from an HTTP response and processes it. If the data is malformed in a way I didn't anticipate, it seems like it would be nice if the code ignored it rather than crashing the application using my library, or forcing the application to halt all processing just because of one little bit of bad data. Still, if you take the attitude that malformed data should be explicitly detected by the code (whether by catching an exception or doing a direct "look before you leap" test), rather than relying on unexpected exceptions, this technique could be seen as hiding a bug every time it successfully does its job! So I suppose I should just let the exception propagate, regard any exceptions that show up as bugs, and fix them. It is of course often useful to let exceptions do the work, reducing lines of code and avoiding race conditions by not explicitly checking things. But, even when faced with malicious network data, I suppose that's only justified when you understand with reasonable specificity which exceptions are going to be raised and for what reason -- and my use of except: definitely does not fall into that category. Even more doubtfully, I have a pair of methods .save() and .load(). .save() is straightforward: it writes the object's state to a disk file. .load() loads new data from a disk file, *appending* to the data held by the object. .load() is supposed to raise IOError when something goes wrong (IOError is probably the wrong class here, but that's another issue). .load() makes sure it only raises that error by catching everything then re-raising IOError: I do this like so: try: self.load_data() except: reraise_unmasked_exceptions((IOError,)) raise IOError("invalid file format") def reraise_unmasked_exceptions(unmasked=()): # There are a few catch-all except: statements in this module, for # catching input that's bad in unexpected ways. # This function re-raises some exceptions we don't want to trap. if ClientCookie.CLIENTCOOKIE_DEBUG: raise unmasked = unmasked + (KeyboardInterrupt, SystemExit) etype = sys.exc_info()[0] if issubclass(etype, unmasked): raise The network data case uses the same function, but like so: try: cookies = self.parse_cookies() except: reraise_unmasked_exceptions() cookies = [] Problems: 0. It's ugly and hard to understand. 1. May mask bugs. 2. Even when bugs are not masked, it won't be obvious what happened without turning on the debug switch. Part of the reason it's supposed to only raise that error is that .revert() is used to to *overwrite* (not append) to the data held by the objecct, implemented something like this: def revert(self, filename): old_state = copy.deepcopy(self.cookies) self.cookies = {} try: self.load(filename) except IOError: self.cookies = old_state raise But of course the bare except: could equally well be in .revert(), not .load(). And really, I now think it shouldn't be there at all, because it can only hide bugs. Right? When *is* it justified to use except:, then? I've seen simple uses like this that seem fine (this one from Alex Martelli, I think): def isstringlike(x): try: x+"" except: return False else: return True That's fine because x+"" is too simple to have a bug in it. Even there, though, what happens if KeyboardInterrupt happens just as the try block is getting executed? Another reasonable use, in a straightforward debugging hack: try: ... except: # use traceback module here to print out some detail of the exception ... raise And: try: use_dodgy_plugin_code() except: print "your plugin is buggy" Anywhere else? John From francisgavila at yahoo.com Sat Dec 6 22:51:47 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 6 Dec 2003 22:51:47 -0500 Subject: New inited instance of class? References: Message-ID: Samuel Kleiner wrote in message ... >Is there a builtin way of making making another instance of your own >class? You mean, from the inside (from one of the instance methods of the class)? def new(self, *args, **kargs): return self.__class__(*args, **kargs) >I really expected type(self)(*args, **keywords) to work this way. Works for me. What traceback does it give you? >Currently i'm doing this: > >def new(self,*args,**keywords): > from new import instance > s=instance(self.__class__) > if hasattr(D(),'__init__'): > s.__init__(*args,**keywords) > return s That's ugly. -- Francis Avila From peter at engcorp.com Mon Dec 15 09:45:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Dec 2003 09:45:18 -0500 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: Message-ID: <3FDDC8FE.AED055CB@engcorp.com> google12 wrote: > > Ann... I had tried to use Photoshop 7 to save a .png file with transparency > as a .jpg file, and the transparency will be kept in the .jpg file. If JPEG doesn't support transparency, then clearly that couldn't have happened, or Photoshop uses a non-standard JPEG format. Perhaps Photoshop "transparently" (no pun intended) saves the alpha data to some other location, but magically restores it when you reload the .jpg? (How have you confirmed that the data is really stored in the .jpg file and not somewhere else?) From jjl at pobox.com Mon Dec 1 09:34:17 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Dec 2003 14:34:17 +0000 Subject: segfault in extension module References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: <87k75gsj2u.fsf@pobox.com> Nathaniel Echols writes: [...] > > IMO just avoid all this stuff and use SWIG/Boost.Python/Pyrex. > > I'll look at these, but I only have a tiny little bit of code I need to do [...] > Would I really benefit from using one of the other methods? Why not take advantage of it? You've already discovered how hand-writing extensions can be painful. SWIG is probably best for you. Ignore all the fancy SWIG features, just ask it to wrap the function, it's very easy. > The goal here > is explicitly to put only the very time-dependent code in C; everything > else stays in Python. SWIG should be able to do that. There's probably some overhead above a hand-written wrapper, but it's so trivial to use SWIG in this simple way that you probably shouldn't begin to worry about that -- it's unlikely to be a problem. John From jacek.generowicz at cern.ch Fri Dec 12 07:20:44 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Dec 2003 13:20:44 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: bokr at oz.net (Bengt Richter) writes: > On 12 Dec 2003 11:17:16 +0100, Jacek Generowicz wrote: > > >bokr at oz.net (Bengt Richter) writes: > > > >To be honest, I have trouble believing that a local variable lookup > >would be significantly faster than a closure lookup ... or is there > >some other point to this ? > > No, I think you are right. I was mainly reacting to the "there's no > way" statement ;-) Sure ... I was sort of answering to a few posts upthread, as I hadn't done that yet. > >I get your version being almost imperceptibly slower. > When things are that close, it's very hard to draw conclusions > except that they are probably close ;-) But to split hairs you > probably have to run the two tests separately, in quiescent system > situations, ... when it's that close, I just don't care :-) When it's that close, the Python version, CPU, temperature, phase of the moon etc. are probably more significant than the algorithm ... and, most importantly, my time is better spent on finding more effective ways of speeding up my code. > I don't have your "timing" module, Are you sure? It's on every Python installation I currently have access to, so I assumed it was in the standard distribution. Hmm ... OK, the library reference lists it under "Obsolete". From tjreedy at udel.edu Wed Dec 31 00:36:58 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 Dec 2003 00:36:58 -0500 Subject: Formal reference for Python References: Message-ID: <1KidnUSy0aHo_W-iRVn-hA@comcast.com> "Tim Churches" wrote in message news:mailman.65.1072845144.8134.python-list at python.org... > I am writing a scientific paper and need to reference Python. Is there any > preferred way of doing so, which gives credit where it is due? This has been > discussed previously, but not recently, I think. > > The latest version of R (a free, open source language/environment for statistical > analysis) includes a citation() function, which returns the canonical citation for R > as defined by the core R development team. Worth emulating in Python? How about Guido van Rossum, Python Reference Manual, Python Software Foundation, http://www.python.org/doc/current/ref/ref.html, 2003 tjr From bdesth.nospam at removeme.free.fr Fri Dec 12 06:59:32 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2003 12:59:32 +0100 Subject: Function application optimization. In-Reply-To: References: Message-ID: <3fd9a972$0$28708$626a54ce@news.free.fr> Jacek Generowicz wrote: > Given > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > > How should one spell > > results = map(lambda f,a: f(a), fncs, args) > > in order to get the result most quickly ? > I dont know if it will be faster (timeit might tell you this), but what about something as simple stupid as: results = [] nbfuns = len(fncs) for i in range(len): results.append(fncs[i](args[i])) Note that you must have at least len(fncs) args. HTH, Bruno From spam at thalassa.informatimago.com Sun Dec 21 13:16:30 2003 From: spam at thalassa.informatimago.com (Pascal Bourguignon) Date: 21 Dec 2003 19:16:30 +0100 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <7fe97cc4.0312210106.5a72c199@posting.google.com> Message-ID: <87vfoaf341.fsf@thalassa.informatimago.com> xah at xahlee.org (Xah Lee) writes: > maybe some other day when i'm pissed, i'll write a better exposition > on this issue. I've been wanting to write a final-say essay on this > for long. Don't feel like it now. Perhaps instead of losing you time with this, you would better use one of the other strengths of unix: it's modularity, and implement your own shell, or try scsh (scheme shell). There, you don't have to mess with sh idiosyncratic syntax: you just write pure lisp to combine your commands. There is also an easy way to replace to EOL chars by one in scsh. -- __Pascal_Bourguignon__ . * * . * .* . http://www.informatimago.com/ . * . .* There is no worse tyranny than to force * . . /\ ( . * a man to pay for what he does not . . / .\ . * . want merely because you think it .*. / * \ . . would be good for him. -- Robert Heinlein . /* o \ . http://www.theadvocates.org/ * '''||''' . SCO Spam-magnet: postmaster at sco.com ****************** From wade at lightlink.com Tue Dec 30 17:40:42 2003 From: wade at lightlink.com (Wade Leftwich) Date: 30 Dec 2003 14:40:42 -0800 Subject: Newbie: sort list of dictionaries References: <7xy8su7a1k.fsf@ruckus.brouhaha.com> Message-ID: <5b4785ee.0312301440.72fd9348@posting.google.com> Paul Rubin wrote in message news:<7xy8su7a1k.fsf at ruckus.brouhaha.com>... > Sven Brandt writes: > > I have a list of dictionaries. I want the elements of the list to be > > sorted by the value of a key of the dict . > > > > Excample: > > my_list=[{'title': 'foo', 'id': 5, 'text': 'some text'}, > > {'title': 'bar', 'id': 3, 'text': 'my text'}, > > {'title': 'bla', 'id': 6, 'text': 'any text'}, ] > > > > my_list.sort("by the id value") > > The Pythonic way to do it may not be what you're used to, but once you > understand it you'll be able to apply the understanding to other areas > of programming. > > The list sort method lets you pass an optional comparison function, > that takes two items and returns -1, 0, or 1, depending on what order > the items are supposed to appear in. The comparison function takes > exactly two args (the items to be compared). You can't pass a third > arg to specify the field name. You could do something ugly like use a > global variable, but the preferred way given a field name is to > construct a brand new comparison function just for that name: > > def compare_by (fieldname): > def compare_two_dicts (a, b): > return cmp(a[fieldname], b[fieldname]) > return compare_two_dicts > [snip ...] Another way to do it, also Pythonic I think, is with the Decorate-Sort-Undecorate (DSU) pattern: unsorted_list = [{'id':99, 'title':'a'},{'id':42, 'title':'b'}, ... ] decorated_list = [(x['id'],x) for x in unsorted_list] decorated_list.sort() sorted_list = [y for (x,y) in decorated_list] If performance is a consideration, this is supposed to be much faster than providing a comparison function to list.sort(). If you want to package it up as a function, try this: >>> def sortlist(L, decorator=None): ... if decorator is None: ... def decorator(x): ... return x ... newL = [(decorator(x), x) for x in L] ... newL.sort() ... L[:] = [y for (x,y) in newL] ... >>> L = [2,3,6,1,17,0] >>> sortlist(L) >>> L [0, 1, 2, 3, 6, 17] >>> L = [{'id':99, 'title':'a'},{'id':42, 'title':'b'}] >>> def mydecorator(mydict): ... return mydict['id'] ... >>> sortlist(L, mydecorator) >>> L [{'id': 42, 'title': 'b'}, {'id': 99, 'title': 'a'}] >>> Now you have in-place sorting, just like with the built-in sort() method. -- Wade Leftwich Ithaca, NY From gh at ghaering.de Fri Dec 5 09:58:37 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Dec 2003 15:58:37 +0100 Subject: How to tell the difference between string and list In-Reply-To: <1070635589.841.8.camel@marigold> References: <1070635589.841.8.camel@marigold> Message-ID: <3FD09D1D.7030205@ghaering.de> Jan Kokoska wrote: > Hello, > > I need to recognize 'var' and ['var'], usually I would use: > > if a.__class__() == '': > #string > elif a.__class__() == []: > #list > > But unfortunately in Zope PythonScripts, where I need to use this, one > is not supposed to use underscore-prefixed methods as I just found out. > > I figure this is a question general enough to post here (and not on the > Zope list), any clues? Lots of possibilities: Python 2.2+: Politically correct: if isinstance(a, str): elif isinstance(a, list): Even more politically correct (Python 2.3+): if isinstance(a, basestring): elif isinstance(a, list): No-bullshit version (Python 2.2+): if type(a) is str: elif type(a) is list: Python 2.1 and even more ancient ones: if type(a) is type(""): elif type(a) is type([]): or from types import StringType, ListType if type(a) is StringType: elif type(a) is ListType But if you need *any* of these, chances are you should redesign your API so you don't need to switch on the type of the parameter. IMO it's generally better to have a different method for each type. -- Gerhard From max at theslimmers.net Tue Dec 23 21:36:04 2003 From: max at theslimmers.net (max) Date: 23 Dec 2003 18:36:04 -0800 Subject: Problem mapping VB com code to Python References: <4f55e45a.0312191451.73b8f84b@posting.google.com> Message-ID: <4f55e45a.0312231836.436c858d@posting.google.com> Thanks to you and Mark, you were both correct, I simply needed to find the correct invocation of the ProgId :-) max "Paul Paterson" wrote in message news:... > > "max" wrote in message > > news:4f55e45a.0312191451.73b8f84b at posting.google.com... > > > I am trying to use a sdk to access quickbooks, the sdk provided a COM > > > interface and I think it installed the com server files/dlls. A VB > > > code example is provided, but I can't figure out how to map "Dim > > > sessionManager As New QBFC2_1Lib.QBSessionManager" > > > into a corresponding Python statement, when I try > > > obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get > > > traceback Shown below. > > > > > > I have been able to run makepy and it generates a lovely file. I can > > > find a Type Library, but need a little help mapping this to be able to > > > access the com object and call its methods. > > > > > > I have included a snipit of the sample VB code and the traceback from > > > my attempt to create a client com object ? > > > > > > Any help much appreciated, > > > > > > max > > > > > > > > > > > > =======Traceback ============= > > > >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > > > line 95, in Dispatch > > > dispatch, userName = > > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > > line 84, in _GetGoodDispatchAndUserName > > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > > line 72, in _GetGoodDispatch > > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > > pythoncom.IID_IDispatch) > > > com_error: (-2147221005, 'Invalid class string', None, None) > > > > I had a similar problem with a different library that would early bind in VB > but wouldn't work with win32com.client.Dispatch. IIRC I got around it by > hunting in the registry with regedit for likely looking class ID's > ("SomeLibrary.SomeObject"). It is also possible that the VBP file will > contain the GUID which you can then use in a registry search to find a class > ID. > > It may be a shot in the dark but in my case when the VB code was, > > Dim S As MYLIB.Server > Set S = MYLIB.DefaultServer > > the corresponding Python ended up being, > > c = win32com.client.Dispatch("MYLIB.MYLIB") > s = c.DefaultServer > > I'm not sure if this will work in your case but I think if you search the > registry for "QBFC" you might turn something up. > > Paul From martin at v.loewis.de Mon Dec 8 12:18:49 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 08 Dec 2003 18:18:49 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > >bokr at oz.net (Bengt Richter) writes: > > > >> Ok, I'm happy with that. But let's see where the errors come from. > >> By definition it's from associating the wrong encoding assumption > >> with a pure byte sequence. > > > >Wrong. Errors may also happen when performing unexpected conversions > >from one encoding to a different one. > ISTM that could only happen e.g. if you explicitly called codecs to > convert between incompatible encodings. No. It could also happen when you concatenate strings with incompatible encodings. > s3 = (s1.bytes().decode(s1.coding) + s2.bytes().decode(s2.coding)).encode(cenc(s1.coding, s2.coding)) So what happens if either s1.coding or s2.coding is None? > def cenc(enc1, enc2): > """return common encoding""" > if enc1==enc2: return enc1 # this makes latin-1 + latin-1 => latin-1, etc. > if enc1 is None: enc1 = 'ascii' # notorios assumption ;-) > if enc2 is None: enc2 = 'ascii' # ditto > if enc1[:3] == 'utf': return enc1 # preserve unicode encoding format of s1 preferentially > return 'utf' # generic system utf encoding It would be better to call that utf-8, as utf is an unfortunate alias... So concatenating latin-1 and koi-8r strings would give an utf-8 string, as would concatenating an ascii string and a latin-1 string. > But this is not an error. An error would only arise if one tried to use > the bytes as characters without specifying a decoding. So print open("/etc/passwd").read() would raise an exception??? > >Unfortunately, not. You seem to assume that nearly all strings have > >encoding information attached, but you don't explain where you expect > >this information to come from. > Strings appearing as literals in program sources will be assumed to > have the same encoding as is assumed or explicitly specified for the > source text. IMO that will cover a lot of strings not now covered, > and will be an improvement even if it doesn't cover everything. I doubt that. Operatings will decay to "no encoding" very quickly, or give exceptions - depending on your (yet unclear) specification. > >??? What is a "possibly heterogenous representation", how do I > >implement it, and how do I use it? > See example s3 = s1 + s2 above. In what sense is the resulting representation heterogenous? ISTM that the result uses cenc(s1.encoding, s2.encoding) as its representation. > s[0] and s[1] create new encoded strings if they are indexing > encoded strings, and preserve the .coding info. So e.g., in general, > when .coding is not None, > > s[i] <-> s.decode(s.coding)[i].encode(s.coding) So if s.coding doesn't round-trip, s[i].bytes() would not be a substring of s.bytes(), right? > In other words, when s.coding is not None, you can think of all the > possibilities as alternative representations of > s.bytes().decode(s.coding) where .bytes() is a method to get the raw > str bytes of the particular encoding, and even if s.coding is None, > you could use the virtual 'bytes' character set default assumption, > so that all strings have a character interpretation if needed. So what is the difference between this type, and the unicode type? It appears that indexing works all the same in your string, type, and in the Unicode type, and instead of saying .bytes, you say .encode(encname). > >So *all* existing socket code would get byte strings, and so would all > >existing file I/O. You will break a lot of code. > Why? Because people try to combine such strings with strings with encoding information. You haven't specified yet what happens when you try to do this, but it appears that you are proposing that one gets an exception. Regards, Martin From ny_r_marquez at yahoo.com Mon Dec 8 13:51:33 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 8 Dec 2003 10:51:33 -0800 Subject: Problem installing gadfly on Mandrake 9.2 References: <8a27e309.0312080551.331fb053@posting.google.com> Message-ID: <8a27e309.0312081051.39dc3fc@posting.google.com> "Fredrik Lundh" wrote in message news:... > make sure you've installed the python-devel package. Thank you very much. I'll try that. Also, while we are at it, does any one know if a version of kjbuckets.pyd for Python 2.3 is going to be available soon? Or, is the one for 2.2 Ok to use with 2.3? From MidasOneTwo at hotmail.nospam.com Sat Dec 27 14:14:29 2003 From: MidasOneTwo at hotmail.nospam.com (Midas) Date: Sat, 27 Dec 2003 19:14:29 GMT Subject: ObjectA calling ObjectB Message-ID: <3fedd9cc.46564976@news.iprimus.ca> In my "main" code, I would like to create two new objects (ObjectA and ObjectB) and have ObjectA directly call an ObjectB method. In order to do this I believe ObjectA must hold a reference to ObjectB. What about the name of the method? Must it be hardcoded in ObjectA? From dw-google.com at botanicus.net Mon Dec 29 00:46:36 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 28 Dec 2003 21:46:36 -0800 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <99dce321.0312282146.3c2c78ea@posting.google.com> engsolnom at ipns.com wrote... > Also, if I have a string 4 chars long, representing two bytes of hex, > how can I *validate* the string as a *legal* hex string? > > isdigit works until string = '001A', for example > isalnum works, but then allows 'foob' > > Is there a 'ishexdigit'? I could parse the string, but that seems > "un-Pythonish" Have you considered using the int() builtin? Here is an example: def is_hex(n): ''' Return truth if can be converted as hexadecimal from a string. ''' try: int(n, 16) return True except ValueError: return False From gagenellina at softlab.com.ar Wed Dec 24 13:49:15 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2003 15:49:15 -0300 Subject: Storing pairs of (int,int) in a database : which db to choose ? Message-ID: <5.2.1.1.0.20031224154909.01f9b8e0@192.168.0.115> At 23/12/2003 04:35, you wrote: >I want to implement a fulltext search for messages in a forum. More >exactly for each message I store pairs (wordId, msgId) for each >identified word and when I search something I want to be able to >retrieve very quickly all msgId for a given wordId. > >So my problem now is what should I use to store my data and still be >able to retrieve all messages for a given word very quickly. Either I >find a workaround in sqlite to make it store values on less bytes, or >I use something else. Try the shelve module: it comes with Python, it's like a persistent dictionary whith key=string, value=anything. Uses dbm and pickle internally. Instead of storing pairs, you could store: wordId: (tuple of msgIds) so your primary search is just like a dictionary lookup: db[wordId] Gabriel Genellina Softlab SRL From Pieter.Claerhout at Creo.com Thu Dec 18 08:47:44 2003 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 18 Dec 2003 14:47:44 +0100 Subject: Searching docs (was Re: Logging) Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D20@cseexch01.cse.creoscitex.com> One I forgot to mention... If you are looking for the docs for a specific module, you can use the following URL: http://python.org/doc/2.3/modindex.html cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Pieter Claerhout [mailto:Pieter.Claerhout at creo.com] Sent: 18 December 2003 14:43 To: 'Kamus of Kadizhar'; python-list at python.org Subject: RE: Searching docs (was Re: Logging) You can search through the docs on: http://web.pydoc.org/ and on http://starship.python.net/crew/theller/pyhelp.cgi cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Kamus of Kadizhar [mailto:yan at NsOeSiPnAeMr.com] Sent: 18 December 2003 14:20 To: python-list at python.org Subject: Searching docs (was Re: Logging) On Thu, 18 Dec 2003 23:40:33 +1100, Anthony Baxter wrote: > Did you look in the logging documentation? At the end of the > current docs, there's a simple example: Missed that. Is there a search on python.org that only searches docs? That would be really helpful.... I keep coming up with gobs of irrelevant stuff on my searches. I keep missing simple stuff like that. -Kamus -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list From Padraig at Linux.ie Thu Dec 18 15:09:02 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Thu, 18 Dec 2003 20:09:02 +0000 Subject: cleanup after exceptions In-Reply-To: References: <0%mEb.1392$HR.4074@news.indigo.ie> Message-ID: <3FE2095E.70000@Linux.ie> Jp Calderone wrote: > On Thu, Dec 18, 2003 at 07:11:12PM +0000, Padraig at Linux.ie wrote: > >>Hi, >> >>I'm a little confused why objects >>are not deleted after they go >>out of scope due to an exception? > > > Because objects don't go out of scope. Only variables do. Objects remain > "alive" as long as there are any references to them. > > >>For e.g. >> >> >>>>>import time >>>>> >>>>>def f(): >>>>> myfile=open("file.test","w") >>>>> myfile.write("not flushed\n") >>>>> exception=throw >>>>> >>>>>f() >>>>>time.sleep(10) >> >> >>The file is not written/closed until >>the python interpreter exits. >>The same thing applies to other objects. > > > In this case, the traceback still holds a reference to the frame from > which the exception was raised, OK I can see that, but why doesn't a pass on the exception release it? This is demonstrated with: #!/usr/bin/env python import time class c: def __del__(self): print "del" def f(): C=c() exception=throw try: f() except: pass time.sleep(3) > which itself holds a reference to all the > locales from that function. don't know what you mean by this > > Calling sys.exc_clear() This isn't in version 2.2.2 at least > (possibly followed by gc.collect()) should force > the cleanup you expect. thanks, P?draig. From mesteve_b at hotmail.com Sun Dec 14 17:55:31 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 14 Dec 2003 22:55:31 GMT Subject: execl difficulty References: Message-ID: I tried that and it didn't work, but I like the direction you suggested. Thanks, I'll figure this sucker out. "Bengt Richter" wrote in message news:briksl$oc4$0 at 216.39.172.122... > On Sun, 14 Dec 2003 20:53:10 GMT, "python newbie" wrote: > > >Can anyone tell me why this would cause "Invalid Number of Parameters" while > >trying to compile (or interpret or whatever) > > > >import os > >os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Mai n > >Web/dp") > > > >Here's what the Python reference says: > > execl(path,arg0, arg1, ...) > > > >if you can see something obvious, please tell me > > I think xcopy uses suffixed optional forward-slash switch options, so it might be getting confused? > I'd try (note the 'r' prefixes for raw string literals): > > os.execl(r"C:\WINDOWS\system32\xcopy.exe", r"E:\MainWeb\dreampics\*.*", r"E:\MainWeb\dp") > > I don't know what the length or count limits might be on expansion of "*.*" but hopefully > it it pretty big. > > Regards, > Bengt Richter From anthony at python.org Fri Dec 19 21:12:09 2003 From: anthony at python.org (Anthony Baxter) Date: Sat, 20 Dec 2003 13:12:09 +1100 Subject: RELEASED Python 2.3.3 (final) Message-ID: <200312200212.hBK2C9Ni011271@localhost.localdomain> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.3 (final). Python 2.3.3 is a bug-fix release of Python 2.3. A couple of serious bugs related to weakrefs and the cyclic garbage collector have been fixed, along with a number of bugs in the standard library. See the release notes on the web page for more details. For more information on Python 2.3.3, including download links for various platforms, release notes, and known issues, please see http://www.python.org/2.3.3 Highlights of this new release include: - A couple of serious bugs in the interactions of weakrefs and cyclic GC have been squashed. - At shutdown, the second call to the cyclic garbage collector has been removed. This caused more problems than it solved. - The xml.parsers.expat module now provides Expat 1.95.7. - Bug #823328: urllib2's HTTP Digest Auth support works again. - See http://www.python.org/2.3.3/NEWS.html for other bugfixes. Highlights of the previous major Python release (2.3) are available from the Python 2.3 page, at http://www.python.org/2.3/highlights.html Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python 2.3.x Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 234 bytes Desc: not available URL: From richie at entrian.com Wed Dec 3 04:12:53 2003 From: richie at entrian.com (Richie Hindle) Date: Wed, 03 Dec 2003 09:12:53 +0000 Subject: PyMeld and PyMeldLite (was Re: Separation of content and codefor web) In-Reply-To: <3FCD4BA7.F2D6AACB@engcorp.com> References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> <3FCCBF61.9587D06@engcorp.com> <3FCD4BA7.F2D6AACB@engcorp.com> Message-ID: Peter, > Wow, all that and he even writes unit tests! :-) > (Out of curiosity: was it test-driven ala TDD, or are these traditional > unit tests?) A bit of both. These days I'm doing true TDD for almost all Python work. When I wrote the bulk of PyMeld I wasn't yet converted, so mostly I would code a feature and then immediately write a unit test. I've always used coverage analysis with unit tests, insisting on 100% line coverage wherever possible (I must get around to releasing my coverage analysis module some day). Some of the latterly-added PyMeld features were done with TDD, and most bugfixes have TDD-written regression tests. (My smoke-test of the dictionary interface was done with TDD 8-) In PyMeld's case I've used doctest to do TDD, to very good effect. Using the same physical string as the design document, the source code comment, the API documentation, the unit tests, the regression tests *and* the website content is just fantastic. -- Richie Hindle richie at entrian.com From martin at v.loewis.de Sun Dec 7 12:37:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Dec 2003 18:37:33 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> <2lFAb.43218$aT.25634@news-server.bigpond.net.au> Message-ID: "Neil Hodgson" writes: > Ruby 2.0 will probably implement strings with encoding attributes. The > developers want to avoid changing encoding whenever possible. Yes, but Ruby was very bad at Unicode all the time. Also "Ruby will" is a weak statement - AFAICT Ruby 2 is about the same mythical implementation that P3k is. > One posting I saw had joining strings with different encodings as an > error although I don't know if this has been finalised. I doubt > whether it will work well, so I think the best approach for Python > is to watch Ruby and if it is successful then copy. "m17n" is the > magic googling term Well, yes. I also doubt it will work; Ruby has traditionally supported only a single encoding at the time well, and focused on the Japanese ones primarily. Regards, Martin From martin at v.loewis.de Mon Dec 22 15:31:35 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 22 Dec 2003 21:31:35 +0100 Subject: print arabic characters In-Reply-To: References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Peter Otten wrote: > Disclaimer: As I know nothing about right-to-left printing languages, it's > likely that I have got it at least partially wrong. Indeed. First of all, each Unicode character has a directionality, available as unicodedata.bidirectional; this is L, R, or AL for most characters; some characters have weak (EN, ES, ET, ...) or neutral (B, S, ...) directionality. You need to find runs of characters with the same directionality; extending the run into weak or neutral characters. Then you need to reverse only RTL runs, leaving the LTR runs intact. Next, in the process of reversing, you may need to mirrot weak LTR characters, replacing them with their unicodedata.mirrored character. Then, for AL runs, you need to replace European numerals with Arabic numerals (but keeping the LTR order). Finally, and again for Arabic characters, you need to perform glyph shaping, replacing the first character of a word with the INITIAL FORM, the last character with the FINAL FORM, all other characters of a word with the MEDIAL FORM, and all remaining characters with the ISOLATED FORM. This, of course, assumes your font has glpyhs for these available. This is specified in more detail in http://www.unicode.org/reports/tr9/ > Can anybody point me to a way to iterate over characters with a varying > number of bytes? There is no trivial algorithm. You best decode the string into Unicode, reverse, then encode again to the original encoding. Regards, Martin From michele.simionato at poste.it Tue Dec 16 06:10:51 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 16 Dec 2003 03:10:51 -0800 Subject: downloading long files References: <95aa1afa.0312152351.7b6143be@posting.google.com> Message-ID: <95aa1afa.0312160310.7e629fd6@posting.google.com> garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) wrote in message news:... > Michele Simionato wrote: > > I have a connection which is not 100% rock solid, so if I try > > to download a large file (i.e. a Linux ISO image) chances are > > that the connection will break. Is there a way to check periodically > > if the connection is open, reopen it if needed, and continue the > > download without restarting from the beginning? > > yes, use wget http://www.gnu.org/directory/wget.html > or are you looking for a pure python solution? A pure Python solution would be preferable, indeed. Michele From removeahmed.mohamed.edigramremove at wanadoo.frremove Mon Dec 22 13:11:17 2003 From: removeahmed.mohamed.edigramremove at wanadoo.frremove (Ahmed MOHAMED ALI) Date: Mon, 22 Dec 2003 19:11:17 +0100 Subject: Remembering References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Message-ID: Hi, If you talk about your python code ,type your instructions in a file.If you talk about your data ,you must use a persistence system (file,database ...) Ahmed "MComp" wrote in message news:37c4fd7c.0312221002.1f4fe6d0 at posting.google.com... > Hey guys, I'm another new to programming guy. I have one quick > question. How do you make a program not forget everything you input, > once it shuts down? Thanks in advance. From http Thu Dec 25 06:12:02 2003 From: http (Paul Rubin) Date: 25 Dec 2003 03:12:02 -0800 Subject: 2.3 list reverse() bug? References: Message-ID: <7xad5hup6l.fsf@ruckus.brouhaha.com> cartermark46 at ukmail.com (Mark Carter) writes: > >>> d1 = [1,2] > >>> d2 = d1 > >>> d2.reverse() > >>> print d1 #note: d1, not d2 > [2, 1] > > Surely that can't be right: d1 should still be [1,2]. If it is > "right", then I expect that many people are in for a suprise. It's correct. d1 and d2 are the same list, and list.reverse reverses in place. If you want d1 and d2 to be two separate lists, try d1 = [1,2] d2 = d1[:] # makes a copy of d1 d2.reverse() print d1 From tyler at tylereaves.com Sat Dec 13 16:56:59 2003 From: tyler at tylereaves.com (Tyler Eaves) Date: Sat, 13 Dec 2003 21:56:59 GMT Subject: ossaudiodev Message-ID: The docs list the module as being available on FreeBSD, yet neither 2.2 (built from ports) or 2.3.2 (built by hand from canonical sources) have it. From oren-py-l at hishome.net Thu Dec 25 06:14:13 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 25 Dec 2003 06:14:13 -0500 Subject: "literal" objects In-Reply-To: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: <20031225111413.GA38569@hishome.net> On Wed, Dec 24, 2003 at 08:09:31AM +0000, Moosebumps wrote: ... > A thought that occured to me is that classes are implemented as dictionaries > (correct?). So you could have a dictionary like this: > > x = {'a': 3, 'b': 5} > y = {'a': 5, 'b': 15} > > This would be the __dict__ attribute of an object I suppose. But I don't > see anyway to assign it to a variable so you could access them like x.a and > y.a. I don't know if this would be a "nice" way to do it or not. You can update an object's __dict__ from an existing dictionary: obj.__dict__.update(x) would make obj.a==3 and obj.b==5 You can do this in an object's constructor and combine it with keyword arguments to get a nifty struct-like class: class Struct: def __init__(self, **kwargs): self.__dict__.update(kwargs) >>> x=Struct(a=5, b=5) >>> x.a 5 >>> x.b 5 >>> x If you want something a bit more fancy, you can add the following __repr__ method to the Struct class, so you can now print these structs, too: def __repr__(self): return "%s(%s)" % (self.__class__.__name__, ', '.join(['%s=%s' % (k, repr(v)) for k,v in self.__dict__.items()])) >>> x Struct(a=5, b=5) >>> class Person(Struct): ... pass ... >>> p = Person(name="Guido van Rossum", title="BDFL") >>> p Person(name='Guido van Rossum', title='BDFL') >>> p.name 'Guido van Rossum' >>> p.pet = 'dead parrot' >>> p Person(pet='dead parrot', name='Guido van Rossum', title='BDFL') >>> Oren From Mike at DeleteThis.Geary.com Fri Dec 26 14:14:39 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 26 Dec 2003 11:14:39 -0800 Subject: Python Language Reference References: Message-ID: Stephen Ferg wrote: > http://www.ferg.org/pyref/index.html Very nice work!! Any chance of using plain black on white? The color scheme is hard to look at on my ThinkPad LCD screen. Thanks! -Mike From gnari at simnet.is Sun Dec 21 09:02:04 2003 From: gnari at simnet.is (Ragnar Hafstað) Date: Sun, 21 Dec 2003 14:02:04 -0000 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <7fe97cc4.0312210106.5a72c199@posting.google.com> Message-ID: "Xah Lee" wrote in message news:7fe97cc4.0312210106.5a72c199 at posting.google.com... > Ragnar Hafsta? (gnari at simnet.is) wrote: > > > you are forgetting what -p does > > ... > > perl -0 -pi'*~' -e 's@\n\n@\n at g' *.java > > Thank you kindly. > > -- > > Now there are a slew of perl driviling morons who > has also participated in answering to no avail. Die! (snipped rather much more) I apologise gnari From martin at v.loewis.de Tue Dec 30 20:03:16 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 31 Dec 2003 02:03:16 +0100 Subject: Is Python Mac Centric??? In-Reply-To: References: Message-ID: Jeff Epler wrote: > There are also a couple of people who are working very hard on > Mac-specific modules for Python. I don't know why they're included in > the core while pythonwin is not--is it just historical coincidence? A > license difficulty? Change in attitudes? AFAIR, the Mac parts were included on request of Jack Jansen, who was looking for a "permanent home" for his code, with CVS, bug tracking, integrated releases, and all that. Guido van Rossum agreed, as it would make Jack's life simpler. I personally was shocked when I saw just *how* big the code base was, but then accepted it, as much of it is for OS9 and older, and the OSX stuff is more and more getting folded into the standard libraries (where applicable); OS9 support will be dropped for Python 2.4. Apart from Tim's analysis of coding styles, I think PythonWin would become integrated if Mark Hammond requested that. Anybody else requesting it would have no effect; and, as Tim said, Mark is unlikely to request it because he doesn't want to wait a year for the next Python release just to release the next version of PythonWin. Regards, Martin From peter at engcorp.com Mon Dec 15 09:15:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Dec 2003 09:15:25 -0500 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> <3FD9D4E9.FE199F61@engcorp.com> <7xfzfphdzt.fsf@ruckus.brouhaha.com> Message-ID: <3FDDC1FD.6687FD2@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > As the author, John might seem biased, but I'll weigh in with my own > > praise for the product. His comment "if you want to stay sane" is > > really on-the-mark here... Cookies _are_ insane, but ClientCookie at > > least provides them a nice padded room in which to reside... > > Cookies aren't insane in concept, but their implementation leaves some > things to be desired. Agreed... especially with IE6.1, where I still have an incredibly annoying problem with a Zope-based Intranet where my cookies are being forgotten periodically, which among other things has led to repeated data loss (when combined with anothe IE peculiarity which loses the data in the input fields of a form if the form submission fails... when you hit "back" you no longer have your data to resubmit). Oh, but I'm describing a problem with a _Microsoft_ product, so the whole comment was redundant. Sorry. -Peter From adalke at mindspring.com Sun Dec 28 14:51:42 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 28 Dec 2003 19:51:42 GMT Subject: Project dream References: <%c2Hb.7537$lo3.4095@newsread2.news.pas.earthlink.net> Message-ID: Me: > > An integrated chemical/bioinformatics development and > > exploration environment. Got a few million dollars to fund me? > > (Actually, more like 10 million, but bootstrappable with only > > a few million.) Will Stuyvesant: > I guess all that money is needed for getting high quality people into > it? Or other reasons? What techniques would you use? Have you scoped out how much it costs to run a company? Suppose you want to pay a decent salary. Around here that's about $60 - $70,000 for software developers, and about the same for good computational chemists. (Maybe a bit higher, unlikely to be lower.) Say 2 software developers, one with good comp. chemistry experience, one with good QA skills, another for documentation, and if it's the above environment then a usability engineer and GUI developer -- call it 4 full-time equivalents, or about $1/4 million per year. Add in overhead (health insurance, bookkeeping, computers, etc.) and that's about $1/2 million per year. If you've read "Crossing the Chasm", science -- especially the so-called 'hard sciences' -- are on the early-adopter side of the chasm. That is, there are a bunch of people who spent years in libraries, doing research, writing papers, to get a PhD. They have few qualms about spending more time and effort to learn something. Compare this to sane people, who just want things to work without usually needing to worry about the details. I like that my car, a very complex device, needs amazingly little attention from me. Scientists in their specialty are the grease monkeys like my uncle who complained about a 1938 model year truck which no longer had the door in the firewall to tweak the carburetor while driving. One chemist, when told by others that the software took a long time to learn, replied "suck it up and just learn it." I think this is bad, for two reasons. First, extending the analogy a bit, it means the specialist are limited to 1930s model cars instead of getting to 1960s rally cars; still able to tweak and tune as needed, but it works and lets you go places. Hence my company's motto "More Science, Less Time." Second, it prevents non-specialists from using the tools for that field. There are many times when someone in a related field (say, bioinformatics instead of chemical informatics) needs use a few techniques, or times when tasks once considered esoteric -- like a similarity search of a subset of a DNA database -- are taught in introductory-level courses. These must be made both easy to use and robust in operation. The problem with either approach is that it requires a lot of new software to be written or rewritten, for reasons I won't get into. Scientists tends to be more reactionary than average, and stay with software where all the warts are known rather than worrying about new bugs, or having to justify in talks and papers why a new approach was used over the standard one. Putting all these together, that means any good software for this field will take a lot of work, a lot of time, and a long, slow acceptance period, which means it will take 3 to 4 years before my project dream is self-supporting. Hence, "a few million dollars." Instead, I'm doing consulting -- but still looking for a company or three interested in funding me to work on my dream. :) > And I can not do C bindings (too long ago I did C). > Besides I don't *want* to C again :-) Tools like SWIG make it quite easy. > > My answer then is to do any of these projects; they are all great > > ones to learn how to do larger, more useful projects. > > Um, more useful? Can you give some more examples of what > you think useful? He-he. I'm very biased in this respect, so everything I can think of is in the computational life sciences, and even when I relax that restriction I still end up with things that I might make a living out of. "Useful" at this point in my life means making money to live on, travel, enjoy myself -- ie, the proverbial "life, liberty, and the pursuit of happiness." The list you gave (two games, a vector graphics program, and a weblog program) don't fall into that category for me since there's too much competition already in those domains. > I am looking for a fun project and inspiration and maybe even fun > people who join a project, you got that right :-) Go to sourceforge and browse the list until you find something interesting. If you want, you can even limit the search to Python. Or go to bioinformatics.org and look through the list there. ;) Andrew dalke at dalkescientific.com From bokr at oz.net Sun Dec 21 16:41:02 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Dec 2003 21:41:02 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On Sun, 21 Dec 2003 07:41:40 -0500, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:bs2j3b$fc5$0 at 216.39.172.122... >> On Sat, 20 Dec 2003 06:38:20 -0500, "John Roth" >wrote: >> >> >> >Sure, you can use a property to not have to put >> >in the explicit function call, but then you can't put >> >in the explicit function call *anywhere* you use that >> >property. >> > >> Nor can you supply explicit arguments if you want to, though you could >> provide an alternate name, so you could access either way. > >That's really an inherent feature of the 'property' notion: >since it's accessed like a variable, the getter can't have any >parameters. Since the property access return an object, >I suppose you could have something that looks like an >indexable or slicable property. Or even callable, with sneaky dynamic method substitution ;-) Or any other expression trailer combination of, e.g., .attr, (), etc. > >> Nor can we do properties without accessing them via the attribute magic >(i.e., >> not via bare global names for example). >> >> >Ruby syntax makes it *optional*. That's what is >> >missing here. > >> I've floated various ideas/brain_farts more/less seriously for triggering >magic >> via name access alterantive to getattr magic, but there seems to be no >enthusiasm >> or else horrification at the thought, so I haven't stirred that pot for >some time ;-) >> >> What would be the syntax you would like to use, with what effect? > >Well, the basic idea was simply to make the () optional for functions >with no parameters. No particular syntax there but it would require some >major jump through hoops gyrations from the virtual machine, and there >would have to be some way of getting the function object when you >wanted it, and I suspect the difference between a function object and >a more general 'callable' would totally confuse most people. And of >course, does a function/method with only keywords count as a function >with no parameters? > >Ruby can get away with it because, as far as I know, functions are not >first class objects. They certainly aren't in Perl which was Ruby's >inspiration. Really? Perl was Ruby's inspiration?? > >It's a non-starter for Python, though. Seems so. OTTOMH I guess you could have the tokenizer generate two kinds of names, names_as_now, and bare_names (tagged so with lookahead determining no trailers). Then you could dynamically check if a bare_name was referring to a callable, and call it with no params if so, and for all other name usage do as now. Except that as you point out, you'd need a way to inhibit the effect. But since this thing would be unusual (and would cause major breakage), maybe it could be enabled only for references to objects with an __autocall__ alias to their __call__ attribute. And then, since the auto-call would only happen for bare names, you could pass it as a function by using name.__call__ instead of name. Or use vars()['name']. Not that I am proposing this ;-) Regards, Bengt Richter From francisgavila at yahoo.com Sun Dec 7 12:56:06 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 7 Dec 2003 12:56:06 -0500 Subject: New inited instance of class? References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message ... >Samuel Kleiner wrote: >> So can I make all my classes derive from object without >> doing so explicitly- IE, without having to change every >> single top-level class definition? >> > >You can do it on a per-file basis by putting > >__metaclass__ = type > >once before the class definitions. That strikes me as a very *bad* idea, because it's no longer obvious that the classes themselves are new-style, and the OP might develop a bad habit of using this to avoid typing '(object)' all the time. (Or he might show us all for fools, if ':' becomes shorthand for '(object):'.) Aside from that, metaclasses are a more advanced and less-commonly-used feature of classes, and therefore probably more vulnerable to change. I know it should work, but am uneasy that it might manifest some unexpected behavior (or bug). -- Francis Avila From chris.lyon at spritenote.co.uk Fri Dec 19 11:20:36 2003 From: chris.lyon at spritenote.co.uk (Chris Lyon) Date: 19 Dec 2003 08:20:36 -0800 Subject: The Truth? References: Message-ID: "TyBriD" wrote in message news:... > i have 100% no programming experience but i have read some VB6 and parts of > C++ books never stuck with it because it was to confusing, but i was told > python is a great place to start is that true?. if so is there specifi parts > to learn and start off with n why links would be great thanks. In your position I would consider learning about dictionaries, lists and tuples initially as (to my mind,TMM) they form the basic units upon which (TMM) much seems to be built. You don't say if the object are something you understand or require but they form a fairly important element of the language. If they are a concept that is new to you then it is wise to invest time in understanding how they are built and how to turn programming concepts into objects. Python certainly makes this easy but it can be frustrating and it is important not to blame conceptual problems with objects on python's (TMM) simple implementation. The word self takes on a life of it's own after a while. You also don't mention which particular operating system flavour you are arriving from, although I would guess windows from the visual basic mention. There are important differences between linux and windows in the file handling and path area's which can lead to confusion and irritation. Learn to use os.path.join() for building your path string's and the magic numbers for setting read only files in windows are:- os.chmod(destfile ,33060) #Make a Windows file R/O os.chmod(destfile ,33206) #Make a Windows file R/W now some one should be along to disagree with this shortly :) From __peter__ at web.de Mon Dec 15 11:00:02 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Dec 2003 17:00:02 +0100 Subject: Build classes/packages dinamicaly References: Message-ID: Paulo Pinto wrote: > I have a package that generates classes from a > set of XML files using exec. > > So far the classes appear in the global namespace. > > Is there any way to also create packages dinamicaly > and add the classes to those packages? > > Thanks in advance, > Paulo Pinto >>> import types >>> mymodule = types.ModuleType("mymodule") >>> exec "def demo():\n\tprint 'hello from', __name__\n" in mymodule.__dict__ >>> mymodule.demo() hello from mymodule >>> Seems to work. I haven't used it myself, though. Peter From adsl5lcq at tpg.com.au Thu Dec 18 22:30:23 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Fri, 19 Dec 2003 14:30:23 +1100 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: On Fri, 19 Dec 2003 03:17:36 GMT, "Rainer Deyke" wrote: >You're trying to solve the wrong problem. Python caches small integers, so >you've only got a very small number of distinct integer objects. This is a >good thing, because each Python object has a eight byte overhead. >Introducing a new type wouldn't result in any memory savings. > Thanks. I had thought as much, but was not totally sure. >The real overhead comes from the references to those objects. Each >reference is four bytes (on 32 bit computers), and there is no way to >decrease this. Your best option is to use high level objects that contain >many integers internally but don't store them as individual Python >references. The array module is one choice, Numarray is another. If >immutability isn't an issue, you could even use strings (with each character >treated as an eight bit integer). So the references to each integer is what causes the massive overhead. I've read up on Numarray and the array module in the docs, but didn't see how I could adapt my current program to use these modules because of how my data is currently organised. I have one constantly changing dict with many millions of keys (tuples of ints) which in turn associates itself with a tuple of ints and two more dicts. Every single container type contains only integers. Am I correct in assuming that an array cannot be used as a key for a dictionary? As they are mutable? Thanks for your help, Glen From newsgroups at jhrothjr.com Fri Dec 26 16:20:59 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Dec 2003 16:20:59 -0500 Subject: dynamic typing question References: <8ef9bea6.0312261227.56ade9a9@posting.google.com> Message-ID: "Hung Jung Lu" wrote in message news:8ef9bea6.0312261227.56ade9a9 at posting.google.com... > claird at lairds.com (Cameron Laird) wrote in message news:... > > 1. Why, in your mind or your teammate's, > > is dynamic typing a "lack"? What, pre- > > cisely, is the benefit of static typing? > > There are a number of legitimate > > answers. It occurs to me that, without > > precision on which interest you, we > > might be missing an opportunity to > > clarify "The Python Way" significantly. > > One static typing advantage I've run into: > > When you change the name of a variable in a class, and re-compile the > program, the compiler shows you ALL places where compilation fails. > These could be hundreds of places in dozens of files. In dynamically > typed language like Python, you have to rely on text search, which > often yields many false positives, especially for common/overloaded > names like .count, .name, .type, etc. In statically-typed languages, > making name changes is not very painful, since the compiler will tell > you where exactly you need to follow up with the changes. In > dynamically typed language, you will have to manually write unit test > codes to ensure name consistency. > > I am sure Python people have come up with strategies to deal with this > problem. That's what I'd like to hear. (Unit test is one route.) But > this is one place where I've found statically-typed compilers useful. > I mean, I have seen this discussion many times, but most responses > from Python users have not been realistic (often simply shrugging off > the problem and saying something like "compilers don't detect all the > bugs, blah blah blah".) I would like to hear more real-life experience > rather than academic conjectures. The OP said they would be using Test Driven Development. In TDD, you write maybe a half dozen lines before running your test suite. If it ran last time, and it didn't run this time, then you have maybe a half dozen lines to check. Lots of people regard the 'undo' command as a great debugger in this case. Of course, if you write hundreds of lines before doing a compile, then you will need all the help you can get. John Roth > > regards, > > Hung Jung From jjl at pobox.com Tue Dec 23 15:12:05 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 20:12:05 +0000 Subject: Remembering References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Message-ID: <87llp3i99m.fsf@pobox.com> lbray_103 at yahoo.com (MComp) writes: > Hey guys, I'm another new to programming guy. I have one quick > question. How do you make a program not forget everything you input, > once it shuts down? Thanks in advance. Once you've tried simple file manipulation (opening, reading, writing, closing, and some of the stuff in os.path), look at the pickle module. Don't get seduced by it too early, though, or you'll skip the learning experience of struggling with parsing text files, which is good for your soul ;-) John From theller at python.net Tue Dec 2 04:54:19 2003 From: theller at python.net (Thomas Heller) Date: Tue, 02 Dec 2003 10:54:19 +0100 Subject: Shared Memory Modules References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> <3fcbd6b8$1@nntp0.pdx.net> <3fcbd24f$0$1502$e4fe514c@news.xs4all.nl> <3fcc5a0b$0$1491$e4fe514c@news.xs4all.nl> Message-ID: <8ylv1r5g.fsf@python.net> Irmen de Jong writes: > Bengt Richter wrote: >> What's that first zero argument? > [...] >> Does that mean you are trying to use stdin as the open file handle? > > No it doesn't, according to Thomas Heller's post in this thread. > Thomas said 0 means "not associated with a file" on windows... mmapmodule.c internally uses INVALID_HANDLE_VALUE of a file handle of 0 is used. As I said, read the source (and MSDN). And then submit a documentation patch . Thomas From mk at net.mail.penguinista Wed Dec 10 11:17:35 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Wed, 10 Dec 2003 17:17:35 +0100 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> <3fd728e3$0$213$e4fe514c@news.xs4all.nl> Message-ID: <3fd7471f@news.mt.net.mk> >>>>Tab completion for keywords and methods etc (you can get this in the >>>>standard python shell as well of course) >>> >>>You can? How? >> >> Press tab after typing part of the keyword/method. > > Sean was talking about the 'standard python shell' so I tried > the default python (2.3) on my mandrake 9.2 box. > It doesn't work, it just inserts a tab character. Put this in ~/.pythonrc, and setup the PYTHONSTARTUP environment variable to point to it: export PYTHONSTARTUP=~/.pythonrc # ~/.pythonrc # enable syntax completion try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") -- ?????? (jabberID:damjan at bagra.net.mk) I believe the technical term is "Oops!" From tnienstedt at telesyn.com Thu Dec 4 17:48:53 2003 From: tnienstedt at telesyn.com (Ted Nienstedt) Date: Thu, 4 Dec 2003 17:48:53 -0500 Subject: stddev bug in util.py In-Reply-To: <3FCFB1BB.BB572A89@engcorp.com> Message-ID: <005e01c3bab8$ca9afe90$421210ac@telesyn.corp> Yes, that's exactly what I did. I had thought that the posted msg would include the other recipients('russell at cs.berkeley.edu','Peter at Norvig.com') - my bad on that point. Sorry to bother. I had wished that I had realized this bug existed earlier and thought others might appreciate learning of it as well. -----Original Message----- From: Peter Hansen [mailto:peter at engcorp.com] Sent: Thursday, December 04, 2003 5:14 PM To: python-list at python.org Subject: Re: stddev bug in util.py Ted Nienstedt wrote: > > The code was obtained from http://aima.cs.berkeley.edu/python/utils.html > Perhaps I should have made that clear Wouldn't it therefore make a lot more sense to send the problem report directly to the authors, at the addresses under their home pages which are listed at http://aima.cs.berkeley.edu/ ? Or did you do that already, and just thought you ought to warn the rest of us, too? ;-) -Peter From __peter__ at web.de Mon Dec 15 19:22:25 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Dec 2003 01:22:25 +0100 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: Matthew Sims wrote: > Is there anyway to assign to an element that wasn't defined in the > beginning? Like if I wanted element 5 assigned but not element 4 > without using "" or None? You can write your own class: class GrowingList(list): def __init__(self, seq, default=None): list.__init__(self, seq) self.default = default def __setitem__(self, index, value): if index >= len(self): self.extend([self.default]*(index - len(self))) self.append(value) else: list.__setitem__(self, index, value) g = GrowingList(["alpha", "beta", "gamma"]) g[7] = "omega" print g This is a partial implementation, only g[index] = value will work. > I'm currently re-writing a Perl script into Python and with Perl I was > free to assign any element in the array without having to fill in the > previous elements. I can't seem to do that in Python...unless I'm > doing it wrong. As already pointed out, a mechanical translation will yield substandard results. As you did not describe the problem you are solving with the "autogrowing" list, there is little chance for us to come up with a better or at least more idiomatic approach. Peter PS: Welcome to the worst programming language - except all others :-) From speno at net.isc.upenn.edu Mon Dec 29 16:33:53 2003 From: speno at net.isc.upenn.edu (John P. Speno) Date: Mon, 29 Dec 2003 21:33:53 +0000 (UTC) Subject: PIL: jpeg comment References: Message-ID: In Gerrit Holl writes: >Hi, >how do I read a JPEG comment with the Python Imaging Library? PIL won't do it out of the box, but it's easy to add it. I posted a patch here: http://www.pycs.net/users/0000231/ Enjoy. From ark at acm.org Sun Dec 21 12:04:28 2003 From: ark at acm.org (Andrew Koenig) Date: Sun, 21 Dec 2003 17:04:28 GMT Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: "MetalOne" wrote in message news:92c59a2c.0312191113.569724ca at posting.google.com... > I am trying to write a generator function that yields the index position > of each set bit in a mask. > e.g. > for x in bitIndexGenerator(0x16): #10110 > print x > --> 1 2 4 > > > This is what I have, but it does not work. > Changing yield to print, shows that the recursion works correctly. > > def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) > > What am I missing? If you really want to make your program work the way you apparently intend, then you need to activate the generator you create recursively and yield each value that it yields. For example: def bitIndexGenerator(mas, index=0): if mask == 0: return elif mask & 0x1: yield index for n in bitIndexGenerator(mask >> 1, index + 1): yield n However, unless your purpose in writing this program is to improve your understanding of recursion, this technique uses much more mechanism that needed to solve the problem--as other replies have already pointed out. From oren-py-l at hishome.net Sat Dec 20 11:24:27 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 20 Dec 2003 11:24:27 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <20031220162427.GA60868@hishome.net> On Sat, Dec 20, 2003 at 08:44:45AM -0500, John Roth wrote: > I'm not certain I'm making the connection. The visitor pattern > as I use it doesn't seem to have much to do with generators. > It's a way of disconnecting the sequencing logic from the > processing logic, You mean like this? def generator(...): sequencing logic, yield stuff for object in generator(...): processing logic > while a generator seems to encapsulate both in the same function. Can you give any specific reasons why you believe this to be the case? > A good case in point is file processing. I've got a class that > encapsulates a directory: instantiate it and it reads the directory > into an internal list. Then if you invoke the .visit(instance)) method, > it calls either the 'file' or the 'directory' method in that instance > for each of the names in the directory. If I need to go down a > directory chain, I simply invoke it recursively. Recursively? I thought the whole point of using such a class was to disconnect, as you say, the sequencing logic from the processing logic. If the user of the class must explicitly invoke the recursion the sequencing logic becomes hard-wired into the processing logic. With a generator you could pass an argument to the sequence logic that instructs it to do, for example, a breadth-first or depth-first traversal without affecting the processing logic. > If I arranged it so I called the visitor instance one last time > (possibly using a 'lastTime' method) I could completely Like this? for object in generator(...): processing logic last time I think it's great that Python has functions and bound methods as first-class objects and that they can be passed around as values. I just don't think they should be used when there are far simpler ways to achieve the same result. Oren From python at rcn.com Fri Dec 26 19:43:59 2003 From: python at rcn.com (Raymond Hettinger) Date: 26 Dec 2003 16:43:59 -0800 Subject: Help ! newbie problem References: Message-ID: <5d83790c.0312261643.7dd1c9e4@posting.google.com> > I am trying to learn python... I can't explain the difference beetween these > two programms, Fibonacci suites : > > > >>> a,b,c = 1,1,1 > >>> while c<12: > ... print b, > ... a,b,c = b,a+b,c+1 > ... > 1 2 3 5 8 13 21 34 55 89 144 > > and > > >>> a,b,c = 1,1,1 > >>> while c<12: > ... print b, > ... a=b > ... b=a+b > ... c=c+1 > ... > 1 2 4 8 16 32 64 128 256 512 1024 In the first program, the each element on the right hand side of the equal sign is evaluated before any assignments are made. So, the value of "a" is updated *after* "a+b" is computed. In the second program, "a" is updated *before* "a+b" is computed. So, the first program can be expanded to something like this: >>> a,b,c = 1,1,1 >>> while c<12: ... print b, ... tmp1 = b ... tmp2 = a+b ... tmp3 = c+1 ... a = tmp1 ... b = tmp2 ... c = tmp3 Raymond Hettinger From hokiegal99 at hotmail.com Tue Dec 23 10:37:47 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 10:37:47 -0500 Subject: return statement in functions In-Reply-To: <93f5c5e9.0312221718.23e42dac@posting.google.com> References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: OK, I took the good advice I was given here and made my functions very specific. I made them all return something sane... something one would expect them to return. I even wrote a function to handle the report writing itself, but when it gets the output from the other functions to write the report file, it only writes this: I would like for it to write out what the functions returned. Obviously, I am missing something very fundamental here. Could someone hit me in the head with a hammer and help me understand this? Here is an example of what I'm trying to do. Please be gentle with me. From experience, I know that intelligence and modesty do not mix, but make an exception for me, just this once... The ugly report function: def report(a,b,c,d,e,f,g,h,i,j,k): outputFile = open('report.txt', 'w') print >> outputFile, a print >> outputFile, b print >> outputFile, c print >> outputFile, d print >> outputFile, e print >> outputFile, f print >> outputFile, g print >> outputFile, h print >> outputFile, i print >> outputFile, j print >> outputFile, k outputFile.close() This function is an exception to my new "ALWAYS RETURN SOMETHING SANE" motto as I don't care what this returns. Below is the first function where the output is taken as 'a' by the report function: def fs_object_count(path): file_count = 0 dir_count = 0 for root, dirs, files in os.walk(path): file_count += len(files) dir_count += len(dirs) return dir_count, file_count Here's one other example: def doc_extension(path): for root, dirs, files in os.walk(path, topdown=False): for fname in files: doc_new = fname + '.doc' ms_id = string.find(file(os.path.join(root,fname), 'rb').read(), 'Microsoft') doc_id = string.find(file(os.path.join(root,fname), 'rb').read(), 'Word.Document.') ext = os.path.splitext(fname) if not ext[1] and doc_id >=1 and ms_id >=1: newpath = os.path.join(root,doc_new) oldpath = os.path.join(root,fname) os.renames(oldpath,newpath) return oldpath, newpath Here's how I call the report function: report(fs_object_count,clean_dir_names,etc., etc.) Thanks!!! From ville.spammehardvainio at spamtut.fi Sun Dec 7 15:56:07 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 07 Dec 2003 22:56:07 +0200 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: allenabethea at aol.com (Allenabethea) writes: > I am a new python tinkerer. I love the language. But what is its > future but as a legacy tool? What, has .NET suddenly turned out to be popular while I wasn't watching? The whole world is hardly jumping on the .NET platform, actually mostly people seem to be ignoring it... Or is this a troll of some kind? You might also want to take a look at: http://zope.org/Members/Brian/PythonNet/ -- Ville Vainio http://www.students.tut.fi/~vainio24 From santoshk at datec-systems.com Tue Dec 2 06:49:23 2003 From: santoshk at datec-systems.com (kumar) Date: 2 Dec 2003 03:49:23 -0800 Subject: Telnet server implementation Message-ID: Hi all, I want to write a telnet server for an embedded linux box using python.The problem is that it doesn't give a shell ( just a limited CLI commands for configuring it . )My requirement is to write a telnet server ( residing on the box) listening on some specific port where it can listen to telnet requests from clients and provide them an interactive command line session. I tried using the python's async_chat module but it is very limited ..any wrappers around this module so that it can be used more interactively ?? . Any pointers would be highly appreciated . The current available CLI on this box allows me to write python scripts remotely , ftp it and run them, so executing them won't be problem. Thanks kumar From jacek.generowicz at cern.ch Tue Dec 9 04:05:21 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 10:05:21 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: "Terry Reedy" writes: > "Jacek Generowicz" wrote in message > news:tyf7k171jbq.fsf at pcepsft001.cern.ch... > > I have a program in which I make very good use of a memoizer: > > > > def memoize(callable): > > cache = {} > > def proxy(*args): > > try: return cache[args] > > except KeyError: return cache.setdefault(args, callable(*args)) > > return proxy > ... > > I've got to the stage where my program is still not fast enough, and > > calls to the memoizer proxy are topping profiler output table. So I > > thought I'd try to see whether I can speed it up by recoding it in C. > > Have you tried psyco on above? Nope, but psyco would be politically unacceptable for my users, in this case. OTOH, I've been wanting to play with psyco for ages ... > Can any of your callables be memoized by list rather than dict? > (ie, any count or restricted int args?) You've lost me there. From spam at spam.com Sat Dec 13 07:17:59 2003 From: spam at spam.com (Matej Pivoluska) Date: Sat, 13 Dec 2003 13:17:59 +0100 Subject: Evaluating time References: Message-ID: Angelo Secchi wrote: > > What is the best way to check how long a python script takes to be > executed ? > > Thanks in advance > > angelo % time python yourscript.py -- mP http://pivoluska.matfyz.cz/ From ajsiegel at optonline.com Sat Dec 6 09:39:08 2003 From: ajsiegel at optonline.com (Arthur) Date: Sat, 06 Dec 2003 14:39:08 GMT Subject: Python's simplicity philosophy References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: <0rp3tvcgeb6v6b3nl8rdsk81e53kiphsu2@4ax.com> On Fri, 05 Dec 2003 02:48:40 -0500, Douglas Alan wrote: > >When people assert that > > reduce(add, seq) > >is so much harder to use, read, or understand than > > sum(seq) > >I find myself incredulous. People are making such claims either >because they are sniffing the fumes of their own righteous argument, >or because they are living on a different planet from me. On my >planet, reduce() is trivial to understand and it often comes in handy. >I find it worrisome that a number of vocal people seem to be living on >another planet (or could use a bit of fresh air), since if they end up >having any significant influence on the future of Python, then, from >where I am standing, Python will be aimed at aliens. While this may >be fine and good for aliens, I really wish to use a language designed >for natives of my world. The dynamics here are indeed sad. When an MIT guy says stuff like this, it is discountable because he is an MIT guy. What is trivial to him... When a guy like myself, with a degree in English and an MBA says essentially the same thing - it is more than discounted. It is persumptuos, almost, to be participating. The silliness of the converstations here, about what "I" of course can understand, but cannot expect others to grasp easily have been indeed a near downfall, in my eyes. At times, as you say, a broad and depressing insult seems to be eminating from those discussions. I've never noticed much insight in those discussion, and none have served the practical decision making process in connection with the future of Python well, at all. I would probably include the "sum" decision in the mix. Art From aahz at pythoncraft.com Sun Dec 7 11:02:38 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2003 11:02:38 -0500 Subject: Humpty Dumpty (was Re: Lists and Tuples) References: Message-ID: In article , Fredrik Lundh wrote: >Arthur wrote: >> >> "Type" is not normally an ambiguous word. > >really? in my experience, "type" and "object" are about as ambiguous >as words can get, especially when you're talking about Python. Hrm. I see your point, but I also think it's fairly easy to get people to agree on definitions for "type" and "object" within the context of a discussion. From my POV, the ambiguity comes from layering on additional meanings beyond that supported by the C API. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bwglitch at hotpop.com Mon Dec 8 20:51:37 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Mon, 08 Dec 2003 20:51:37 -0500 Subject: Converting a python script into a standalone application In-Reply-To: References: Message-ID: Sandeep Gupta wrote: > Hi, > > I've written a commercial application that uses Python scripts for > some of the functionality. Installing the Python portion of the > application requires me to first install Python, and then install the > scripts. I'm looking for an easier way to install the Python portion. > > I've been referred to: http://www.mcmillan-inc.com/install1.html > > Which application would people recommend for creating a standalone > executable? > > Are there any licensing issues I need to consider wrt including a > "Python runtime" with my distribution? You can also look at py2exe at http://starship.python.net/crew/theller/py2exe/ . Its license is BSD-like, AFAICT. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "I would've preferred a robot truck." "Heathen." -- Two Aliens, on Monkey Master, on January 23, 2001. http://www.itswalky.com/ From aahz at pythoncraft.com Tue Dec 23 11:01:27 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Dec 2003 11:01:27 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <3FE8652D.2E8F21A8@engcorp.com> Message-ID: In article <3FE8652D.2E8F21A8 at engcorp.com>, Peter Hansen wrote: > >P.S. My heartfelt thanks to whomever it was who posted the Lewis Carroll >reference lately... I'm _still_ trying to find my old copy of Through the >Looking Glass to find that section! Forgotten the Power Of Google? http://www.literature.org/authors/carroll-lewis/through-the-looking-glass/chapter-08.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From http Tue Dec 30 18:33:18 2003 From: http (Paul Rubin) Date: 30 Dec 2003 15:33:18 -0800 Subject: selecting a random item from a set References: Message-ID: <7xsmj1dgox.fsf@ruckus.brouhaha.com> Alexander Schmolck writes: > Quite a few algortihms prominently feature choosing/removing a > single random element from a set at a time. On first sight I can't > think of anything better to achieve this with `sets.Set` than > something along the lines of: > > for dummy, randomElement in zip(range(randrange(len(s)+1)), s): pass > # possibly followed by > s.remove(randomElement) > > Is there a better way? If not, how about something like Set.randompop()? The classic way to do it goes something like this: for n, randomElement in enumerate(s): if random() < (1.0 / (n+1)): e = randomElement # possibly followed by s.remove(randomElement) Note that you don't need to know the size of the set in advance. You can use the same method for (e.g.) choosing a random line from a file, without knowing how many lines the file has, and without having to read the file twice or store it in memory. Seeing why this works (unless I made an error) is left as an exercise :). From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 10 05:21:39 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 10 Dec 2003 11:21:39 +0100 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> Message-ID: Stuart Bishop: >Rene Pijlman: > >> from skin import template >> >> where skin is only known at runtime (it's passed as a parameter or >> hidden field to my mod_python application). > >That is scary - you need to treat anything arriving from the client >as an attack. Yes, I verify the name of the skin before the import. -- Ren? Pijlman From bokr at oz.net Fri Dec 19 17:02:19 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Dec 2003 22:02:19 GMT Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: On 19 Dec 2003 11:13:39 -0800, jcb at iteris.com (MetalOne) wrote: >I am trying to write a generator function that yields the index position >of each set bit in a mask. >e.g. >for x in bitIndexGenerator(0x16): #10110 > print x >--> 1 2 4 > > >This is what I have, but it does not work. >Changing yield to print, shows that the recursion works correctly. > >def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) > >What am I missing? Here is one that works also for negative numbers (includes the least significant of the arbitrarily extended sign bits): >>> def bitnos(self): ... """Little-endian bit number generator""" ... bits = long(self) ... sign = bits<0 ... bitno = 0 ... while bits>0 or sign and bits!=-1L: ... if bits&1: yield bitno ... bitno += 1 ... bits >>= 1 ... if sign: yield bitno ... (I'll use a subclass of long I recently posted (with missing ~ operator in first version, but fix followup posted) to show bits) The above is a mod of the bit list generator from the latter. >>> from lbits import LBits >>> >>> for i in range(-3,4)+[0x16, -0x16]: ... print '%3s %8r %s' %(i, LBits(i), [bit for bit in bitnos(i)]) ... -3 101b [0, 2] -2 110b [1] -1 11b [0] 0 0b [] 1 01b [0] 2 010b [1] 3 011b [0, 1] 22 010110b [1, 2, 4] -22 101010b [1, 3, 5] Regards, Bengt Richter From missive at frontiernet.net Fri Dec 26 17:25:05 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 26 Dec 2003 22:25:05 GMT Subject: sys.path[0] in IDLE Message-ID: Am I reading this correctly? http://python.org/doc/current/lib/module-sys.html """ As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. """ So, sys.path[0] should be the directory that my script is in? Even if running the script from IDLE? Has anyone else had problems with this? Especially on windows? From bhan at andrew.cmu.edu Mon Dec 22 02:50:19 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Mon, 22 Dec 2003 02:50:19 -0500 (EST) Subject: test if a file is locked? In-Reply-To: References: Message-ID: On Mon, 22 Dec 2003, Benjamin Han wrote: > On Mon, 22 Dec 2003, Carl Banks wrote: > > Fortepianissimo wrote: > > > > > > > > > I can lock a file using the following snippet: > > > > > > --- > > > import fcntl > > > > > > f=open('flock.txt','w') > > > fcntl.lockf(f.fileno(),fcntl.LOCK_EX) > > > --- > > > > > > If some other script tries to open 'flock.txt', it'll wait until the > > > file is unlocked/closed. > > > > > > My question is, I'd like to tell a script to quit *immediately* if it > > > cannot open the file, or, if it knows the file is locked. > > > > > > The reason I need this is I want to serialize parallel processes using > > > a lock file. Any suggestion is welcome! > > > > > > Try this: > > > > fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB) > > Ok looks like I'm still missing something: so how do you get 'f' without > using open() or file()? Either of these will put the script on hold... I got it, thanks! From jzgoda at gazeta.usun.pl Fri Dec 19 17:01:06 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Dec 2003 22:01:06 +0000 (UTC) Subject: any one used googles api? References: Message-ID: Bill Sneddon pisze: > Has anyone used googles API who would be will to share > a simple example. I have been wanting to play around with > SOAP for a while and this looks like a place to start. > > I am going to mess with it in ASP when our IT guys set it up > for me. I think I saw something on this topic at F. Lundh's site: http://effbot.org/zone/element-google.htm Frederik uses his own XML parsing library, but the idea is easy to understand. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From danb_83 at yahoo.com Thu Dec 11 21:49:22 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Dec 2003 18:49:22 -0800 Subject: Formatting floats References: <20031211143214964-0500@braeburn.themorgue.org> Message-ID: Kevin Smith wrote in message news:<20031211143214964-0500 at braeburn.themorgue.org>... > I'm trying to get floats formatted in exponent notation but with the > first non-zero number to the right of the decimal instead of to the left ( > e.g. '-.107E2' instead of '-1.07E1'). Is this possible using the string > formatting operations? >>> def formatFloat(x): ... mantissa, exponent = ('%e' % x).split('e') ... mantissa = float(mantissa) / 10 ... exponent = int(exponent) + 1 ... return '%fe%d' % (mantissa, exponent) ... >>> formatFloat(-1.07E1) '-0.107000e2' From aleax at aleax.it Fri Dec 26 04:29:34 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Dec 2003 09:29:34 GMT Subject: class creation References: Message-ID: <2cTGb.9029$_P.352385@news4.tin.it> km wrote: > Hi all, > > If i create a class "REX" and want to import it and test its > implementation in a python script what should be the file name of the > class file be ? Whatever you wish, as long as the extension is .py and you place the file in some directory along Python's sys.path. For example, if your "class REX:" (etc) is located in blaugh.py in the current directory, import blaugh r = blaugh.REX() is how you instantiate the class to get an instance r you can call methods on. Alex From duncan at NOSPAMrcp.co.uk Thu Dec 4 10:00:05 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 4 Dec 2003 15:00:05 +0000 (UTC) Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) wrote in news:8089854e.0312040649.4a7f1715 at posting.google.com: > I eventually discovered that (as a silly example) : > a = [[]]*10 > b=-1 > while b < 10: > b += 1 > a[b] = b > print a > > Produced : > [ [9], [9], [9]...... > > Which isn't at all what I intended............... > What is the correct, quick way of doing this (without using a loop and > appending...) ? The recommended way these days is usually: a = [ [] for i in range(10) ] That still has a loop and works by appending empty lists, but at least its just a single expression. Also you can incorporate the next stage of your initialisation quite easily: a = [ [b] for b in range(10) ] -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From nessus at mit.edu Sat Dec 6 22:49:02 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 06 Dec 2003 22:49:02 -0500 Subject: New inited instance of class? References: Message-ID: Samuel Kleiner writes: > Is there a builtin way of making making another instance of your own > class? I really expected type(self)(*args, **keywords) to work this way. Doesn't self.__class__(*args, **keywords) work? |>oug From reply.in.the.newsgroup at my.address.is.invalid Mon Dec 1 13:29:39 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 01 Dec 2003 19:29:39 +0100 Subject: Separation of content and code for web (was Re: Python for web ?) References: <3FCB8535.F8F89132@engcorp.com> Message-ID: Peter Hansen: >By far the most rigorous separation that I've seen to date, and one >we're experimenting with more right now, is to have a pure-HTML (or XHTML) >web page with *no* code or funky little embedded crap of any kind at >all, and rely exclusively on "id" attributes on the dynamic parts. [...] >I think there's a Java system where this idea was implemented best >but the name doesn't come to mind at the moment. XMLC (or what's left of it): http://xmlc.enhydra.org/ >Anyone know of a Python-based approach using the same core concept? ZPT: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/ZPT.stx -- Ren? Pijlman From bokr at oz.net Fri Dec 12 06:52:53 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Dec 2003 11:52:53 GMT Subject: Speed: bytecode vz C API calls References: Message-ID: On 12 Dec 2003 11:17:16 +0100, Jacek Generowicz wrote: >bokr at oz.net (Bengt Richter) writes: > >> On Tue, 9 Dec 2003 23:50:06 -0500, "Francis Avila" wrote: >> >> >Stuart Bishop wrote in message ... >> >>About the only thing that could be done then is: >> >> >> >>def memoize(callable): >> >> cache = {} >> >> def proxy(*args, _cache=cache): > >To be honest, I have trouble believing that a local variable lookup >would be significantly faster than a closure lookup ... or is there >some other point to this ? No, I think you are right. I was mainly reacting to the "there's no way" statement ;-) > >> >Not legal. *args must always come after default args. There's no way to do >> Never say never ;-) >> A function has the __get__ method, which is what getattr magic uses >> to make a bound method. You can use this put cache in the "self" >> position of a bound method, like >> >> >>> def sq(x): return x*x >> ... >> >>> def memoize(func): # callable is a builtin ;-) >> ... def proxy(cache, *args): >> ... try: return cache[args] >> ... except KeyError: return cache.setdefault(args, func(*args)) >> ... return proxy.__get__({}, proxy.__class__) > > >> Looking at the code, it might be worth timing, if you have 90%+ cache hits. >> I'd be curious to see what you get > >I get your version being almost imperceptibly slower. > >I used this: When things are that close, it's very hard to draw conclusions except that they are probably close ;-) But to split hairs you probably have to run the two tests separately, in quiescent system situations, so that the first is not improving or worsening the environment for the second (i.e., in terms of interpreter state re memory, or even cpu cache in some cases, though that usually only applies to the first time through a loop. And also keep the fastest of 5-10 trials, to eliminate glitches due to spurious irrelevant system activity. I don't have your "timing" module, so I don't know what it does. If it randomly reordered multiloop trials of A vs B and took minimums, then maybe interactions could be washed out, but otherwise A & B in the same test source leaves some ambiguity about the real ranking (which of course will not matter, practically speaking;-) > >import timing >import sys [...] Regards, Bengt Richter From http Sun Dec 21 02:52:55 2003 From: http (Paul Rubin) Date: 20 Dec 2003 23:52:55 -0800 Subject: web programming: experiences with non-zope frameworks? References: Message-ID: <7xu13u7gko.fsf@ruckus.brouhaha.com> Brendan O'Connor writes: > Can anyone make comparisons among the different frameworks? What > combinations of packages do people use? Are *any* of them substantially > more popular than any other? There have been a few other comparisons done. That shootout page you mentioned isn't bad. Zope is the most established but is its own world. Twisted to me shows the most determination to do things correctly, but its learning curve is steep, and there's a lot that it doesn't do for you. Basically none of these systems impresses me as really being ready for prime time. > I think it would be nice to have not another list of several dozen one-man > projects, but rather a collection of practical knowledge to narrow a > python web programmer's options to the realistic and mature choices. The closest thing to a realistic and mature choice is Zope, and yet it's not really satisfying. I'll give some heretical advice: if you're doing a big project, set aside some of the development time to evaluate what's out there and adopt or develop something that's best for your specific needs, with the understanding that you're going to have to maintain it yourself. If you're doing a small project and can't afford to set aside that much time, then hold your nose and write in PHP or even Perl (HTML::Mason is an impressive package if you don't mind the cancer that is Perl, so it would be great if someone wrote something like it for Python). Another approach: some friends of mine did a hybrid system with a web interface in PHP and backend functions in Python, and were very happy with the results. My reaction is that if Python and PHP both had big enough shortcomings to justify the cost of the two-interpreter, two-language approach, then then neither of them really deserves advocacy. Python is certainly a better implementation language than PHP, but if you're doing web applications in it, you really need a pioneer spirit. After you get through choosing and evaluating a web framework, you next have to choose and evaluate a database interface--sheesh. Python is nowhere near as mature for out-of-the-box quick web development as PHP is. Of course that may change in the future. However, that's the state of things today. From km at mrna.tn.nic.in Tue Dec 30 11:47:38 2003 From: km at mrna.tn.nic.in (km) Date: Tue, 30 Dec 2003 22:17:38 +0530 Subject: inline Message-ID: <20031230164738.GA4140@mrna.tn.nic.in> Hi all, Does python support inline assembly ? (like C ) how can one do that in Python ? any link to third party module ? kindly enlighten thanks, KM From skip at pobox.com Tue Dec 30 12:04:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Dec 2003 11:04:52 -0600 Subject: Is Python Mac Centric??? In-Reply-To: References: Message-ID: <16369.45108.486150.170933@montanaro.dyndns.org> >> Also, I've noticed that OSX 10.3 comes with Python 2.3 installed, Tim> That was Apple's decision, not "ours". >> but that Windows XP does not. Tim> And that's Microsoft's decision, not "ours". We can't tell OS Tim> vendors what to ship, and all OS vendors are equally free to Tim> redistribute Python (the Python license extends that right to Tim> everyone who wants it). While Microsoft doesn't bundle Python with Windows, there are one or two PC makers who add Python to their Windows boxes (HP comes to mind - the practice appears to have originated at Compaq before HP acquired it). I think that's mostly to support their extra admin tools, not to encourage all their customers to start writing software. Skip From __peter__ at web.de Tue Dec 9 15:29:09 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 21:29:09 +0100 Subject: Nub needs help withTkinter References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> <1cca69c7.0312081017.27140c39@posting.google.com> <1cca69c7.0312091129.72af0e05@posting.google.com> Message-ID: Agency wrote: > O.K. > > So, I'm stuck again. I tried putting the code into a class, might not > be > smart given what I know, but I did it. I'm thinking that the beat, > time, and bpm would each have their own class and display/label. I > know that the pack() determines if something shows up. So, I'm > guessing that somewhere along the line pack() is not be referenced > right. My problem is that I have a window, > with no label showing up. I also just noticed that there is no linkage > between the beatContainer/frame and the beatNum/label. Here is the > newbie code: > > from Tkinter import * > > > class beatX: > def _init_(self, parent): > self.beatContainer = Frame(parent) > self.beatContainer.pack() > > self.beatNum = Label(self, text = "Beat Counter : ") > self.beatNum.config(text = "Beat Counter : %d" %beats) > self.beatNum.pack() > self.beatNum.bind("", self.beatCounter) > self.beatNum.bind("", self.beatReset) > > def beatCounter(event): > print "increment counter" > beats = beats + 1 > > def beatReset(event): > print "reset counter" > beats = 0 > > root = Tk() > root.mainloop() The Tkinter toolkit has problems of its own, so you better learn the basics first: The __init__() method has two preceding and two trailing underscores. Every method in a class has self as the first parameter, unless you know why it's otherwise. The class definition is normally not sufficient, you will also want at least one instance, created like so: instance = Class(args). Now to your beatX class. I've made the minimum changes necessary to avoid a traceback and ignorance of user input, and I recommend that you change it incrementally to meet your needs, so that when - not if :-) - it breaks again you can go back to the previous state. See the beats attribute for the simplest usage pattern of a class attribute and how showCounter() is invoked in three different places to keep the beatNum Label uptodate. from Tkinter import * class beatX: def __init__(self, parent): self.beatContainer = Frame(parent) self.beatContainer.pack() self.beats = 0 self.beatNum = Label(self.beatContainer) self.beatNum.pack() parent.bind("", self.beatCounter) parent.bind("", self.beatReset) self.showCounter() def showCounter(self): self.beatNum.config(text="Beat Counter : %d" %self.beats) def beatCounter(self, event): print "increment counter" self.beats = self.beats + 1 self.showCounter() def beatReset(self, event): print "reset counter" self.beats = 0 self.showCounter() root = Tk() b = beatX(root) root.mainloop() Again, learning the language with a non-GUI script will probably be more rewarding. Good luck! Peter From jjl at pobox.com Sun Dec 21 19:58:58 2003 From: jjl at pobox.com (John J Lee) Date: Mon, 22 Dec 2003 00:58:58 +0000 (GMT) Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: <20031221235511.GA11803@titan.progiciels-bpi.ca> References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> <20031221235511.GA11803@titan.progiciels-bpi.ca> Message-ID: On Sun, 21 Dec 2003, [iso-8859-1] Fran?ois Pinard wrote: [...] > To quickly check that it works, once in the new Vim, try: > > :py print 3 + 5 > > and you should see `8' in the bottom line. Thanks. BTW, one question I forgot to ask, which is maybe the most important from my point of view: how do your fingers like vi? Mine have never been completely happy with the standard emacs keys, but I don't like to change them. I keep meaning to give the vi keys a chance, but it's almost like learning to type again... > > I'm currently thinking of ditching pine (for something, like pine, > > that's cross-platform, does IMAP well, is free (beer) but also libre, > > has a decent disconnected mode, preferably written in a high-level > > language, and that doesn't offer remote buffer overflows on its > > feature list!... except such a beast doesn't seem to exist). > > Gnus was really marvelous, nothing can really compare with it. I looked [some of below is on-topic, promise ;-] I use it for news (apart from now, since I got this as email, not news). Does it do good disconnected IMAP, I wonder? Very very few programs seem to do that *useably* (for my habits, anyway). KMail seems to be growing support for that, but it's very new. > around a bit for a replacement, and the best I came with is Mutt. I > did not consider Pine for long, but do not remember why I excluded it. I've used it (pine) for almost ten years (never seriously used anything else), and it's nice, but: - weird non-libre-ish licence, pain to install on Debian - written in C: improvements are slow to arrive (especially given the weird license and "cathedral-style" development system), and the usual overflows - recent remote send-email-to-become-root overflow exploits! - offline and disconnected-mode support is poor to non-existent (bad if you use a modem) > Getting Mutt and some of my Python scripts to really cooperate required > some doing, and a few kludges, and I still feel very far from having a > mail agent offering Python as an extension language. I also saw Python There's Mahogany, but it's GUI-based (dunno if the keyboard support is good, which my hands regard as essential). I'm also not sure if the Python support is actually stable. > extensible mail agents, but which had some weakness in the underlying > mail engine, so far that I could judge. Yes, it seems like it's bound to be one of those things that are messy enough to take years of bug fixes to get really right. I once contemplated writing a clone of pine in Python, but I expect it's just too much work to seriously consider. With Barry Warsaw's email module being used by Mailman (Barry again, of course), I suppose that takes care of *some* of the mess, but far from all. And the names "pyne" and "balsa" are already taken <0.5 wink> ("twig", maybe? "stick"? "needle"? No, of course, it'd have to be "larch"!-). [...] > it. In my case at least, the big move is now part of the past, the main > suffering is behind. You talk like an ex-drug addict ;-) > > | I still have no idea on the Vim capabilities for controlling highlighting > > > I've always thought the way to do this must be to allow both simple > > high-level language (elisp, python) ways of doing this for covering the > > broad range of languages &c., and some kind of low-level (C, I guess) > > plugin standard for wiring up editors to things like the Python parser. > > Who wants to reimplement the Python parser, after all? > > This is about editing SGML, isn't it? I wrote something for Emacs [...] Yes, but not only SGML. python-mode has quirks (I suppose mostly to do with things other than syntax colouring -- paragraph-fill, for example) that could be fixed with proper parsing rather than (I presume) the bunch of regexes that python-mode gets by with. If Mark Hammonds Windows editor does it, I don't see why Emacs and vi shouldn't. John From skip at pobox.com Tue Dec 23 11:45:40 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 23 Dec 2003 10:45:40 -0600 Subject: Flat file database In-Reply-To: References: Message-ID: <16360.28980.440813.523855@montanaro.dyndns.org> Art> Is there any Python module designed to simplify the use of a plain Art> text file as a flat file database? Several others have mentioned various possibilities. If Python 2.3 is available to you, you might consider the csv module. You can edit the files with Excel or another spreadsheet. In your code, you can use the csv.DictReader class to pull out the fields of interest: # just off the top of my head! def select(where, csvfile): "return rows from csvfile which overlap with dictionary 'where'." results = [] for row in csv.DictReader(csvfile): if matches(where, row): results.append(row) return results Coding of the matches function is left as an exercise for the reader. Skip From grey at despair.dmiyu.org Mon Dec 22 01:00:40 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 22 Dec 2003 06:00:40 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: On 2003-12-22, Mel Wilson wrote: > Cute. Every function returns something.. None if > nothing else.. except for functions that don't return. > def v(): > raise ValueError > would be another variation on the theme. You're missing the point, aren't you? Is it intentionally missing it or are you that dense? -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From missive at frontiernet.net Sat Dec 27 16:53:30 2003 From: missive at frontiernet.net (Lee Harr) Date: Sat, 27 Dec 2003 21:53:30 GMT Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> Message-ID: On 2003-12-27, Midas wrote: > Thanks for replying. > It looks like you hardcoded the name ObjectB within ClassA. I'd like to avoid all hardcoding of names. In other words, I'd like ObjectA to be *told*, at run time, which object to call and which method to call. > > On Sat, 27 Dec 2003 21:42:05 +0100, Lawrence Oluyede wrote: > >>You could simply do something like this: >> >>class A: >> def __init__(self): >> self.ObjectB = B() >> >>class B: >> def someMethod(self): >> pass >> >>if __name__ == "__main__": >> ObjectA = A() >> ObjectA.ObjectB.someMethod() class A: def __init__(self): self.b = B() def run_time(self, method_name): getattr(self.b, method_name)() class B: def foo(self): print 'foo!' a = A() a.run_time('foo') From lvraab at earthlink.net Fri Dec 12 17:01:24 2003 From: lvraab at earthlink.net (Lucas Raab) Date: Fri, 12 Dec 2003 22:01:24 GMT Subject: Building problem Message-ID: I've downloaded a set of modules and when using the MS-DOS prompt: python setup.py build (or install) the following message appears: error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. Has anyone else seen this problem? If you have, any feedback would be much appreciated. From boris.boutillier at arteris.net Tue Dec 2 08:24:00 2003 From: boris.boutillier at arteris.net (Boris Boutillier) Date: Tue, 02 Dec 2003 14:24:00 +0100 Subject: Module for doing some Parsing in Python Message-ID: Hi all, I'm looking for parsing a Verilog file in my python module, is there already such a tool in python (a module in progress) to help instead of doing a duplicate job. And do you know of some generic parsing module in python, in which you give some kind of grammar and callbacks ? Thanks for the help Boris From lkcl at lkcl.net Tue Dec 16 16:30:41 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 21:30:41 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195200.GI17021@lkcl.net> Message-ID: <20031216213041.GM17021@lkcl.net> On Tue, Dec 16, 2003 at 09:08:37PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > > I fail to see how ACLs are a sound basis to solve the problem that > > > rexec solves. ACLs, in my view, are a sound basis to solve a different > > > problem (that of different identities accessing the same resources). > > > > substitute "identity" for "calling object" i.e. function and i > > believe that there is a viable proposal. > > I don't think so. Suppose I have an object A protected by ACLs. Now I > write a new method > > def doit(): > A.doit() > > Question 1. What is the calling object? the globally-defined doit function. > Question 2. Assuming it is "the doit function", and assuming the doit > function is not listed in the ACL: Will the call be executed? see below. > If yes: What is the purpose of the ACL then? > If no: I believe the proposal is not usable in practice. For example, > what should be the ACL on calling open()? okay. that is why in ACLs (or better CCLs) it is necessary to have an "all functions" wildcard "name". in NT, this is the "world" security id "S-1-1" (i think) which represents "everyone". if you set a CCL, and you expect to deny everything but a particular function, you must have a two-entry CCL: [('function_to_be_denied_access', DENY, 'permissions_to_be_denied'), ('all functions', 'ALLOW', 'anything')] and yes, this is _normal_ practice in the use of ACLs in NT and VMS. and yes, the default action is (IIRC), "if not explicitly stated, deny". with the exception to that, of course, that if no CCL is set, it's "as if" there was a CCL set of [('all functions', 'ALLOW', 'anything')]. l. From nospam at nopes Tue Dec 23 23:27:56 2003 From: nospam at nopes (Steve) Date: Wed, 24 Dec 2003 15:27:56 +1100 Subject: A dictionary list? Message-ID: <3fe91593@clarion.carno.net.au> Hi, How can I create a list of a dictionary? (in other words, I need to create an array of a dictionary). Please help! Steve From nessus at mit.edu Mon Dec 8 01:05:28 2003 From: nessus at mit.edu (Douglas Alan) Date: Mon, 08 Dec 2003 01:05:28 -0500 Subject: Case sensitive and ludicrous statements References: Message-ID: mjackson at alumni.caltech.edu (Mark Jackson) writes: > Re. CamelCase and SmallTalk: ISTR that the Alto keyboard lacked an > underscore character (I believe the character code was used for > left-arrow, which I vaguely recall was used for assignment in BCPL > and/or Mesa). As constructions like foo_bar are the obvious > alternative to FooBar, could this lack have been a factor at PARC? That sounds plausible. I think I also remember using a computer at some point that didn't have an underscore character. It's hard to come up with another explanation -- the Smalltalk folk where way too smart to have done something that on the face of things is quite silly. |>oug From martin at v.loewis.de Sun Dec 7 12:31:49 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Dec 2003 18:31:49 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: "Fredrik Lundh" writes: > otoh, it would make sense to use 8-bit strings to store Unicode strings > that happen to contain only Unicode code points in the full 8-bit range > (0..255). I'm not sure about the advantages. It would give a more efficient representation, yes, but at the cost a slower implementation. Codecs often cannot know in advance whether a string will contain only latin-1 (unless they are the latin-1 or the ascii codec), so they would need to scan over the input first. In addition, operations like PyUnicode_AsUnicode would be very difficult to implement (unless you have *two* representation pointers in the Unicode object - at which time the memory savings are questionable). > I assume you meant: > > Yes, all library functions that expect *text* strings should support > Unicode objects. Correct. > having written Python's Unicode string type, I'm now thinking that > it might have been better to use a polymorphic "text" type with > either UTF-8 or encoded char or wchar buffers, and do dynamic > translation based on usage patterns. I've been playing with this > idea in Pytte, but as usual, there's so much code, and so little > time... "Better" in what sense? Would it even be better if you had to preserve all the C-level API that we currently have? Regards, Martin From ods at strana.ru Mon Dec 1 09:12:59 2003 From: ods at strana.ru (Denis S. Otkidach) Date: Mon, 1 Dec 2003 17:12:59 +0300 (MSK) Subject: compile(unicode) & source encoding In-Reply-To: Message-ID: On 28 Nov 2003, Martin v. [iso-8859-15] L?wis wrote: MvL> > 1. What is the reason to encode source code to utf-8? MvL> MvL> I think it is because Just found that the most MvL> straight-forward thing MvL> to do: UTF-8 supports all Unicode characters, and you have MvL> to choose MvL> *some* encoding, as the resulting byte strings need to be MvL> encoded MvL> somehow. Why we have to choose one particular encoding and not just assume all strings to be unicode? MvL> In addition, anybody desiring a different encoding can MvL> explicitly MvL> invoke .encode() Surely. But there is no way to emulate "python -U" behavior for compiled piece of code. -- Denis S. Otkidach http://www.python.ru/ [ru] From ny_r_marquez at yahoo.com Wed Dec 10 09:09:43 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 10 Dec 2003 06:09:43 -0800 Subject: python com wrappers References: <87k756szxh.fsf@pobox.com> Message-ID: <8a27e309.0312100609.375c66f3@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87k756szxh.fsf at pobox.com>... > Paul Rudin writes: > [...] > > seems to solve the problem, although perhaps this breaks something > > else? > > Try posting what you just wrote to the python-win32 list. > > > John John, Could you provide a pointer to that list? I know of the Mailing Lists at Source Forge, but they are just a bug reporting one and checkins one. Thanks. From brett at python.org Mon Dec 1 22:34:07 2003 From: brett at python.org (Brett C.) Date: 1 Dec 2003 19:34:07 -0800 Subject: python-dev Summary for 2003-10-16 through 2003-11-15 References: <3fc7a20a$0$41748$5fc3050@dreader2.news.tiscali.nl> Message-ID: <8ab0589d.0312011934.3bf5feb8@posting.google.com> "GerritM" wrote in message news:<3fc7a20a$0$41748$5fc3050 at dreader2.news.tiscali.nl>... > "Brett C." wrote in message > news:mailman.1153.1069961629.702.python-list at python.org... > > python-dev Summary for 2003-10-16 through 2003-11-15 > > ++++++++++++++++++++++++++++++++++++++++++++++++++++ > > > > This is the twenty-eighth and twenty-ninth summaries written by Brett > > Cannon (does anyone even read this?). > > Yes, absolutely, every time. Normally I go to the website, to read the > formatted version. This time I could not yet find it, so I read the raw text > version. > Sorry about that. I just pushed the new pages to the web site. One of these days I need to write a script to do all of the standard stuff that I do for each summary so that I stop having minor screw-ups like this. > keep up the good work, kind regards, Gerrit Thanks, I'll try. -Brett From nessus at mit.edu Mon Dec 8 16:07:39 2003 From: nessus at mit.edu (Douglas Alan) Date: Mon, 08 Dec 2003 16:07:39 -0500 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: "rzed" writes: > Douglas Alan wrote: >> I used Pascal in the very late '70's and very early '80's, and I >> never saw anyone use CamelCase in it. And now that David Epstein >> has jogged my memory -- it is indeed in SmallTalk that I first saw >> people using CamelCase, and, I must say, I was rather aghast. >> >> IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopleWouldWriteLike>> ThisAllTheTime. >> >> |>oug > There's nothing about case standards that suggests that removing > spaces between lexical units is a good thing. Right -- removing spaces is not a good idea, because spaces aid in readability. The traditional (i.e. pre-CamelCase) way of separating words in indentifies was to use dashes or underscores. As in, If-dashes-used-to-seperates-words-within-identifiers-were-a-good-idea- then-everyone-would-write-like-this-all-the-time. And they probably would, if there weren't able to use spaces. It's much more readable than the CamelCase version. > In any event, it would > be preferable to > "IFCAMELCASEWEREAGOODIDEAEVENINACASESENSITIVELANGUAGE, > THENPEOPLEWOULDWRITELIKETHISALLTHETIME." in either a case-sensitive or > case-insensitive language. That's for sure, but I don't think that that idea is on the table. It's always been common, when not using CamelCase, to use dashes or underscores. > The worst-case (as it were) scenario that I can remember happened when > I was working with PL/I on an IBM mainframe, using 3270 terminals. > This was a case-insensitive language, so some people adopted the > conventions others have mentioned (constants in ALL_CAPS, functions > and procedures in camelCase (sometimes) -- but some didn't. Some coded > with the terminal set to *display* all caps (which allowed typing in > lower case without being aware of it), and some didn't. Some of each > group modified the code of programmers from the other group, and when > the terminals displayed case as entered, the result was an unholy > hodgepodge of upper and lower case clumps of letters in the oddest > places imaginable. There was no apparent rhyme or reason to the case > changes, even though everyone was utterly systematic about how they > did their coding. All the more reason to standardize on dashes or underscores. > The reason people chose to mix their cases is that one-case code is > difficult to read. no it isn't. it isn't even difficult to read one-case english. |>oug From exarkun at intarweb.us Wed Dec 10 09:18:27 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 10 Dec 2003 09:18:27 -0500 Subject: multi-threaded app hangs In-Reply-To: <013101c3befa$73cbbfa0$3f0aa8c0@arindamlap> References: <013101c3befa$73cbbfa0$3f0aa8c0@arindamlap> Message-ID: <20031210141827.GA15478@intarweb.us> On Wed, Dec 10, 2003 at 02:18:58PM +0530, Sudipto Biswas wrote: > Hi, > > I have written a multi-threaded (about 8 threads) networking application > with a text-mode interface. It writes to a trace-file in the background. > Additionally I have also given some debug prints to STDOUT from different > threads. The program runs fine on Python-2.2.2/RH 8.0. > > But when I move to Python-2.2.2/RH-9.0 the program behaves oddly. It stops > suddenly and *does not* give the continueous stream of expected output in > STDOUT and tracefile. > > On pressing ctrl-Z the hanged program gets suspended. On giving 'fg' > command the suspended program comes to foreground, AND AGAIN RUNS FOR > SOMETIMES (generates stream of text in STDOUT and tracefile) before it > hangs again. This way ctrl-Z and 'fg' if pressed on hang, helps the > program to run further. > > I am using the 'Thread' class to create objects which run as separate > threads. > > Has anybody faced a similar problem? Often, threaded programs will behave in mysterious ways. This is due to something called a "race condition", where the thread which reaches a particular section of code varies, leading to different behavior each time that particular section of code is run. One way to prevent this is to use locks, so that code is always run in the same order. Another way to prevent it is to simply avoid using threads. For a network application, this is fairly simple. Just use non-blocking or asynchronous I/O. In the standard library, asyncore helps to do this. As a third party module, Twisted (http://www.twistedmatrix.com) helps a *lot* more. Jp From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 3 18:30:23 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 04 Dec 2003 00:30:23 +0100 Subject: Why Python (a bit different) In-Reply-To: References: <3fce6605$0$248$a3f2974a@nnrp1.numericable.fr> Message-ID: <3fce720f$0$212$e4fe514c@news.xs4all.nl> Skip Montanaro wrote: > Gerald> 'Why did Guido create Python?' > > Start here: > > http://artima.com/intv/ > > Search for "Guido". That is a very valuable suggestion. I thoroughly enjoyed reading those interviews with Guido when they were published on the site. And not only because they tell about Python's origin. And Bill Venners has some more interesting interviews there. --Irmen From tjreedy at udel.edu Sun Dec 7 00:04:57 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 7 Dec 2003 00:04:57 -0500 Subject: list.sorted() References: Message-ID: "Robert Brewer" wrote in message news:mailman.170.1070745662.16879.python-list at python.org... >reverse is not true: you can't call normal instance methods from the >class--you get a TypeError by not passing an instance for "self" to bind to. Yes you can: explicitly pass an instance as first arg for 'self' to bind to ;-) (or did I misunderstand your claim?) TJR From francisgavila at yahoo.com Mon Dec 22 18:43:34 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 18:43:34 -0500 Subject: Using both keyword=something and *unknownqty arguments in a function References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: EP wrote in message ... >Is it possible? > >def skeptic(first='Zeus', second='Guido', *others) > print first > print second > print others > return "and I did not think it could ever work!" > >answer=skeptic('believer', 'non-believer', 'heretic', first='Eric', >second='unknown') > >Asking this seriously, please forgive any cuteness. Is there a way this >can be made to work, or are these two types of arguments mutually exclusive? This particular case seems to be theoretically possible but the implementation can't handle it. Enter a feature request. You may end up having to write a PEP if this is deemed a change of semantics, and it may very well be. I think there's a deeper issue here: you want Python to assign default args first, then fill in positional arguments, skipping over those already assigned. Python wants all arguments to be assigned positionally, and then to have keyword arguments assigned at the end (with the result that in certain combinations of calls and default arguments, things get assigned twice; hence your error.) And Python wants this for a very good reason: it's a far clearer and simpler specification. If you assign keyword arguments first, then positional, you have to do all sorts of magic to figure out what the programmer really means; and it may get it wrong, which means the programmer has to figure out what *Python* expects, and hence has to sort through a complex spec. In programming languages, to strive for DWIM will always give us perl. If DWIM isn't right 99.9% of the time, it's far more confusing than giving a simple, consistent spec, to which the programmer conforms. The simple reason for this is that people are far more adaptable than computers, and the onerous is always on us, in the end, to learn to use a language. So would you rather learn a simple language, or a complex one? A DWIM language will inevitably be complex. Of course, you can take this to the opposite extreme, in which we have Forth, Lisp/Scheme, and assembly. :) So the issue isn't the optional arguments (the '*others') at all. For example, should the following be allowed? def g(a=1, b): return a,b Should you be able to call it like this: g(2, a=9) and get (9, 2)? From what you say, you're leaning towards 'yes'. Python, however, says explicitly, 'no', in section 7.5 of the language reference. "If a parameter has a default value, all following parameters must also have a default value." I could even argue that *allowing* you to have a tuple argument after keyword arguments is a violation of the specs. As usual, the specs aren't the clearest or most unambiguous, and we need to go by the reference implementation. IMO, I think what you propose is a bit confusing. The function must assume that if default arguments are specified explicitly, then they must be ignored as positional. Let's do a thought experiment: def f(a=1, b=2, *c): return a,b,c f(9) # Whose argument is this, a or c? -> (9, 2, ()) #Python says a's. So it interprets as positional. f(b=9) -> (1, 9, ()) f(a=1, 2,3,4) # Does 2 belong to b or to c? -> SyntaxError # Python resists the urge to guess. 'import this' f(2,3,4, a=1) # Does 2 belong to a, to b, or to c? -> TypeError #Python says, to 'a'. And trips over itself. But true question remains unanswered. Here's a real toughie: f(2,3,4,b=1) # To whom does 2, 3, and 4 belong? You already know what Python says, but I bet you're not sure what *you* would say, nor what some other programmer would say. So you now see the Python philosophy quite clearly: you may not like what Python does, but you certainly understand it unambiguously! Your scenario of f(3,4, a=1, b=2) is the only one where an unambiguous answer is conceivably possible. But if Python allows the semantics you prefer, it will complicate the implementation and the specification, and further it will encourage this sort of behavior, leading to the scary possibility of a future PEP that suggests that f(2,3,4,b=1) have a legal interpretation, too! You should be happy enough that we have default and keyword arguments at all: they are a tradeoff between convenience and simplicity/explicitness. I think Python has achieved the right balance here, and we shouldn't ask too much, lest we regret our asking. -- Francis Avila From jjl at pobox.com Wed Dec 3 13:16:14 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Dec 2003 18:16:14 +0000 Subject: comparing nan "number" References: <87vfp01muq.fsf@pobox.com> <87znebe6ux.fsf@pobox.com> Message-ID: <87ptf5lqc1.fsf@pobox.com> Michael Hudson writes: > jjl at pobox.com (John J. Lee) writes: > > > Alexander Schmolck writes: > > [...] > > > possibly be `False` and {x:"some value}[x] might well raise an exception if > > > `x` is a nan (or indeed one of infinitely many Numeric arrays with > > [...] > > > > Don't you mean SomeMapping((x, "some value"))[x]? A dict lookup > > doesn't use __eq__. > > Huh? Yes it does (*after* __hash__, of course, but...). Oh, collisions, right? John From mwh at python.net Thu Dec 4 07:16:25 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Dec 2003 12:16:25 GMT Subject: segfault in extension module References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: Nat Echols writes: > > Post some code. > > may god have mercy on my soul: Well, I can't see anything flagrantly wrong with that. Does a debugger provide any hints? Cheers, mwh -- [3] Modem speeds being what they are, large .avi files were generally downloaded to the shell server instead[4]. [4] Where they were usually found by the technical staff, and burned to CD. -- Carlfish, asr From ajsiegel at optonline.com Sun Dec 7 08:46:21 2003 From: ajsiegel at optonline.com (Arthur) Date: Sun, 07 Dec 2003 13:46:21 GMT Subject: Lists and Tuples References: Message-ID: On Fri, 5 Dec 2003 11:10:34 -0600, Skip Montanaro wrote: >Generally, choose between tuples and lists based upon your data. In >situations where you have a small, fixed collection of objects of possibly >differing types, use a tuple. In situations where have a collection of >objects of uniform type which might grow or shrink, use a list. For >example, an address might best be represented as a tuple: > > itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201") > caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866") > >Though all elements are actually strings, they are conceptually different >types. It probably makes no sense to define itcs as Some of my confusion derived from these semantic issues. We are strongly typed and when the list/tuple distinction starts to be talked with the words "types"," homogenous" , "heterogenous" in close proximity - we, on the receiving end, will .... I think the potential misdriection is obvious from your explanation above. "Type" is not normally an ambiguous word. It seems to me that an explanation would stress, upfront, that in fact homogenous.hetereogenous in this context is at an abstract level, and unrelated to type,as such and as your example illustrates. Or else, why does the word "type" need to occur at all, other than perhaps to explain, explicitily, it is not of relevance Rather than in a way that implies that it is. This is a question really. Though not properly phrased as one. Because I fear I am still missing something. Art From CousinStanley at hotmail.com Wed Dec 31 16:57:53 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 31 Dec 2003 14:57:53 -0700 Subject: Project dream References: Message-ID: | This site is out of date. | Clicking on "this months requests" | shows stuff from May of 2000 Brad .... The site is old and out of date, but I think that many of the requests for programs may still be valid and perhaps a good source of inspiration for coders looking for projects .... Pack a lunch, then try the Request Archive .... http://www.csn.ul.ie/~madman/software/madereq/archived.htm -- Cousin Stanley Human Being Phoenix, Arizona From tudor.tata at tin.it Sat Dec 13 09:36:26 2003 From: tudor.tata at tin.it (tudor) Date: Sat, 13 Dec 2003 14:36:26 GMT Subject: python2.3 upgrade Message-ID: hello! I had python 2.2.1 so I upgraded to python 2.3.2, but all my applications using python (rh8) give errors now. I installed from src.rpm Traceback (most recent call last): File "/usr/sbin/redhat-switch-printer", line 84, in ? main() File "/usr/sbin/redhat-switch-printer", line 68, in main from switchprinter_gui import mainDialog File "/usr/share/redhat-switch-printer/switchprinter_gui.py", line 51, in ? import gtk ImportError: No module named gtk Should I GO BACK TO 2.2.1? Thanks From marko.faldix.tudisweck at mplusr.de Mon Dec 15 05:04:04 2003 From: marko.faldix.tudisweck at mplusr.de (Marko Faldix) Date: Mon, 15 Dec 2003 11:04:04 +0100 Subject: codecs latin1 unicode standard output file Message-ID: Hello, with Python 2.3 I can write umlauts (a,o,u umlaut) to a file with this piece of code: import codecs f = codecs.open("klotentest.txt", "w", "latin-1") print >>f, unicode("My umlauts are ?, ?, ?", "latin-1") This works fine. This is not exactly what I wanted to have. I would like to write this to standard output so that I can use same code to produce output lines on console or to use this to pipe into file. It was possible before Python 2.3. Isn't possible anymore with same code? -- Marko Faldix M+R Infosysteme Hubert-Wienen-Str. 24 52070 Aachen Tel.: 0241-93878-16 Fax.:0241-875095 E-Mail: markopointfaldix at mplusrpointde From bokr at oz.net Wed Dec 3 17:41:38 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Dec 2003 22:41:38 GMT Subject: Turning f(callback) into a generator References: Message-ID: On Wed, 03 Dec 2003 18:48:41 +0100, Peter Otten <__peter__ at web.de> wrote: >It's easy to write a function that wraps a generator and provides a >callback. E. g.: > >import os, sys > >def walk(path, visit): > """ Emulate os.path.walk() (simplified) using os.walk()""" > for dir, folders, files in os.walk(path): > visit(dir, folders + files) > > >if __name__ == "__main__": > walk(".", lambda d, f: sys.stdout.write(d + "\n")) > > >However, I did not succeed in turning the old os.path.walk(), i. e. a >function taking a callback, into a generator. Is there a general way to do >it without having to store all intermediate results first? > > >Peter > >PS. No, I don't have a use case. Threads welcome if all else fails :-) > I suspect that's what is necessary currently, until we get a yield that can suspend a whole stack of frames at a yield inside nested calls to functions. Then it would just be a matter of putting a yield in a callback routine and starting the walk from the base generator-making function/method/whatever. Maybe deep generators could be created via an __iter__ method of the function type as an alternative/extension to has-yield-in-function-code-body magic. Exit from the generator wouldn't happen until you exited the base frame. Yield in a nested function call would just suspend right there. Easier said than done, of course ;-) Regards, Bengt Richter From phildog22 at yahoo.com Fri Dec 12 12:27:18 2003 From: phildog22 at yahoo.com (Phil D.) Date: Fri, 12 Dec 2003 09:27:18 -0800 (PST) Subject: Recording web page URLs Message-ID: <20031212172718.26311.qmail@web41508.mail.yahoo.com> Hello everyone, I'm building a python application that will monitor a person's behavior with his mouse while surfing the web (probably using Internet Explorer). I want to record the URLS of the pages he visits. Is there a simple way to do this in python? Thanks, Phil --------------------------------- Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sat Dec 13 20:47:36 2003 From: http (Paul Rubin) Date: 13 Dec 2003 17:47:36 -0800 Subject: ANN: lunatic-python 0.1 References: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> <878ylgjj3h.fsf@pobox.com> Message-ID: <7xzndwxj9j.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > In fact, even if you *are* sending him your credit card details, it's > *still* of almost no consequence, SSL being pretty useless in practice > (see Bruce Schneier's writings on the subject, eg. in "Secrets and > Lies")... I wouldn't say SSL is useless in practice, but the CA business certainly is 99% scam. From mfranklin1 at gatwick.westerngeco.slb.com Tue Dec 16 11:03:36 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 16 Dec 2003 16:03:36 +0000 Subject: introspecting builtin functions/methods In-Reply-To: References: Message-ID: <1071590616.4010.0.camel@m-franklin> On Tue, 2003-12-16 at 15:56, =?UNKNOWN?Q?Gon=E7alo?= Rodrigues wrote: > Hi, > > Does anyone know if and how I can, from within Python, read the > signatures of builtin methods/functions? > > The following fails: > > >>> import inspect > >>> inspect.getargspec(list.append) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\inspect.py", line 655, in getargspec > raise TypeError('arg is not a Python function') > TypeError: arg is not a Python function > >>> inspect.getargspec(list.append.__call__) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\inspect.py", line 655, in getargspec > raise TypeError('arg is not a Python function') > TypeError: arg is not a Python function > > Also: > > >>> for elem in dir(list.append): > ... print elem > ... > __call__ > __class__ > __delattr__ > __doc__ > __get__ > __getattribute__ > __hash__ > __init__ > __name__ > __new__ > __objclass__ > __reduce__ > __reduce_ex__ > __repr__ > __setattr__ > __str__ > > gives no clue. > > TIA, with my best regards, > G. Rodrigues You mean something like: >>> list.append.__doc__ 'L.append(object) -- append object to end' >>> list.count.__doc__ 'L.count(value) -> integer -- return number of occurrences of value' -- Martin Franklin From dw-google.com at botanicus.net Sun Dec 14 22:25:29 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 14 Dec 2003 19:25:29 -0800 Subject: connection to samba server References: Message-ID: <99dce321.0312141925.2dc4e47d@posting.google.com> "Przemo Drochomirecki" wrote... > does anyone knows how to connect to samba server (from windows) Hello there. Your question isn't particularly clear, however I can assume you mean something more like "can anyone help me establish a connection to a Samba server from Python under Windows?" In which case, the clearest solution might be to use a suitable Windows API call to map the remote Samba computer's share to a local drive letter, then just access the remote Samba files via that drive letter, eg.: def map_drive(local, remote, username = None, password = None): return win32wnet.WNetAddConnection2( win32netcon.RESOURCETYPE_DISK, local, remote, None, username, password, 0 ) def unmap_drive(...): ... map_drive("Z:", r"\\mum\my_share") # unmap_drive("Z:") Alternatively if your share does not require authentication (ie. you are pre-authenticated to the Samba server, or it has guest shares), you may directly use UNC pathnames to access the share, eg.: # will throw 'invalid argument' if you are not authenticated. os.chdir(r"\\mum\my_share") os.listdir(".") # etc. Alternatively, you could prepend the UNC path to each file you wish to access, although this may be considerably slower: to_process = [ 'input1.txt', 'input2.txt', 'job.ctl' ] unc_path = r'\\mum\my_share' for filename in to_process: pathname = os.path.join(unc_path, filename) processee = open(pathname) ... Hope that helps. To the other respondees, answering in the unhelpful manner that you did makes you no more than trolls. Has it ever crossed your mind that in some parts of the world, the education necessary to communicate in the accepted pythonic anal way, might not be readily available? You may argue that it is better to teach someone how to ask a question correctly, but I would rather see it as being a poor example of your community. It is quite possible (gathering from the way he posted) that this poster has never before talked on a Python user list. How do you think he feels about his first experience with fellow Python programmers, good or bad? Nothing agitates me more on the Internet than people wasting each other's time in this manner. True, the poster wasn't particularly clear, but do you have a right to demand he posts in clear well defined English? The Internet is a global medium, and despite popular assumption, English is not an Internet standard. I have as much right to post in native Belfast slang as you have to post in well written English. Please learn to be accepting of one another, it is so much more helpful than to try to correct something that shouldn't be corrected. The original poster was well meaning, was your reply? If you didn't understand the question then don't reply. Others may well do, and the poster will quickly work out whether or not he is being clear by the number of replies he receives. By doing the usual "person isn't being clear, lets make an example of him" dance, you wasted not only your own time, but his, everyone who reads your pointless thread, and some megabytes of Internet bandwidth to boot. Goodnight, David. From http Fri Dec 12 17:22:39 2003 From: http (Paul Rubin) Date: 12 Dec 2003 14:22:39 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> <3fd8f5bd$0$17127$626a54ce@news.free.fr> Message-ID: <7xk751he1c.fsf@ruckus.brouhaha.com> Mark Roach writes: > but not wxPython. You must use MSVC for compiling on Windows. However, > unless you have patches or extensions to compile, the precompiled version > should work just fine. I've had enough experiences getting stuck in a project due to library bugs or incorrect documentation that I really want to be able to run the complete program (including libraries) under a debugger. That sounds like I need MSVC. However, I guess that's tolerable since this would be a paid project that needs to run on Windows. Sure, using MSVC is distasteful, but so is using Windows in the first place, so if I'm willing to use Windows at all, having to use MSVC as well is just more of the same. Thanks. From miki.tebeka at zoran.com Sun Dec 28 14:59:24 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 28 Dec 2003 11:59:24 -0800 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: <4f0a9fdb.0312281159.38c01835@posting.google.com> Hello Pjer, > If I were to build a Windows application that is a true standard Windows > application in every conceivable way and that adheres to the MS Windows > standards as much as possible (installation, GUI, printing, registry, RTF > etc.), and if portability to other platforms is only a minor concern, ... > would Python be a good choice? > > What packages, libraries and modules would you recommend for GUI, > installation, data storage etc.? The combination I use at work is: Python + wxPython + win32all + py2exe + NSIS Installer. Works like a charm, native looking Windows application in no-time. HTH. Miki From mertz at gnosis.cx Thu Dec 11 14:23:34 2003 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 11 Dec 2003 14:23:34 -0500 Subject: Generator state/parameters References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> <7xisknr9nm.fsf@ruckus.brouhaha.com> Message-ID: <2QM2/kKkXwiQ092yn@gnosis.cx> |Robin Becker writes: |> I was just about to ask if generators allow for a stream like mechanism, |> but obviously if we're not allowed to change the generator state then it |> seems quite hard. Paul Rubin wrote previously: |Well, there's always global state. But the state need not be global, just a mutable object yielded by a generator. As I thought about this fact, I have come to find Raymond Hettinger's proposals for enhancing simple generators less urgent (but I probably still vote +1, though now moot). >>> def echo(): ... message = [None] ... while message[0] != "EXIT": ... yield message ... >>> for mess in echo(): ... if mess[0] is not None: print mess[0] ... mess[0] = raw_input("Word: ") ... Word: foo foo Word: bar bar Word: EXIT This is a toy example, but the point is that we are perfectly able to pass data back into a generator without using global state. -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From ferdy at ferdy.com Fri Dec 26 15:37:49 2003 From: ferdy at ferdy.com (ferdydurke) Date: Fri, 26 Dec 2003 21:37:49 +0100 Subject: Multiple assignment behaves unexpectedly (was: Help ! newbie problem) References: Message-ID: Rene Pijlman wrote: > ferdydurke: >>... a,b,c = b,a+b,c+1 > > b is set to a + b. > > [...] >>... a=b >>... b=a+b > ^ > This a has a different value now, because of the previous statement. > So this sets b to b + b. > thanks a lot for the reply, I gotcha now From mwh at python.net Fri Dec 12 10:32:35 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 12 Dec 2003 15:32:35 GMT Subject: SWT and Python (was: Re: What GUI toolkit looks the best?) References: <20031211190954.GA54939@hishome.net> <05f701c3c026$5eb9c8f0$7401a8c0@voidmk9> Message-ID: Oren Tirosh writes: > SWT has been ported from Java to C# for the SharpDevelop project. I wonder > how difficult it would be to port SWT to Python. Is SWT the framework that was developed for Eclipse? I realise I could look this up myself, but well, that involves NN4 for the moment... Cheers, mwh -- But since your post didn't lay out your assumptions, your goals, or how you view language characteristics as fitting in with either, you're not a *natural* candidate for embracing Design by Contract <0.6 wink>. -- Tim Peters, giving Eiffel adoption advice From anton at vredegoor.doge.nl Sun Dec 28 20:35:30 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 29 Dec 2003 02:35:30 +0100 Subject: [puzzle] Message-ID: <3fef8612$0$117$3a628fcd@reader2.nntp.hccnet.nl> While trying to solve Glen Wheelers problem I discovered an interesting puzzle. I'm going away for a day or so and it would be nice to have it solved when I'm back. It's about a different way to generate the so-called antonian numbers (still trying to find a better name) but now in lexicographically sorted order. I have found a generator for them but as yet I have no way to directly compute "sorted reflected" integers from a normal integer sequence. I hope my code is more clear than my question ... One hint, ISTMT in order to get at a "sorted reflected" integer sequence there has to be a fixed maximum number, while the antonian digits function is infinite. Anyway, it's much too late and I had too much coffee, so maybe it's trivial ... Anton class AntonianSorted: def __init__(self, n, k): self.limits = [k for i in range(n)] self.state = [] self.iterator = self.__gen__() def __iter__(self): return self def next(self): return self.iterator.next() def __gen__(self): state, limits = self.state, self.limits while 1: if len(state) < len(limits): state.append(0) else: i = len(state)-1 while i > 0 and state[i] == limits[i]-1: state.pop() i -= 1 if state[i] < limits[i]-1: state[i] += 1 else: raise StopIteration yield state[:] def antonianvalue(seq, base): return reduce(lambda x,y: x*base+y+1,seq,0)-1 def antoniandigits(val, base): res = [] while val > -1: res.append(val % base) val = val/base-1 res.reverse() return res def product(L): return reduce(lambda x,y: x*y,L,1) def xproduct(n,k): res = 0 for i in range(1,n+1): res += product([k]*i) return res def test(): ndigits, base = 3,3 A = AntonianSorted(ndigits,base) for i,x in enumerate(A): a = antonianvalue(x, base) d = antoniandigits(i, base) print "%2i <==> %2i %9s <==> %9s" %(i,a,x,d) print for i in xrange(xproduct(ndigits,base)): print "%2i <==> ??" %(i) if __name__=='__main__': test() From eric.brunel at N0SP4M.com Fri Dec 19 04:12:39 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Fri, 19 Dec 2003 10:12:39 +0100 Subject: Tkinter / Threads: "Invalid command name" References: <3fe1e985$0$11374$91cee783@newsreader01.highway.telekom.at> Message-ID: Russell E. Owen wrote: > In article <3fe1e985$0$11374$91cee783 at newsreader01.highway.telekom.at>, > Michael Schutte wrote: > > >>...I want to write a server application; like telnet is a client. The user >>should be able to bind() to a port and wait for a client. The written >>and recieved data is stored in a Text widget, self.__text. The >>accept()ing is done in a seperate thread (using the threading module), >>in method self.__tryConnect(). >>But the seperate thread raises an exception at >> self.__text["state"]="normal" . >>A part of the code: > > > You should only deal with Tkinter from the main thread. > > (That was most certainly true in the past. I'm not quite positive that > it is still supposed to be true, but I can assure you that it doesn't > work well on my system.) > > I suggest you use a Lock or Queue or some other inter-thread > communication object to let the accept thread communicate with the rest > of the application. I usually use the event_generate method with custom events on Tkinter widgets from secondary threads to report events to the main thread. This seems to work well on all platforms I've worked with (Linux, Windows, Solaris). The communication via a Lock or Queue is a bit less "natural", since you have to check regularly if a secondary thread tries to tell you something. My ?0.02. HTH. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jepler at unpythonic.net Mon Dec 8 12:31:29 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Dec 2003 11:31:29 -0600 Subject: sorting slovak utf In-Reply-To: <3FD47794.40902@kios.sk> References: <3FD45B2C.1080107@kios.sk> <3FD47794.40902@kios.sk> Message-ID: <20031208173121.GQ11102@unpythonic.net> There are several problems all going on at the same time: First, you have to select a locale that your OS supports. Python can't fix the fact that your installation of Windows doesn't support the sk_SK.utf-8 locale. It may support the sk_SK locale in another encoding, though. You could try this sequence: >>> locale.setlocale(locale.LC_ALL, "sk_SK") 'sk_SK' >>> locale.getlocale() ('sk_SK', 'utf') # my system chooses utf-8 for this locale >>> enc = _[1] # use whatever encoding the system chose # _ is special in interactive prompt, it # holds the value of the last expression # use enc = locale.getlocale()[1] normally now, read the file and encode it into the system's locale: >>> f = open("aaa.txt") >>> l = [line.decode("utf-8").encode(enc) for line in f] >>> f.close() (note that there are pitfalls here if you want to sort utf-8 data according to sk_SK conventions while that data contains unicode characters not expressible in the character set that you used in the first step!) Now, you have to use a locale-sensitive function when you sort your list of strings, because 'l.sort()' without a comparison function will use the same ordering by character value no matter your locale. You have two choices. First, locale.strcoll is suitable for use as the list.sort comparison function: >>> l.sort(locale.strcoll) >>> print "".join(l).decode(enc).encode("utf-8") # prints the locale-aware sorted version of l # assuming your terminal is utf-8 Second, you can instead use the DSU pattern and locale.strxfrm: >>> m = [(locale.strxfrm(line), line) for line in l] >>> m.sort() >>> l[:] = [i[1] for i in m] Jeff From http Tue Dec 30 18:36:51 2003 From: http (Paul Rubin) Date: 30 Dec 2003 15:36:51 -0800 Subject: selecting a random item from a set References: <7xsmj1dgox.fsf@ruckus.brouhaha.com> Message-ID: <7xoetpdgj0.fsf@ruckus.brouhaha.com> Paul Rubin writes: > The classic way to do it goes something like this: > > for n, randomElement in enumerate(s): > if random() < (1.0 / (n+1)): > e = randomElement > # possibly followed by > s.remove(randomElement) Oops, meant to say: for n, e in enumerate(s): if random() < (1.0 / (n+1)): randomElement = e # possibly followed by s.remove(randomElement) From nospam at nopes Mon Dec 15 21:46:39 2003 From: nospam at nopes (Steve) Date: Tue, 16 Dec 2003 13:46:39 +1100 Subject: Sleep()? Message-ID: <3fde71e8$1@clarion.carno.net.au> Hi, Is there some way to implement a timer in python? I want to open a process and pipe a log out of it every 10 minutes. How can I do this? Thanks Steve From Srikanth.Mandava at cosinecom.com Thu Dec 18 21:02:31 2003 From: Srikanth.Mandava at cosinecom.com (Srikanth Mandava) Date: Thu, 18 Dec 2003 18:02:31 -0800 Subject: control-c and threads Message-ID: Hi! When a signal handler is registered in the main thread and "control-c" is entered, the child thread is getting the KeyboardInterrupt exception(The documentation says the main thread MUST receive the signal handler function call if handler is registered). In python 2.2.1 the main thread was always called with the sigint signal handler which was registered. In my case the child thread is waiting on stdin using "raw_input" function. This seems to be causing all sorts of strange behavior in the program once the child thread gets the keyboardinterrupt exception and eventually leading to seg fault on a sys exit . Any idea why this is happening in 2.3.1? This scenario worked in 2.2.1. Is this fixed in 2.3.2?. Thanks Srikanth -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at intarweb.us Mon Dec 22 22:20:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 22 Dec 2003 22:20:53 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: <20031223032053.GA23694@intarweb.us> On Mon, Dec 22, 2003 at 08:07:27PM +0000, Jarek Zgoda wrote: > Steve Lamb pisze: > > >>> A function must return to have a return value. When does sys.exit() > >>> return? > > > >> Something, that is of type NoneType. > > > > He didn't say what, he said when. Can anyone show a program that will > > evaluate the return of sys.exit() and successfully parse it? =D > > sys.exit() doesn't return to caller -- but it doesn't mean it doesn't > return a value. Does this value is discarded? Didn't have time (and > need) to check out. > I hope we can finally put this topic to rest. sys.exit *does not have a return value*: static PyObject * sys_exit(PyObject *self, PyObject *args) { PyObject *exit_code = 0; if (!PyArg_ParseTuple(args, "|O:exit", &exit_code)) return NULL; /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, exit_code); return NULL; } See? "return NULL;" means "this function does not have a return value". If you still do not believe me, please go study the Python/C API until you do. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From alanmk at hotmail.com Mon Dec 1 14:01:47 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 01 Dec 2003 19:01:47 +0000 Subject: help with soap, please (java axis) References: Message-ID: <3FCB901B.42C59923@hotmail.com> [Yurj] > but I receive a: > > SOAPpy.Types.faultType: org.xml.sax.SAXException: No deserializer defined for array type > {http://www.w3.org/1999/XMLSchema}list: I don't have time to answer this in detail, but I do have one suggestion: That error looks like it's coming from Axis (from the "org.xml.sax.SAXException"). Looking through my Axis config file, I see no mention of the namespace you mentioned, namely http://www.w3.org/1999/XMLSchema However, the 2001 schema is listed in the axis config file (webapps/axis/WEB-INF/server-config.wsdd). http://www.w3.org/2001/XMLSchema If I'm right that this is the cause of the error, you have two options to resolve the problem 1. Make SOAPpy generate calls in the 2001/XMLSchema namespace. 2. Configure Axis to have a deserializer for the 1999/XMLSchema namespace. Sorry, don't have time to help with either option right now. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jeder at earthlink.net Mon Dec 22 02:59:49 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Mon, 22 Dec 2003 07:59:49 GMT Subject: Some pygame issues Message-ID: Hello everyone, I recently started up with pygame and after some general playing around in it, I started writing a small pong game within it. It's practically functional; it loads up a 640x480 window, plays some music, allows the user to move his paddle up or down, and has a moving dot. Although, here's the issue I've come to find. I wanted to get the dot simply moving back and forth on the x-axis - once it collides with x position of the right or left paddle, it reverses it's direction. Although, with the current setup, it moves, hit's the right paddle, and simply gets locked at that position. [start code] #First Game Using Pygame (A pong type game) import pygame from pygame import * import whrandom #Classes class resolution: width = 640 height = 480 class color: black = 0,0,0 white = 255,255,255 class leftpadd: x = 10 y = 215 width = 20 height = 50 class rightpadd: x = 610 y = 215 width = 20 height = 50 class dot: x = 317.5 y = 207.5 width = 15 height = 15 #dir = +1 #Global Variables done = 0 #Set the resolution and initialize the window screen = pygame.display.set_mode((resolution.width, resolution.height)) pygame.display.init() #toggle fullscreen #pygame.display.toggle_fullscreen() #Playing Sound #Initialize Mixer, Load the audio file, and then play it pygame.mixer.init() pygame.mixer.music.load('bustamove.mp3') pygame.mixer.music.play(0, 0.0) #Enable keys to repeat pygame.key.set_repeat(1,1) while done == 0: #Quit Sequence remaining_events = pygame.event.get() for event in remaining_events: if event.type == QUIT: done = 1 #Displaying the left paddle and making it move screen.fill(color.black) #Players Paddle (left), Computers paddle (right), and the infamous dot screen.fill(color.white, (leftpadd.x,leftpadd.y,leftpadd.width,leftpadd.height)) screen.fill(color.white, (rightpadd.x,rightpadd.y,rightpadd.width,rightpadd.height)) screen.fill(color.white, (dot.x,dot.y,dot.width,dot.height)) #Paddle Movement for event in remaining_events: if event.type == KEYDOWN: if event.key == K_DOWN: leftpadd.y = leftpadd.y+2 screen.fill(color.white, (leftpadd.x,leftpadd.y,leftpadd.width,leftpadd.height)) elif event.key == K_UP: leftpadd.y = leftpadd.y-2 screen.fill(color.white, (leftpadd.x,leftpadd.y,leftpadd.width,leftpadd.height)) #Collision detection if leftpadd.y > 430: leftpadd.y = 430 if rightpadd.y > 430: rightpadd.y = 430 if leftpadd.y < 0: leftpadd.y = 0 if rightpadd.y < 0: rightpadd.y = 0 #Dot Motion dot.x = dot.x+1 #Dot collision HAVING ISSUES HERE! if dot.x + dot.width > rightpadd.x: dot.x = dot.x-1 if dot.x + dot.width < leftpadd.x: dot.x = dot.x+1 #Refresh the screen and pump the event qeue. pygame.display.flip() pygame.event.pump() Any suggestions on how to get the dot to reverse it's direction? I think I understand what's causing it, but I'm loss as to how to correct it. Thank you, ~Ryan From vze4rx4y at verizon.net Sun Dec 7 00:22:34 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 07 Dec 2003 05:22:34 GMT Subject: Fuzzy Logic References: <3FD26452.90906@di.uoa.gr> Message-ID: "Christos KK Loverdos" wrote in message news:3FD26452.90906 at di.uoa.gr... > Hi all! > > Is there any fuzzy logic package? 70% Yes -- see http://www.biostat.wisc.edu/~annis/creations/PyLisp/ 20% Sorta Yes -- see http://starship.python.net/crew/seehof/NeuralPython.html 10% No real code but there are toy examples Raymond Hettinger From francisgavila at yahoo.com Wed Dec 24 23:45:02 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 24 Dec 2003 23:45:02 -0500 Subject: arguments problem~ References: Message-ID: black wrote in message ... class B(A): def __init__(self, *args, **kw): A.__init__(self, args, kw) Should be A.__init__(self, *args, **kw). To illustrate: >>> def f(*args, **kwargs): ... return [args, kwargs] ... >>> f(1, 2, b=3) [(1, 2), {'b': 3}] >>> a = f(1, 2, b=3) >>> f(a) [([(1, 2), {'b': 3}],), {}] >>> f(*a) #Your error [((1, 2), {'b': 3}), {}] >>> f(*a[0], **a[1]) [(1, 2), {'b': 3}] In a calling context, * and ** do the opposite of what they do in a function definition context: they unpack tuple/lists and dicts into distinct arguments and keyword arguments. By not calling A.__init__ with unpacked arguments, you literally passed a tuple and a dict, and in the function these got grouped together in args. It's in the docs somewhere, I swear. :) -- Francis Avila From yurj at alfa.it Mon Dec 1 13:35:09 2003 From: yurj at alfa.it (Yurj) Date: Mon, 1 Dec 2003 17:35:09 -0100 Subject: help with soap, please (java axis) Message-ID: <200312011635.hB1GZ9XY025030@alfa.it> Hi all! I've to produce this xml as a soap request (I'm using SOAPpy): titolo titolo_ws tipoIid tipoIid_ws autore autore_ws iid iid_ws *links* dataProvider ps_ws1 url url_ws1 diritti diritti_ws1 dataProvider ps_ws0 url url_ws0 diritti diritti_ws0 I can the first part (without *links*) with: import SOAPpy server = SOAPpy.SOAPProxy("http://myserver.com/service") a=[{'key':'titolo','value':'I Promessi Sposi'},{'key':'tipoIid','value':'isbn' {'key':'autore','value':'Alessandro Manzoni'},{'key':'iid','value':'566669'}] a1=SOAPpy.structType() a1._addItem('id0',a) print server.request(a1) ======== this works. The server is Java Axis. But, when I try the *links* part, I've failed. Can someone explain me how to create a python object that can used by SOAPpy to send the full request? I've tried with: links=[{'key':'dataProvider','value':'DATA PROVIDER'},{'key':'url','value':'ht ://dafnedb.cab.unipd.it/repository/123458'},{'key':'diritti','value':'stringa n i diritti'}] link1=SOAPpy.arrayType() link1=[links] a=[{'key':'titolo','value':'I Promessi Sposi'},{'key':'tipoIid','value':'is {'key':'autore','value':'Alessandro Manzoni'},{'key':'iid','value':'566669' ey':'*links*','value':link1}] but I receive a: SOAPpy.Types.faultType: Help! :) P.S. I'm not subscrive, please CC me... thanks! ________________________________________________ Message sent using ALFANET Caorle WEBMAIL 1.0 From jcb at iteris.com Thu Dec 4 01:48:28 2003 From: jcb at iteris.com (MetalOne) Date: 3 Dec 2003 22:48:28 -0800 Subject: python's threading has no "interrupt"? References: Message-ID: <92c59a2c.0312032248.535feebd@posting.google.com> You might be able to solve your problem a couple of ways. A sample scenario might be than you are using a condition variable and are blocked in cv.wait(). The user selects "exit" from a menu and you would like to interrupt the cv.wait() so that the program may exit. while not cond(): cv.wait() processData() These lines of code require another thread to modify the condition and call cv.notifyAll() The cond() function could be modified def cond(): return origCond() and exitSelected Alternatively a semaphore could be used. s = Semaphore(2) on startup s.acquire() #This one will be released upon selecting "exit". later on s.acquire() #This consumes a slot and continues or waits for an available slot. processData() on "exit" calling s.release() will wake up the above code. Finally, since both of these ideas may be a bit of a headache you might find setting Thread.setDaemon(True) to be useful. This allows your program to terminate when the main thread terminates even if other threads are running. From fperez528 at yahoo.com Tue Dec 16 14:57:16 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 16 Dec 2003 12:57:16 -0700 Subject: compiling python-bibtex References: Message-ID: Alex Olivas wrote: > i'm not sure whether this is the correct list for this question, but i'm > trying to > build python-bibtex-1.1.93.1 with gcc 3.3.2 and am getting the following > error messages... Hey Al, post over on the pybliographic list. I'm almost 100% sure they already have Fedora packages available of everything (search the archives over the last 3 weeks). f From jjl at pobox.com Thu Dec 4 18:55:02 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Dec 2003 23:55:02 +0000 Subject: stddev bug in util.py References: Message-ID: <874qwgdtpl.fsf@pobox.com> "Ted Nienstedt" writes: [...] > Sorry to bother. I had wished that I had realized this bug existed > earlier and thought others might appreciate learning of it as well. [...] I'm sure you posted with the best intentions, so thanks for the thought! Though it does indeed look like a strange and possibly quite unpleasant bug for the users of the particular software you're using, it's of no interest at all to most Python users, who have never heard of that software, so it's not appropriate for c.l.py. You want either the authors' email addresses, a mailing list specific to the library you're using, a bug tracker (database of bugs, almost always accessed via the web), or some combination of the above. John From martin at v.loewis.de Tue Dec 16 14:25:41 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Dec 2003 20:25:41 +0100 Subject: build on AIX without Tk References: Message-ID: "Tennill, Dustin" writes: > Is there any way to build without including tkinter support? (Or am I > just doing something wrong????) You should disable compilation of _tkinter in setup.py, by putting a return statement into detect_tkinter. Regards, Martin From jacek.generowicz at cern.ch Fri Dec 12 04:04:28 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Dec 2003 10:04:28 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Peter Otten <__peter__ at web.de> writes: > See below for my ideas towards a generalized memoizing framework. [I haven't the time to have a look at it in any detail right now, so forgive me for not responding/commenting in full, just yet.] > > def foo(some_type): > > ... > > return something > > > > > > foo = memoize(foo) > > > > data = [int, float, my_class, his_class, str, other_class] * 10**6 > > > > map(foo, data) [+] > > Do you discard the result for real? No, sorry, of course not. > > [+] Can you see why I don't want to mess with the call site ? > > No. It would mean taking it out of the map and that would mean losing the C-coded loop that map provides. > Now to my code. The idea is to make memoized functions available to > different modules from a central registry, and to expose the cached results > for hand-optimized hotspots. Otherwise it was all mentioned in this thread, > if not the original post. I'll make sure to find the time to study this. From fumanchu at amor.org Thu Dec 18 18:50:38 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 18 Dec 2003 15:50:38 -0800 Subject: re troubles Message-ID: If 'kittens' is ALWAYS in the first column, then there will never be a / between it and its containing tr start tag. Then you could use: m = re.compile(r"[^/]*kittens.*?", re.DOTALL) m.sub("", data) Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: Evanda Remington [mailto:evanda at remingtons.org] > Sent: Thursday, December 18, 2003 3:23 PM > To: python-list at python.org > Subject: re troubles > > > I'm trying to filter some rows of an html table out, based on their > contents. For input like: > """ > > > > << want to filter > << this out. > << > >
    Lasers17
    kittens8
    robots8
    > """ > I would like to completely remove the (3 line) table row that > makes mention > of kittens. The regexp I have tried to use is: > r".*?kittens.*?". > When compiled and used with subs("",data), strangely removes > everything > from the first "" to the first "" after kittens. > > That is, the ".*?" notation works in the second half, but not > in the first > half. It behaves the same as ".*" should. > > Any advice? > > -e > > -- > Evanda Remington > evanda at wreck.org > > -- > http://mail.python.org/mailman/listinfo/python-list > From jjl at pobox.com Mon Dec 29 18:48:07 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Dec 2003 23:48:07 +0000 Subject: argument list References: Message-ID: <87llovi3t4.fsf@pobox.com> Forgot to add: I'd probably just use (C API equivalent of) try: ... except TypeError: rather than using inspect. John From jzgoda at gazeta.usun.pl Wed Dec 10 15:53:34 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 10 Dec 2003 20:53:34 +0000 (UTC) Subject: ANN: Twisted 1.1.1 References: Message-ID: Cameron Laird pisze: >>Writing one more asyncore/asynchat application pisses me off. Hate it. >>Love it. Thanks God, it's Python, not Rexx, even not Java. > . > Think about that last just a bit more. Asyncore is SUCH an > upgrade over what most of the world is doing. Yes, you are right, most of world still uses synchronous sockets. AFAIK, asynchronous sockets are widely used in ObjectPascal (by way of F. Piette's work), but I don't know any such complete (like these in Python and ObjectPascal) implementation in other Popular Programming Environments (Java is PPE, Rexx is my *local* PPE ;)) -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From fredrik at pythonware.com Mon Dec 8 09:04:39 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 15:04:39 +0100 Subject: Problem installing gadfly on Mandrake 9.2 References: <8a27e309.0312080551.331fb053@posting.google.com> Message-ID: > make sure you've installed the python-devel package. which might be named "libpython2.3-devel" under mandrake, if I interpret my sources correctly... From bsneddonNOspam at yahoo.com Wed Dec 24 11:46:13 2003 From: bsneddonNOspam at yahoo.com (Bill Sneddon) Date: Wed, 24 Dec 2003 11:46:13 -0500 Subject: Simple or Impossible in Python... dynamically dereferencing a class attribute Message-ID: Given the following simple code. I was trying find a way to dynamically de-reference a class attribute. Problem explained below. class test: def __init__(self): self.a = 0 self.b = 0 self.c = 0 myDict = {} myDict['one'] = test() myDict['two'] = test() # I know I can do this at runtime. myVar = 7 myDict['one'].a = myVar myLetter = 'b' ## Is there any way to choose the attribute of test based on a varible. ## like this? myDict['one'].{myLetter} = 9 I know you can do this kind of thing with other languages Perl, C++ Is it possible with Python? If so what is the syntax in Python. Maybe there is a better/equivalent approach if so could you point me to an example? From boydrobh at yahoo.com Wed Dec 31 14:46:25 2003 From: boydrobh at yahoo.com (Rob Boyd) Date: Wed, 31 Dec 2003 11:46:25 -0800 (PST) Subject: Test if IDLE is a mature program In-Reply-To: Message-ID: <20031231194625.1607.qmail@web42003.mail.yahoo.com> --- Aubrey Hutchison wrote: > Why do I need to tinker with it? > > You don't need to tinker with mature programs. > > > -- > http://mail.python.org/mailman/listinfo/python-list I have _never_ had to tinker with IDLE in order to use it. Please read the Python tutorial, 6.1.1, the Module Search Path, before making uninformed assertions. Your experience has nothing to do with IDLE or really even Python. You wouldn't get far in C development if you wrote a garbage file named stdio.h and saved it within the library search path. __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From arjen.dijkstra%no%-%spam% at hccnet.nl Fri Dec 19 14:22:23 2003 From: arjen.dijkstra%no%-%spam% at hccnet.nl (duikboot) Date: Fri, 19 Dec 2003 20:22:23 +0100 Subject: linux wine py2exe ?? Message-ID: Hi all, I've tried to create a .exe file on linux (Fedora). So in installed wine, python2.3 with wine and py2exe (with wine ofcourse) I made a setup file (setup.py) and ran >wine python.exe setup.py py2exe Does anybody know what I've done wrong? Or is it just not possible Greetings, Arjen output: arjen at linux Python23]$ wine python.exe setup.py py2exe fixme:console:SetConsoleCtrlHandler (0x7800f03e,1) - no error checking or testing yet running py2exe running build running build_scripts running install_scripts fixme:imagehlp:BindImageEx (7, "C:\\Python23\\DLLs\\_sre.pyd", "C:\\Python23\\DLLs;C:\\Python23;C:\\WINDOWS\\SYSTEM;C:\\WINDOWS;c:\\windows;c:\\windows\\"..., (null), 0x10001570): stub Traceback (most recent call last): File "setup.py", line 6, in ? scripts=["vervang.py"], File "C:\Python23\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Python23\lib\distutils\dist.py", line 907, in run_commands self.run_command(cmd) File "C:\Python23\lib\distutils\dist.py", line 927, in run_command cmd_obj.run() File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 698, in run extra_path + sys.path) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 842, in find_dependend_dlls alldlls, warnings = bin_depends(loadpath, images) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 1154, in bin_depends for result in py2exe_util.depends(image, loadpath).items(): py2exe_util.bind_error: C:\Python23\DLLs\_sre.pyd #### from distutils.core import setup import py2exe setup(name="vervang", scripts=["vervang.py"], ) ##### From piir at earthlink.net Mon Dec 8 04:36:20 2003 From: piir at earthlink.net (Todd Gardner) Date: 8 Dec 2003 01:36:20 -0800 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> Message-ID: <9b849915.0312080136.867babc@posting.google.com> Chris Liechti wrote in message news:... > Gandalf wrote in > news:mailman.100.1070529056.16879.python-list at python.org: > > > Use PySerial > > > > http://pyserial.sourceforge.net/ > > thanks for recomending it :-) as a little clarification: > the link to pyparallel is here: > http://pyserial.sourceforge.net/pyparallel.html > > (its only a small note on the mainpage) > > currently i have only py2.2 versions available for download, but i can > easily build the 2.3 version upon request, I would like to request that you build a 2.3 version. > or you can build it on your own with mingw32 or cygwin installed: python > setup.py build --compiler=mingw32 > install I am quite the newbie so I would not even attempt to build it on my own yet, soon maybe but... > > you will need giveio.sys, also available in the downloads section, that > allows programs to access the io ports on Win NT/2k/XP > > chris Thanks, Todd From hwlgw at hotmail.com Mon Dec 29 04:09:18 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 29 Dec 2003 01:09:18 -0800 Subject: ANN: Python Language Reference References: Message-ID: > [Aahz] > That's why you should use Lynx. Then you don't have any options. ;-) But isn't Lynx text-only? I want to see the pics! Even though I am not the kind of pervert that want to do things to them with the mouse. From blibjunk at hotmail.com Mon Dec 1 16:54:09 2003 From: blibjunk at hotmail.com (Krister Liljedahl) Date: 1 Dec 2003 13:54:09 -0800 Subject: FD_SETSIZE not working in 2.3.2? Message-ID: Hi, I'm getting an "10055, An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full" error message when opening 64 or more sockets in a single thread when using Python 2.3.2 under Windows XP. I think this is because Python fails to increase the value of FD_SETSIZE before it invokes winsock.h. If I'm reading the Python source right then winsock.h is invoked by errnomodule.c before selectmodule.c increases the value of FD_SETSIZE to 512 from the default 64, which would explain my problems. Does anyone else experience problem with large numbers (>63) of sockets under Windows? Can anyone else succesfully open 64 or more sockets under Windows and poll them using select? Anyone got any other explanations/thoughs/ideas? /Krister From yan at NsOeSiPnAeMr.com Thu Dec 18 07:16:44 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Thu, 18 Dec 2003 07:16:44 -0500 Subject: Logging Message-ID: Does anyone have a working example or a recipe of a simple logging system using the logging module? Any FM I can refer to? I can't seem to get it right - I can't even make sense of the standard library docs. What do I have to do to log records to a file? (Newbie Q, as you might guess...) -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From aahz at pythoncraft.com Sat Dec 27 12:47:17 2003 From: aahz at pythoncraft.com (Aahz) Date: 27 Dec 2003 12:47:17 -0500 Subject: ANN: Python Language Reference References: Message-ID: In article , Will Stuyvesant wrote: > [Troels Therkelsen] >> ...To me, >> it would be preferrable to be able to find the module I want in, say, 3-4 >> clicks, rather than pressing several keys on the keyboard.... > >For me it would be preferrable to use only a few keystrokes instead of >having to find the mouse! That's why you should use Lynx. Then you don't have any options. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From andymac at bullseye.apana.org.au Sat Dec 27 17:11:34 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 28 Dec 2003 09:11:34 +1100 (EST) Subject: 2.3 list reverse() bug? In-Reply-To: References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: <20031228091057.V12838@bullseye.apana.org.au> On Fri, 26 Dec 2003, Alex Martelli wrote: > list(x) is my favourite way to make a shallow copy of list x, but x[:] > and copy.copy(x) are essentially equivalent. Behaviourally yes, performance wise no. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bkelley at wi.mit.edu Thu Dec 11 13:38:25 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 11 Dec 2003 13:38:25 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: <3fd8b949$0$577$b45e6eb0@senator-bedfellow.mit.edu> Cameron Laird wrote: > I want to say a few words about portability and comparisons. > > I'm very reluctant to advise "see what you like the best" in regard to > GUI toolkits > > the way I do for high-level languages. We all know it's entirely > realistic to counsel a newcomer, "Give yourself an hour, and you can > download and install Python (or Perl, or Ruby, or ...) and try it out > for yourself. You'll get a good first impression of how the language > operates." That's not quite what I meant. The first step (for me) is finding out what the toolkit supports. For example, tcl/Tk doesn't have a good grid widget out of the box so for my project it was a non-starter which left Qt, wxPython and GTK+ > isn't the URL I recommend; Scriptics > stopped doing business under that name three and a half years ago. http://wiki.tcl.tk/tk > is a safe choice. I would recommend http://www.tcl.tk/ actually which points to the same place as http://www.scriptics.com/ Brian From bokr at oz.net Sun Dec 21 19:20:11 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Dec 2003 00:20:11 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On Sun, 21 Dec 2003 17:37:10 -0500, "John Roth" wrote: [...] > >> >It's a non-starter for Python, though. > >> Seems so. OTTOMH I guess you could have the tokenizer generate two kinds >of names, >> names_as_now, and bare_names (tagged so with lookahead determining no >trailers). >> Then you could dynamically check if a bare_name was referring to a >callable, and >> call it with no params if so, and for all other name usage do as now. >Except that as >> you point out, you'd need a way to inhibit the effect. But since this >thing would be >> unusual (and would cause major breakage), maybe it could be enabled only >for references >> to objects with an __autocall__ alias to their __call__ attribute. And >then, since the >> auto-call would only happen for bare names, you could pass it as a >function by using >> name.__call__ instead of name. Or use vars()['name']. > >I think that's getting a bit baroque. In fact, after my previous post, >I realized that I had an unnecessary complexity: it's simpler to just >auto-execute "all" functions, and let the ones that require parameters >and don't have them fail like they do today, rather than try to make >a distinction. I sounds like you are suggesting the effect of adding () to every epression not already ending in (). I don't think you can tell what a name is referring to until you look it up. Any LOAD_NAME or LOAD_FAST etc. can put a function reference on the stack (so could the evaluation of any kind of expression!). It would be unacceptable overhead to test for function magic every time you got something onto the stack. AFAIK the only thing that now tells the compiler to generate code to call the unknown thing that has wound up on the stack is encountering a (...) trailer, empty or not. (Property magic is a little different). My bare_name distinction limits testing of the stacked item to expressions ending in plain names, but that's still terrible overhead, unless you generate different code for when a static analysis can show that the name refers to a function. Then you could add an implicit () trailer effect for auto-execution. If you could also require statically determining that it was an "auto-excecute" function, it could pretty much eliminate run-time overhead, IWT. BTW, I said tokenizer before, but that's not the place to look ahead for a trailer. Parser/compiler better. > >It puts the VM through quite a few less hoops: all that really has to >be done is duplicate the various opcodes that can fetch a function >object, so that one of each pair autoexecutes and the other doesn't. See above. Any expression can potentially "fetch a function". ISTM the only kind that you were originally concerned with was ones ending in bare names. >Then the parser can decide which to generate based on whether there >is a parameter list following, and also on whether the "magic" syntax for >retreiving the function object without auto-executing it is present. (quote func) ? ;-) > >I suspect it's also easier to explain: funtions and methods are what >are declared with def and lambda, and if it's not that, then it's not >going to autoexecute regardless of whether it has a __call__ method. >Adding classes to the list might be useful as well, but anything more >would lead, I suspect, to too much confusion. > >It's still a non-starter, though Well, maybe all this is useful in driving home that point ;-) Regards, Bengt Richter From arigo at tunes.org Sat Dec 20 03:43:57 2003 From: arigo at tunes.org (Armin Rigo) Date: Sat, 20 Dec 2003 08:43:57 +0000 Subject: [pypy-dev] Last chance! (was: Does anybody really use frame->f_tstate ?) In-Reply-To: <3FE2C5B5.8080208@tismer.com> References: <3FDE6D35.3090100@tismer.com> <3FE2C5B5.8080208@tismer.com> Message-ID: <20031220084357.GA25998@vicky.ecs.soton.ac.uk> Hello Christian, On Fri, Dec 19, 2003 at 10:32:37AM +0100, Christian Tismer wrote: > since I didn't get *any* reply to this request, > either the request was bad or there is really > nobody using f_tstate in a way that makes it > urgent to keep. Sorry for the delay, we were kind of busy this week here... There are references to f_tstate in Psyco but nothing critical. Using PyThreadState_GET() instead should be fine. A bientot, Armin. From fredrik at pythonware.com Wed Dec 10 07:36:39 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Dec 2003 13:36:39 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: Spiffy wrote: > > that indicates that it's supposed to work, don't you think? > > IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? sure. if multiple independent sources say the same thing, your first thought should be that they're all wrong. > > > Both the .exe and the .mid file are in the python path and the spelling > > > been checked. > > > > you mean sys.path? > > IF I HAD MEANT sys.path, I WOULD HAVE SAID sys.path, DON'T YOU THINK? the python path is stored in the sys.path variable. why did you say python path if you didn't mean it? > I DO NOT THINK THE PROBLEM IS IN HOW I USED THE FUNCTION > NOR WHAT I EXPECTED FROM IT. no, your problems are obviously elsewhere. good luck with your programming career. From gumuz at looze.net Thu Dec 18 04:59:23 2003 From: gumuz at looze.net (Guyon Morée) Date: Thu, 18 Dec 2003 10:59:23 +0100 Subject: Coffee script :) Message-ID: <3fe17a79$0$246$4d4ebb8e@news.nl.uu.net> I just wrote this to decide who's going to get the next round of coffee here in the office. Who knows it might be usefull to other people who also have endless discussions on who is gonna get the coffee :) cheers, Guyon coffee.py ------------------------------------------------------------------------- # who's gonna get coffee? (tm) # # Guyon Moree 2003 import random candidates = [ 'employee1','employee2','employee3','employee4' ] print "%s is the chosen one!" % (random.choice(candidates)) From tjreedy at udel.edu Sat Dec 27 16:48:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Dec 2003 16:48:10 -0500 Subject: callable classes References: Message-ID: <_bydnV23friKY3CiRVn-gQ@comcast.com> "Duncan Smith" wrote in message news:bskkig$sf6$1 at news7.svr.pol.co.uk... > > What do you mean by 'callable class'? Classes are callables. Ot you mean > > a class that defines __call__ method? In this case it's really useful. > > > > regards, > > anton. > > Yes, I meant a class that defines a __call__ method. Cheers. Which makes the *instances* callable, so you meant 'class with callable instances'. TJR From __peter__ at web.de Fri Dec 12 07:57:22 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Dec 2003 13:57:22 +0100 Subject: Function application optimization. References: Message-ID: Jacek Generowicz wrote: > Given > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > > How should one spell > > results = map(lambda f,a: f(a), fncs, args) > > in order to get the result most quickly ? > If you can afford to destroy the args list, a tiny speed gain might be in for you (not verified): for index, func in enumerate(fncs): args[index] = func[index] Peter From abelikov72 at hotmail.com Thu Dec 4 12:43:21 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Thu, 04 Dec 2003 17:43:21 GMT Subject: ISO to Gregorian, strptime madness References: <3FCF562A.23E44C27@engcorp.com> Message-ID: On Thu, 04 Dec 2003 10:43:38 -0500, Peter Hansen wrote: >Afanasiy wrote: >> >> While I'm posting, how about this old dilemma... from the 2.3 modules. >> strptime exists in time, but not in datetime, while strftime exists in >> both. > >Uh, really? > >Looks to me like strptime and strftime are both in time and not in datetime. Yeah I didn't remember the specifics, but it's something like that. Something that I needed to have strptime does not have it, but has strftime. I am a sorry for that mistake now, because of your reply. This is not the primary concern of the post, and not even secondary, so please ignore the silly mistake and help with the other things. From max at cNvOiSsiPoAnMtech.com Wed Dec 17 17:40:52 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Wed, 17 Dec 2003 22:40:52 GMT Subject: is file open? Message-ID: I have a script that processes a file generated by another program. I need an unumbiguous way to know that the file has been written and closed by the other program, at least on Windoze. I am thinking of doing def CanOpen(fname): try: f = open(fname, 'a') f.close() return True except IOError: return False should this work OK? thanks, max From Samwatson at yahoo.com Mon Dec 8 18:52:52 2003 From: Samwatson at yahoo.com (Sam Watson) Date: Mon, 08 Dec 2003 18:52:52 -0500 Subject: Building a new app in python and need some architecture advice. Message-ID: Hi, I could use a little help with a project i'm going to build. I know I want to use python and wxWindows but thats about all I know. The client will be linux or windows. The server will be linux. Basically, its a client/server app with a rich GUI client. The big catch is I want to be able to run the client/server remotely across the web in a secure fashion. I sort of want to stay away from a web server based solutions because they seem to be attacked the most and frankly im not dealing with rocket scientists on the other end. They certainly arent up to the task of keeping a web server locked down. Honeslty, i'm not sure I even am. I'm a big fan of security through obscurity. I need something basically plug and play for them as a server. Im looking to walk in to their office with a box running linux, turn it on, plug it into a cat5 cable and never let them touch it. They will only access it from the GUI client. I will be running SSH for my admin purposes on the box. I'm comfortable with securing that. With that in mind, what would you suggest I use as a remoting/middleware or transport that will be secure across the web and offers some type of authentication? My first instinct is to use pickle and sockets but i figure there ought to be a better way. This is the list of candidates ive come up with so far XML-RPC (Seems like kind of a waste considering the client and server are both python) Pyro (Can i secure this?) Twisted (Is this overkill?) Pure sockets (a lot of infrastructure to write but im pretty experienced with it) Should I use postgres as a back end or take a chance on some kind of Object persistence mechanism? It has to be rock solid. Lots of questions.... I'm a C++/Windows guys trying to break out of purgatory :) Thanks a lot! From claird at lairds.com Thu Dec 11 11:29:21 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 16:29:21 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xekvb1koc.fsf@ruckus.brouhaha.com> <7x65gn1jk5.fsf@ruckus.brouhaha.com> Message-ID: In article <7x65gn1jk5.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >lot better than the "before" shot. I guess I'll look at it more >carefully, but Tkinter has always made me cringe because of its use of >tcl (why does it need its own extension language if Python itself is >supposed to be such a good one)? Thanks. Division of labor. Python is not petty or exclusive; Python welcomes all things beneficial. -- Cameron Laird Business: http://www.Phaseit.net From duncan at NOSPAMrcp.co.uk Mon Dec 1 04:22:29 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 1 Dec 2003 09:22:29 +0000 (UTC) Subject: Bug in glob.glob for files w/o extentions in Windows References: Message-ID: "Tim Peters" wrote in news:mailman.1194.1070165783.702.python-list at python.org: > ? Nope. It's dir that special-cases the snot out of a period, not > Python's glob. On that basis Python also 'special-cases the snot out of a period': try win32api.FindFiles('*.') to get the same behaviour as dir. More accurate would be to say that the operating system has consistent but weird behaviour, since it is below the application level that trailing dots are stripped from filenames and ignored from file patterns. The only way to avoid it on Windows is to retrieve all the filenames and then perform your own pattern matching on them. glob.glob is bypassing the operating system's filename matching to provide behaviour which is consistent across different operating systems, but inevitably this means that it doesn't match some platform's standard behaviour. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gagenellina at softlab.com.ar Fri Dec 26 20:17:51 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2003 22:17:51 -0300 Subject: indendation error In-Reply-To: <20031226061543.GA24283@mrna.tn.nic.in> Message-ID: <5.2.1.1.0.20031226221242.01fc7140@192.168.0.115> At 26/12/2003 11:45, you wrote: After you correct your indentation error, there is another issue: > def __str__(self): > print '(' + str(self.x) + str(self.y) + ')' This should *return* a string, not print it. Try: return '(%s,%s)' % (self.x, self.y) Gabriel Genellina Softlab SRL From genericax at hotmail.com Mon Dec 22 16:17:24 2003 From: genericax at hotmail.com (Sara) Date: 22 Dec 2003 13:17:24 -0800 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <3fe4bd0e.68951468@news.erols.com> Message-ID: <776e0325.0312221317.6f7378f5@posting.google.com> tiltonj at erols.com (Jay Tilton) wrote in message news:<3fe4bd0e.68951468 at news.erols.com>... > xah at xahlee.org (Xah Lee) wrote: > > : i have a bunch of java files that has spaced-out formatting that i > : want to get rid of. I want to replace two end of line characters by > : one end of line characters. The files in question is unix, and i'm > : also working under unix, so i did: > : > : perl -pi'*~' -e "s@\n\n@\n at g" *.java > : > : but this to no avail. > > Of course it's not. > > Perl's -p switch processes one line at a time. A line cannot have more > than one newline character. > > Perl's "paragraph" reading might be useful to you, where any number of > consecutive newline characters mark the end of a record. See "$/" in > perlvar for details. > > perl -i'*~' -lpe "BEGIN{$/=''}" *.java > > : after many minutes of checking and rechecking and lots of trial and > : error with frustration, i realized that the fucking perl to my > : expectations again cannot do this simple fucking thing. > > Complete nonsense. Don't blame your own incompetence on Perl. > > : Fucking stupid perl > : documentation and Larry Wall moron who is i believe incapable of > : writing clearly and logically in English masquerading as humor. > > If you feel you can explaint it more clearly, quit bellyaching about it and > submit a documentation patch. > > Preferrably one that is less petulant and profane than your article. > Frustration is no excuse for incivility. is incivility a word? Curious. Anyhow, if I understand this you want to replace two \n's with one? How about this (untested) code: die "Perl is ever so much smarter than Java\n" unless open F, 'myfile'; my @f = close F; $f = join '', at f; $f =~ s/(\n)\n/$1/gs; die "Hmm this file cant be opened for writing\n" unless open F, '>myfile'; print F $f; close F; print "Perl does it again!\n\n"; From newsgroups at jhrothjr.com Sun Dec 7 19:06:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 7 Dec 2003 19:06:09 -0500 Subject: entering the lists against CamelCase References: Message-ID: "John Benson" wrote in message news:mailman.207.1070837466.16879.python-list at python.org... > I never cared for CamelCase because a lot of words in English are compounds, > and remembering the right CamelCase rendition of them gets difficult. [snip] Well, having worked in monocased languages, I find that the biggest problem with them is the inability to tell where word breaks are without a clue. Capitalization is one such clue, underscores are another. The hyphens you find all over COBOL programs are a third. All of these suffer from the ambiguity problem you mention. The best solution I know of for the ambiguity problem is to create a lexicon for a system rather than simply creating names as they swim up from the depths of the creative unconcious. John Roth > > > From jzgoda at gazeta.usun.pl Fri Dec 19 16:08:08 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Dec 2003 21:08:08 +0000 (UTC) Subject: Which HTMLParser? References: Message-ID: Tuang pisze: > Which one is the best choice for parsing arbitrary real-life Web > pages? I get the feeling that maybe the HTMLParser module is the more > recent, more practical utility, while the htmllib version is the older > one, retained for backward compatibility, but I'm not sure. The docs > don't exactly say that. > > Any recommendations or clarifications of what's going on would be > helpful. If you are not sure that your source is valid HTML, use SGML parser instead. Personally I recommend F. Lundh's sgmlop -- fast, robust and well-written piece of software, real Meisterstueck. Works perfectly on Unix, Windows and IBM iSeries (formerly AS/400). -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From jeder at earthlink.net Mon Dec 22 03:01:09 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Mon, 22 Dec 2003 08:01:09 GMT Subject: Some pygame issues References: Message-ID: Pardon me for extensive post, by the way. ~Ryan From bokr at oz.net Tue Dec 23 07:57:47 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Dec 2003 12:57:47 GMT Subject: Counting how many chars equal to a given char are in the beginning of a string References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: On 22 Dec 2003 12:04:21 -0800, andreif at mail.dntis.ro (Stormbringer) wrote: >Hi, > >Given a string s and a char c, is there a short & elegant way to >determine how many consecutive occurences of c are in the beginning of >s ? > >For example if s = ">>>>message1" and c = ">" then the number I am >looking for is 4 (the string begins with 4 '>'). > Not tested beyond this example ;-) >>> def countleading(c, s): return len(s)-len(s.lstrip(c)) ... >>> s = ">>>>message1" >>> countleading('>', s) 4 Regards, Bengt Richter From http Thu Dec 11 10:01:54 2003 From: http (Paul Rubin) Date: 11 Dec 2003 07:01:54 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xad5z1jq5.fsf@ruckus.brouhaha.com> Brian Kelley writes: > Why forget Tkinter? I've seen Tkinter applications that look > incredibly fabulous. Got any url's for screen shots? > A lot depends on what you are trying to do. If > you are making a graphics-heavy application then Tkinter's canvas is > pretty sweet. I also think IDLE looks pretty good. There will be some graphical icons and stuff like that which people will click on, but no really heavy graphics or drawing tools in the sense of a photo editor or anything like that. > Glade isn't a GUI, it is a GUI builder that uses GTK. In my > experience, GTK doesn't look quite right on windows boxes, especially > the menus. Of course I have the same basic view of Qt and Swing so > know you know my biases. Oh ok, I understand a bit better now. > I tend to use Tkinter for canvas heavy applications and wxPython for > other stuff. Is wxPython Windows specific? I guess it is, but can I port the screen layouts to some comparable Linux toolkit or anything like that? The screen shots for it do look really nice. > Here is my humble opinions in a nutshell (missing a lot here): > wxPython has a grid control to die for and many, many classes, good > printer support and looks like a native GTK app on Linux and a native > app on windows and macintosh. Oh wow, yes I guess it's cross platform then. Hmm, what Micro$oft tool do I need to build and run it? Is Visual C++ enough? I guess I can get the client to pay for some stuff like that. Also, is there a Glade-like drag and drop gui editor for it? > Qt is better for developing - it has a better class structure and I > tend not to have to look up docs as often and can look really, > really nice. The KDE apps that I've seen look good but not really top notch. Maybe more attention could improve them. They're certainly good enough for practical use. > Tkinter has a killer canvas and great postscript output. GTK is > really quite fast. I think I don't care about heavy duty graphics or more than rudimentary printing. > but don't take my word for this, why don't you see what you like the best? > > http://www.wxpython.org/ > http://www.gtk.org/ > http://www.scriptics.com/ > http://www.trolltech.com/ I don't know what I can really tell from these without more experience with them. In particular, which is the most solid and reliable across a wide range of Windows versions (95, 98, ..., XP whatever)? That matters too. Thanks! Paul From baas at ira.uka.de Sat Dec 20 07:12:08 2003 From: baas at ira.uka.de (Matthias Baas) Date: Sat, 20 Dec 2003 13:12:08 +0100 Subject: udp broadcast example, please References: Message-ID: On Wed, 17 Dec 2003 13:22:25 +0200, Torsten Rueger wrote: >sorry, but I've searched and searched to find exact information on how >to do a simple udp broadcast client/server, but can find it: > >I want to have a thread pinging (very small message) and possibly the >same thread receiving maybe with a 1 second timeout. And the same code >should be able to run as multiple instances on the same machine. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 There's an example how to send and receive UDP packets. - Matthias - From whisper at oz.net Sat Dec 27 13:41:25 2003 From: whisper at oz.net (David LeBlanc) Date: Sat, 27 Dec 2003 10:41:25 -0800 Subject: Chandler status (was Re: Project dream In-Reply-To: Message-ID: > > > > I wonder how healty it is: their wiki is empty, the Mitch Kapor blog > > is stopped, there is not much recent news. But interesting certainly. > > Reading the blog at > > http://blogs.osafoundation.org/mitch/ > > So the project seems healthy. Even if the blog entry starts in the > style of writing that usually accompanies "we tried our best, we had > good people, but we're screwed" announcements. > > > -- > Ville Vainio http://www.students.tut.fi/~vainio24 It is not easy, but one can find the information needed to d/l the latest Chandler releases and cvs. I d/l'd the cvs on 12/26 and a quick look found the latest file date as 12/18. That seems pretty healthy to me. http://wiki.osafoundation.org/twiki/bin/view/Chandler/WebHome then select "GettingChandler". Latest distro and cvs instructions there. HTH, Dave LeBlanc Seattle, WA USA From fredrik at pythonware.com Wed Dec 10 01:57:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Dec 2003 07:57:43 +0100 Subject: What is the "self" name always referring to...? References: <9b849915.0312092231.1a843c02@posting.google.com> Message-ID: Todd Gardner wrote: > Pardon my extremely ignorant newbie questions. > > Where can I go to find more information about the "self" argument? > > Is there something special about the word "self" or did Mr. Guido van > Rossum just decide to us the word arbitrarily? > > More precisely it seems that most all classes have "self" as the first > parameter. This may be directly obvious but is the word "self" always > referring to the class or the function it is used in? self is used in *methods* (which are functions associated with classes), and is used to refer to the current instance of the class that method belongs to. for more on classes, see the tutorial: http://www.python.org/doc/current/tut/node11.html the FAQ also contains some helpful entries: http://www.python.org/doc/faq/programming.html#what-is-self http://www.python.org/doc/faq/general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls > Is it a reserved word? nope, but it's usually a good idea to treat it as if it were. From eppstein at ics.uci.edu Sun Dec 7 18:39:59 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 07 Dec 2003 15:39:59 -0800 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: In article , Douglas Alan wrote: > Someone else in this thread claimed that CamelCase came to Pascal via > Apple. And we know that Apple was lapping at the time from the font > of Xerox Parc. This would explain how CamelCase made it from > Smalltalk to Pascal. > > I used Pascal in the very late '70's and very early '80's, and I never > saw anyone use CamelCase in it. I still have Pascal code lying around from 1980-1982 that does use CamelCase (with initial capital for variables and functions, without for procedures). This would have been with Rutgers Pascal on the DECsystem-20, so unlikely to have much Apple influence. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From bryan.weingarten at mpgedit.org Fri Dec 12 00:21:34 2003 From: bryan.weingarten at mpgedit.org (Bryan Weingarten) Date: Fri, 12 Dec 2003 05:21:34 GMT Subject: ANN: py_mpgedit SDK 0.2 beta released Message-ID: py_mpgedit SDK 0.2 beta has been released ========================================= CHANGES * Added volume control * Fixed exception handling when not using callbacks DESCRIPTION py_mpgedit is the mpgedit SDK python extension for Linux and Windows. mpgedit Software Development Toolkit (SDK) is a library exporting core editing, playback and indexing functionality. It edits and plays MP3 files (MPEG 1 layer 1/ 2/3, MPEG 2, and MPEG 2.5 audio files). Using this toolkit, developers can create their own MP3 editing applications. SAMPLE SESSION Here is a sample session demonstrating editing and playback of an mp3 file using this extension. This creates a file new.mp3 from seconds 6 to 12 of old.mp3, then plays new.mp3. >>> import mpgedit >>> spec = mpgedit.Spec() >>> spec.append('old.mp3', '6-12') >>> mpgedit.Index('old.mp3').index() >>> mpgedit.Edit(spec, 'new.mp3').edit() >>> mpgedit.Play('new.mp3').play() LICENSE Python-based open source license GPL-compatible LINKS Download the py_mpgedit SDK: http://www.mpgedit.org/mpgedit/download_sdks.html Browse the documention: http://www.mpgedit.org/mpgedit/sdk/py_mpgedit.htm mpgedit home page: http://www.mpgedit.org mpgedit SDK on freshmeat: http://tinyurl.com/yv8j From http Wed Dec 3 05:53:35 2003 From: http (Paul Rubin) Date: 03 Dec 2003 02:53:35 -0800 Subject: Remove no-printable characters in string References: Message-ID: <7xhe0ixjdc.fsf@ruckus.brouhaha.com> pascal.parent at free.fr (Pascal) writes: > What's the best way to delete or replace no-printable characters in a string. > i.e.: "\x08toto\x00titi" -> "tototiti" or " toto titi" Fastest way is probably with the built-in string.translate operation. From newsgroups at jhrothjr.com Tue Dec 30 15:22:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Dec 2003 15:22:09 -0500 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: Could you please *not* add whatever signature or business card or whatever you're adding to your messages? My anti-virus blocks access to your entire message when you do that, and it's a royal pain to save the message and then disassemble it to find you made one line of comment. John Roth "Jp Calderone" wrote in message news:mailman.51.1072812951.8134.python-list at python.org... From mjackson at alumni.caltech.edu Tue Dec 9 09:54:17 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 9 Dec 2003 14:54:17 GMT Subject: Case sensitive and ludicrous statements References: Message-ID: "Cy Edmunds" writes: > "Mark Jackson" wrote in message > news:br0m9h$qn2$1 at news.wrc.xerox.com... > > Re. CamelCase and SmallTalk: ISTR that the Alto keyboard lacked an > > underscore character (I believe the character code was used for > > left-arrow, which I vaguely recall was used for assignment in BCPL > > and/or Mesa). As constructions like foo_bar are the obvious > > alternative to FooBar, could this lack have been a factor at PARC? > You're right Mark. Mesa mapped the underscore to left arrow, which was used > for assignment. I suppose this was an improvement over Pascal's := except > that ItMadeYouWriteLikeThis. [Good morning, Cy. Bridge?] And I see by the Smalltalk-80 book I have here that Smalltalk makes use of the left arrow as well. This all suggests that the "standard PARC character set" lacked the underscore. (As far as I can tell the only other variation from standard ASCII was the replacement of the carat "^" with an up-arrow.) I wonder how far back that goes - the Nova-based POLOS system? MAXC? -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Logic doesn't apply to the real world. - Marvin Minsky From sam at samuel-kleiners-computer.local Sun Dec 7 10:34:36 2003 From: sam at samuel-kleiners-computer.local (Samuel Kleiner) Date: Sun, 07 Dec 2003 09:34:36 -0600 Subject: New inited instance of class? References: Message-ID: Peter Otten wrote: > Samuel Kleiner wrote: > >> So can I make all my classes derive from object without >> doing so explicitly- IE, without having to change every >> single top-level class definition? >> > > You can do it on a per-file basis by putting > > __metaclass__ = type > That's what I meant. Great, thanks. -- "You've got to kill people, and when you've killed enough they stop fighting." --Curtis LeMay From snarflemike at yahoo.com Tue Dec 2 12:58:34 2003 From: snarflemike at yahoo.com (Mike Silva) Date: 2 Dec 2003 09:58:34 -0800 Subject: Stuck newbie Message-ID: <20619edc.0312020958.4c1700cb@posting.google.com> Hi all, I'm a Python newbie trying to write a simple program to do some processing of a text file. So far I'm able to extract all the data I need from the file into a list (fileinput is very nice!). Here's my problem. I want the list ("namelist") to contain records, with each record consisting of a string ("name"), an integer ("flags"), and two variable-length lists of integers ("list1" and "list2"). I gather that the corresponding data object in Python would be a sequence of those four items, correct? So what I want is a list of sequences? If that is correct, what I don't understand is how to reference and modify elements of an individual object. For example, I want to do things like (in pseudocode): namelist.append( new_record ) .... namelist[ index ].flags = 99 namelist[ index ].list1.append( 100 ) But I don't see how to reference the individual elements of a data object. Any tips greatly appreciated! Mike From luigipaioro at libero.it Fri Dec 5 09:59:54 2003 From: luigipaioro at libero.it (Luigi) Date: 5 Dec 2003 06:59:54 -0800 Subject: Web authentication References: Message-ID: Thak you... I've tried to follow yours suggestions, but I cannot solve my trouble yet! These are my attempts: def open_site1(): import urllib2 auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('My realm', 'http://mysite.com/', 'user', 'password') opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) site = urllib2.urlopen('http://mysite.com/') print site.read() def open_site2(): import urllib class Open_with_auth(urllib.FancyURLopener): def prompt_user_passwd(self, host, realm): return ('user', 'password') urllib._urlopener = Open_with_auth() conn = urllib.urlopen('http://mysite.com') print conn.read() Both don't work! Where is my mistake?? Luigi From skip at pobox.com Sat Dec 6 18:39:03 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 6 Dec 2003 17:39:03 -0600 Subject: how to determine if files are on same or different file systems In-Reply-To: References: Message-ID: <16338.26775.321085.71703@montanaro.dyndns.org> Kamus> It would be nice if I could write a function that would determine Kamus> if the source and destination are on the same file system or not, Kamus> and thus use rename or copy appropriately, or if there is already Kamus> such a built-in function. You might want to check out os.path.ismount(). Using it, you can walk up the two paths toward the root until you hit elements of bot paths where os.path.ismount() returns True. If the two mount points are the same, the two original paths are on the same file system. Here's some sample code. It doesn't help much on my Mac because it essentially has just a single disk partition. On my web server (Linux w/ multiple partitions), it seems to work okay: % df Filesystem 1k-blocks Used Available Use% Mounted on /dev/hda1 248847 93239 142758 40% / /dev/hda6 14333167 9393563 4194190 70% /backup none 385572 0 385572 0% /dev/shm /dev/hda5 9867356 7702853 1652433 83% /home /dev/hda7 1981000 1568913 309675 84% /usr /dev/hda8 248847 120886 115111 52% /var % python samefs.py ('/', '/usr') 0 ('/bin', '/etc') 1 ('/etc/passwd', '/var/log') 0 ('/Applications', '/Volumes Kisses In The Rain') 0 Skip import os def samefs(path1, path2): if not (os.path.exists(path1) and os.path.exists(path2)): return False while path1 != os.path.dirname(path1): if os.path.ismount(path1): break path1 = os.path.dirname(path1) while path2 != os.path.dirname(path2): if os.path.ismount(path2): break path2 = os.path.dirname(path2) return path1 == path2 print ("/", "/usr"), samefs("/", "/usr") print ("/bin", "/etc"), samefs("/bin", "/etc") print ("/etc/passwd", "/var/log"), samefs("/etc/passwd", "/var/log") print ("/Applications", "/Volumes Kisses In The Rain"), \ samefs("/Applications", "/Volumes Kisses In The Rain") From nessus at mit.edu Fri Dec 5 13:55:52 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 05 Dec 2003 13:55:52 -0500 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> Message-ID: "Michael Geary" writes: > In fact, mixed case names have always been very popular in the > case-independent Pascal language. Yet another reason not to use Pascal! The only language silly enough (at least in the original version) to have functions not be able to accept array arguments of arbitray size. |>oug From francisgavila at yahoo.com Tue Dec 9 23:50:06 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 9 Dec 2003 23:50:06 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: Stuart Bishop wrote in message ... >About the only thing that could be done then is: > >def memoize(callable): > cache = {} > def proxy(*args, _cache=cache): Not legal. *args must always come after default args. There's no way to do this without changing the calling characteristics of the function, which the OP has stated is vital. It is probably possible to custom-build a code object which makes _cache a local reference to the outer cache, and play with the bytecode to make the LOAD_DEREF into a LOAD_FAST, but it's not worth the effort. I don't know how fast/slow a LOAD_DEREF is compared to a LOAD_FAST, though. In any case, it won't help more than a few percent. Jacek, I think this is as fast as pure Python will get you with this approach. If the speed is simply not acceptable, there are some things you need to consider, Is this the *real* bottleneck? Consider this before you delve into C solutions, which greatly increase headaches. An easy way to check is to cut out the map and memoization and just use a dictionary preloaded with known argument:value pairs for a given set of test data. e.g., def func(...): ... data = [foo, bar, ....] cache = dict([(i, func(i)) for i in data]) def timetrial(_data=data, _cache=cache): return map(_cache.__getitem__, _data) # [operator.getitem(_cache, i) for i in _data] *might* be faster. then timeit.py -s"import ttrial" "ttrial.timetrial()" If it's still too slow, then either Python simply isn't for this task, or you need to optimize your functions. If this isn't the real bottleneck: - Perhaps the functions I'm memoizing need optimization themselves? - Are there any modules out there which implement these in C already? - How does the competing C++ code do it? Does it get its speed from some wicked data structure for the memoizing, or are the individual functions faster, or what? If this *is* the only significant bottleneck, but you want to try harder to speed it up, you can pursue the C closure path you were mentioning. With the caveat that I don't do any CPython hacking, I know that closures are implemented using co_cellvars and the LOAD_DEREF bytecode. The Python C api does describe an api to cell objects, so that will be the place to look, if it's possible to do a closure in C. It may not be faster than your straightforward approach, of course. However, comparing your Python to a C++ version on the basis of speed is most certainly the wrong way to go. If the C++ is well designed with good algorithms, its going to be faster than Python. Period. The advantage of Python is that it's much faster and easier to *write* (and less likely to introduce bugs), easier to *read* and maintain, and can model your problem more intuitively and flexibly. But if you need maximum speed at all costs, the best Python can do for you is act as a glue language to bits and pieces of hand-crafted C. Do you really *need* the speed, or are you just bothered that it's not as fast as the C++ version? -- Francis Avila From tim.one at comcast.net Wed Dec 31 02:43:15 2003 From: tim.one at comcast.net (Tim Peters) Date: Wed, 31 Dec 2003 02:43:15 -0500 Subject: selecting a random item from a set In-Reply-To: Message-ID: [Tim, asks which algorithms require random selection, as opposed to arbitrary selection, from a set] [Alexander Schmolck] > Feature selection schemes, for example? Eh? That's like "numerical methods" . IOW, too vague. >> (it can be done using O(1) space instead, > s/zip/izip/ s/range/xrange/ ? Yes, but that's still got a ton of overhead due to the Python-level looping. You can do it in O(1) space now at essentially full C speed via, e.g., i = random.randrange(len(some_set)) random_elt = itertools.islice(some_set, i, None).next() some_set.remove(random_elt) That tricks it into finding the starting point with a C loop, and then the iterator is discarded after extracting its first element. But (of course) that still takes average time proportional to the # of elements in the set. Well, that wishes away a detail: this can actually be arbitrarily expensive, as there's no bound on how sparse a Python dict can get, and the C dict iteration code has to visit every slot, occupied or not, to find "the next" occupied slot. So, e.g., it's possible that selecting the only element in a 1-element set requires millions of iterations at the C level. That's unlikely, just possible (a quirk of CPython's dict implementation is that the implementation data structure never shrinks when you delete a key; it may shrink when you add a new key, though!). > ... > I'm not entirely bitten by the premature optimization bug however -- > I know that most of the time in an existing implementation of what I > want to do in another language is spent doing these set operations > and takes minutes to hours to come up with its outputs. Which other language; how does it implement sets; is the time in that language consumed by picking random elements from sets, or by other set operations ("these" isn't really clear); and how big are these sets? If the sets are small, you're not going to beat random.choice(tuple(s)). If the sets are large, low-level optimization of an approach with the wrong O() behavior is just a monumentally bad idea. If the sets are of middling size, get more ambitious . From dennis.posadas at intel.com Tue Dec 9 22:15:53 2003 From: dennis.posadas at intel.com (Posadas, Dennis) Date: Wed, 10 Dec 2003 11:15:53 +0800 Subject: loading new unicode language encoders into lib/encodings Message-ID: Hi, Once you load the necessary language encoder into lib/encodings, is that all there is to using it ? I loaded the encoder eucgb2312_cn.py and pyc into lib/encodings but am still getting the error below... I ran something like this on the command line and this is what I got... >>> s = unicode('50e7', 'eucgb2312_cn') Traceback (most recent call last): File "(stdin)", line 1, in? Lookuperror: unknown encoding: eucgb2312_cn >>> Dennis From dman at dman13.dyndns.org Wed Dec 17 15:28:23 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Wed, 17 Dec 2003 20:28:23 GMT Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> <93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: On Tue, 16 Dec 2003 18:06:16 -0500, hokieghal99 wrote: > Thomas Heller wrote: > >> Name the script 'myscript.pyw' instead of 'myscript.py'. >> >> Thomas > > Thanks for the tip... that did it. I need to read up on the difference > between python.exe and pythonw.exe. The difference is a Microsoft one. The former has stdin, stdout and is a normal program. Microsoft dictates that on Windows such programs must have a black window appear for the life of the program. The latter is an "MFC" (or whatever the proper term is) program with no stdin or stdout. On MS Windows this means that you don't get a black box appearing, and it also means that the 'print' statement and raw_input() function are useless. The difference is the specific functions the C runtime calls to notify Windows of which sort of app it is during startup. On non-Windows platforms (eg UNIX) there is no such distinction. All (UNIX) apps have stdin and stdout, though they aren't necessarily connected to the user in any way, but could be if run in such a context. HTH, -D -- For society, it's probably a good thing that engineers value function over appearance. For example, you wouldn't want engineers to build nuclear power plants that only _look_ like they would keep all the radiation inside. (Scott Adams - The Dilbert principle) www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From richie at entrian.com Thu Dec 4 04:49:49 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 04 Dec 2003 09:49:49 +0000 Subject: Separation of content and code for web (was Re: Python for web?) In-Reply-To: References: <3FCC9A98.193ED480@engcorp.com> <73c38014.0312030233.1c051da5@posting.google.com> Message-ID: > > I believe mixed-case attribute names are not strictly valid XHTML. > > Indeed, thats why I said HTML. For XHTML all attribute names are lower case > only, so the library *could* simply lowercase any attributes you set. True, but it smacks of too much magic to me (even if it were an explicit option you had to set). I reckon Peter's dictionary-like interface is neater. -- Richie Hindle richie at entrian.com From hwlgw at hotmail.com Fri Dec 26 15:36:48 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 26 Dec 2003 12:36:48 -0800 Subject: Project dream Message-ID: Suppose you have the time and the money to start a new project in Python. What would you like to do? I can think of: - A civilization like game in Python, with multiplayer support via twisted. - An easy to use tool for drawing diagrams, typically various kinds of arrows and circles and boxes, that produces nice .eps and .svg files. - A roguelike in Python. Since there is still no portable curses, it needs WConio or something like that, and also multiplayer would be great. - Something for weblogging and todo things, probably via CGI. What would your favorite be? From __peter__ at web.de Mon Dec 22 18:53:34 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Dec 2003 00:53:34 +0100 Subject: list.index() like...but returning lists (for avoiding '0' on multiples hits) References: Message-ID: Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina wrote: > Hi....i asume this is a veeeery usual question. I'm searching on > python.org, but their results is not giving me the answer that i looking > for...So, here i go...when i have myList = [2,4,2,0] ...myList.index(2) > returns 0 (python 2.2)....There is a built-in function-method that returns > [0,2]? I don't think so. But it's not hard to do it on your own: >>> def indices(iterable, value): ... return [index for (index, item) in enumerate(iterable) if item == value] ... >>> indices([1,2,3,1,-1], 1) [0, 3] Peter From toop82 at comcast.net Sat Dec 6 22:18:29 2003 From: toop82 at comcast.net (Robert Toop) Date: Sun, 07 Dec 2003 03:18:29 GMT Subject: memory usage References: Message-ID: <9_wAb.451548$Fm2.447978@attbi_s04> "Dave" wrote in message news:c375aec2.0312052020.6e26239c at posting.google.com... > Hi, > I'm writing code which deals with lists of millions to tens of > millions of > elements. It seems to me that python gobbles up memory faster than it > should in these cases. > > For example, I start the python interpreter and then execute the > following code: > > >>> f = [] > >>> for i in range(1e7): > ... f.append(0.1) > > In another window on my Linux system I then run top. The python > process is now using 155 MB of memory. Why is python using such a > large amount of memory, nearly nearly 16 bytes for a float in this > case? 8 bytes for each float, and I'm guessing 8 bytes for 2 pointers to form the list. One needs 2 pointers in order to facilitate nearby forward/backward reference, and to be able to remove an element without having to search from the start. An extensible list cannot be a pointer-free contiguous array unless all elements are copied each time you append to it. Access to a linked list like this requires not only extra memory, but extra time, to say nothing of large RAM to avoid virtual memory paging. You'd be better off with static-dimensioned (hence contiguous) arrays. Of course, that might be impractical for your app. If your lists require dynamic extension and sparse random access, you'd be better off with an indexed tree (database-like) storage scheme. I'm too new to python to know if such packages exist, but I'll bet they do. From g2h5dqi002 at sneakemail.com Tue Dec 9 00:48:16 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 09 Dec 2003 18:48:16 +1300 Subject: Lists and Tuples In-Reply-To: <20031208190240.5ff11e93.johnlr@despammed.com> References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> <20031208190240.5ff11e93.johnlr@despammed.com> Message-ID: John La Rooy wrote: > Hmmm..Sep 31? Should I file a bug report? ;o) You're failing to take into account the (highly controversial) International Calendar Reform of 2006, which gave all months the same number of days. Python was, of course, the first language to have its datetime module updated to conform with the new standard. (Microsoft Java++#.NET was updated too, but in a subtly incompatible way -- all their months were given 30 days instead.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bdesth.nospam at removeme.free.fr Thu Dec 11 16:36:00 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2003 22:36:00 +0100 Subject: What GUI toolkit looks the best? In-Reply-To: <7xad5z1jq5.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: <3fd8df10$0$17113$626a54ce@news.free.fr> Paul Rubin wrote: > Brian Kelley writes: > (snip) > > >>I tend to use Tkinter for canvas heavy applications and wxPython for >>other stuff. > > > Is wxPython Windows specific? I guess it is, You lose. > but can I port the > screen layouts to some comparable Linux toolkit or anything like that? > The screen shots for it do look really nice. > > >>Here is my humble opinions in a nutshell (missing a lot here): >>wxPython has a grid control to die for and many, many classes, good >>printer support and looks like a native GTK app on Linux and a native >>app on windows and macintosh. Perhaps because it uses 'native' (ie : Gtk+, Motif, Windows native or MacOS X native) toolkits ?-) > > Oh wow, yes I guess it's cross platform then. You win !-) > Hmm, what Micro$oft > tool do I need to build and run it? Is Visual C++ enough? Yeps. Or bcc, or mingw, or... > I guess > I can get the client to pay Why ? It's free (as in free beer and free speech) > for some stuff like that. Also, is there > a Glade-like drag and drop gui editor for it? > wxGlade. And also boa, PythonCard... > I don't know what I can really tell from these without more experience > with them. In particular, which is the most solid and reliable across > a wide range of Windows versions (95, 98, ..., XP whatever)? That > matters too. Can't tell you about that (I used wxWindows on win98 and NT4ws and Linux/Gtk+, without any trouble but as in any non-trivial code, there are bugs... no more no less than in MFC or Borland toolkits) Bruno From antonmuhin at rambler.ru Fri Dec 26 13:53:15 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 26 Dec 2003 21:53:15 +0300 Subject: callable classes In-Reply-To: References: Message-ID: Duncan Smith wrote: > I recently started to rewrite a class and decided to take a bunch of related > methods and put them in a separate callable class. (They're all what I > would call pointwise operations on pairs of instances, they raise exceptions > for identical reasons, and they all return a new instance). It seemed like > a good idea at the time, but now I'm not so sure. So my very general > questions are: > > Is this a reasonable use for a callable class? > > In what circumstances are callable classes particularly useful? (Maybe I > haven't racked my brains long enough.) > > Cheers. TIA. > > Duncan > What do you mean by 'callable class'? Classes are callables. Ot you mean a class that defines __call__ method? In this case it's really useful. regards, anton. From duncan at NOSPAMrcp.co.uk Tue Dec 9 10:08:42 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Dec 2003 15:08:42 +0000 (UTC) Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote in news:m3y8tnw6wh.fsf at mira.informatik.hu-berlin.de: >> The main problem is that functions are first class objects in Python, >> but not in the CLS. The CLS uses delegates to refer to functions, and >> a delegate encapsulates both an object and a pointer to a method. > > In addition, I think one problem is that in CLS, a class has a > pre-determined set of data attributes, whereas in Python, instances > grow new data attributes as they live. I don't believe that is too much of a problem. Even in Python many of the data types have a fixed set of attributes. Even user defined classes, if they use __slots__, might not allow you to add attributes. So, for .Net, some user defined classes might have a __dict__ attribute, but others don't. Attributes which are accessed through __dict__ won't be visible to non-Python code, but that shouldn't be a problem. > >> I have been playing around with a variant on the managed Python >> compiler, and I think I have figured a way to implement Python which >> might just get around this bottleneck. Unfortunately it requires a >> lot of refactoring from the original model, and I'm only working on >> it occasionally in my spare time. > > Very interesting. Are you willing to share the intermediate results > that you get? Publish early, publish often :-) > I'm more than willing to share, but so far its been a massive refactoring job so I was waiting until things settled down a bit before releasing anything. I expect the main speed gains to come when I get the new model for functions and methods working and eliminate as far as possible calls the reflection apis. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From sross at connectmail.carleton.ca Sun Dec 14 13:31:19 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sun, 14 Dec 2003 13:31:19 -0500 Subject: Python Cookbook question re 5.6 References: Message-ID: "Joe" wrote in message news:SX%Cb.548624$Fm2.517912 at attbi_s04... > The recipe in question is "Implementing Static Methods". It shows how to > use staticmethod(). This sentence in the Discussion section isn't clear to > me: "An attribute of a class object that starts out as a Python function > implicitly mutates into an unbound method." I'm not sure what this means, > exactly. Can anyone elaborate? > > Thanks, > Chris > Here's an example that may help show what's going on: class C: def f(): print "f" print type(f) print type(C.f) try: C.f() except TypeError, e: print e try: c = C() C.f(c) except TypeError, e: print e # OUTPUT unbound method f() must be called with C instance as first argument (got nothing instead) f() takes no arguments (1 given) When the class C is evaluated the "print type(f)" statement is executed. It shows that, at that moment, f's type is 'function'. But when you ask, "type(C.f)" it tells you that f is an instance method. When you try to call f using "C.f()" you're told that f is an unbound method, that must be called with an instance of C as the first argument. When you make a method, you usually specify the first argument as being "self". In this case "self" would be an instance of C. So, anyway, now f appears to expect an argument when it's called. So, we try passing in what it appears to expect "C.f(c)", and it tells us that "f() takes no arguments (1 given)". Heh. I'm not exactly sure what Python's doing behind the scenes but I imagine that it's wrapping all function definitions inside the class body: something like for all functions in the class: function = unbound_method(function) where unbound_method is a callable that maintains the original function as an attribute. When you call the unbound_method, it delegates the call to this function f. It's the unbound_method that expects the "instance of C as the first argument", but when it passes the argument to its delegate function f - well, f doesn't take any arguments, so we get an exception. Like I said, I don't know exactly what mechanism are being employed behind the scenes, but this is the way I try to understand what's going on. Hopefully this is somewhat correct, and helpful, Sean From fredrik at pythonware.com Thu Dec 11 07:51:38 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 13:51:38 +0100 Subject: Drawing on the root window in Linux? References: Message-ID: Diez B. Roggisch wrote: > > Sorry if this has been asked before, but I couldn't find any answers, > > and Google was coming up empty. > > Did you check superkaramba? That does python-enriched interactive backround > content. So they gotta somehow manipulate root :) they're using shaped windows, don't they? see http://netdragon.sourceforge.net/?page=Creating+a+Widget+Mask From lkcl at lkcl.net Mon Dec 15 18:36:39 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Mon, 15 Dec 2003 23:36:39 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <1071524194.15985.660.camel@localhost.localdomain> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> Message-ID: <20031215233639.GE26055@lkcl.net> On Mon, Dec 15, 2003 at 04:36:35PM -0500, Jeremy Hylton wrote: > One kind of problem is that newer Python features were designed without > taking rexec into account. It's possible for untrusted code to cause > the trusted interpreter to execute its code without restriction using > descriptors. It would be really difficult to reconcile new-style > classes and rexec. Perhaps a worthwhile project, but probably one > accomplished by design a new restriction mechanism that builds on some > of the basic mechanism of rexec. okay. i think the only really sensible way forward is to begin from a sound basis - one that is going to be a big job to add retrospectively, but a simple beginning can be made. proposal: how about building ACLs into the python codebase? the basic operations are read, write, execute and modify_acl the advanced operations are "applies-to-sub-objects" and "automatically-added-to-created-sub-objects". it should be easy to add more operations, both default ones AND user-defined ones. [the advanced operations are based on the new NT 5.0 (aka windows 2000) enhancements to the original VMS security model back from dave cutler's time when he worked for DEC and then he and his team got poached by microsoft to do NT, yes it's a long story.] the basic primitives are __get_acl__(), __set_acl__() and __check_acl__(operation_type). the acl should consist of a dictionary of aces [access control entries] where the name is the function or module name, and the value is an ace object. the objects should contain a __get_ace__() function and a __set_ace__() function. the ace should contain a permission (read, write, execute, modify_acl etc.) and an "ALLOW" or "DENY" qualifier. the algorithm for evaluating an acl has been worked out already, and implemented originally by matthew chapman of the samba team, so code under the GPL already exists [in an NT-like environment which is over-the-top]. the basics of the evaluation algorithm are that you pass in who you are (in this case, that's the function or module name), what type of operation you want to perform (read, write, execute, or combination of these) and the ACL. the aces are evaluated, looking through the dictionary (actually it's going to have to be a list of tuples now that i think of it because the order is important, due to the ALLOW and DENY attributes), checking first that the ACE name matches the "who am i" and then checking what type of permission was requested against the ACE entries. the tricky bit is the "inheritance" permissions, which create "shadow" ACLs or, more specifically, they "throw shadows" down the sub-objects, adding or removing permissions from all sub-objects. in this way, it is possible to implement rexec by simply removing the write permissions at the top level as an "inherited" permission. an empty acl means "anything goes" (including that of "any acl may be added to this object"). an empty acl also means that there is no performance penalty for having acl code in the python codebase. l. From deets_noospaam at web.de Wed Dec 3 18:52:10 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 04 Dec 2003 00:52:10 +0100 Subject: graphs in python... References: Message-ID: Douglas F. Calvert wrote: > Hello, > I read "Python Patterns: Implementing Graphs" document on the website > and was impressed with doing graphs in this fashion. Is this still the > best documented way to do graphs. The document alludes to a follow up > article tuned for speed but I have not found it. Can anyone suggest > other ways that might be faster? I am looking to implement a graph with > over 11k nodes and I am afraid that the speed might begin to wither. I > have implemented a test version with this code and a set of 5k nodes and > the speed could be quicker:) Maybe its faster to store the adjacences in a matrix (e.g. Numeric array) - some graph ops then are simple matrix ops. A node of course is than only an number - used as index. That should speed things up. You can of course have a dictionary to map names to nums and vice versa. Diez From jbarham at jbarham.com Wed Dec 10 02:04:24 2003 From: jbarham at jbarham.com (John E. Barham) Date: Wed, 10 Dec 2003 07:04:24 GMT Subject: What is the "self" name always referring to...? References: <9b849915.0312092231.1a843c02@posting.google.com> Message-ID: "Todd Gardner" wrote: > Where can I go to find more information about the "self" argument? >From the Python tutorial: "Conventionally, the first argument of methods is often called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. (Note, however, that by not following the convention your code may be less readable by other Python programmers, and it is also conceivable that a class browser program be written which relies upon such a convention.) " http://www.python.org/doc/current/tut/node11.html#SECTION0011400000000000000000 > Is there something special about the word "self" or did Mr. Guido van > Rossum just decide to us the word arbitrarily? You could use anything, but the convention for using "self" is very strong. > More precisely it seems that most all classes have "self" as the first > parameter. This may be directly obvious but is the word "self" always > referring to the class or the function it is used in? I'm not sure what you're asking here. The first argument of any class method (i.e., "self" per the above discussion) is the object on which the method is being called. It's equivalent to the "this" keyword in C++ (Java?), although in C++ "this" is implied and is not part of the argument list. A contrived example: C++: class Foo { public: Foo(int a) { a_ = a; this->a_ = a; // same as above } int getA() { return a_; } private: int a_; }; Python: class Foo: def __init__(self, a): self._a = a def getA(self): return self._a > Is it a reserved word? No. > Thank you in advance, Sure. John From simonb at webone.com.au Fri Dec 12 19:02:58 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 13 Dec 2003 11:02:58 +1100 Subject: Drawing on the root window in Linux? References: Message-ID: On Thu, 11 Dec 2003 17:42:25 +1300, David McNab wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Charlie Lesh wrote: > | Hey all: > | > | Is there any way to draw on the 'root' window? I'm thinking about a > | python screensaver for linux. I know that there are xlib bindings for > | python, maybe a little outdated, but do they have what I might need? > > Try xlib-python (or python-xlib). > And welcome to a whole new world of pain. > > Yeah, but it's cool and it does everything, i think. Let me know if you head down this path. Simon. From mwh at python.net Mon Dec 8 09:49:06 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 8 Dec 2003 14:49:06 GMT Subject: Speed: bytecode vz C API calls References: Message-ID: Jacek Generowicz writes: > Could anyone suggest how I could squeeze more speed out of the > memoizer? (I'll include the core of my memoize extension type at the > below.) You *might* get a speed bump by making your memoized callable a method of the memoizer object rather than implementing tp_call. Cheers, mwh -- M-x psych[TAB][RETURN] -- try it From peter at engcorp.com Tue Dec 2 21:32:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Dec 2003 21:32:24 -0500 Subject: Can Python be run off of a CD-ROM? References: <3FCC8C92.406@ghaering.de> <3FCC9F83.7050405@ghaering.de> <8ylv6pq0.fsf@python.net> Message-ID: <3FCD4B38.CCECD83F@engcorp.com> Thomas Heller wrote: > > win32all is growing in a direction where it makes fewer use of the > registry than in the past, and the sandbox py2exe is already able to > create frozen com servers which work fine with python23.dll in the > executable directory, so I assume somewhere in the future Python > releases don't need dlls in the system directory anymore. Technically, no release since at least 2.0 has required DLLs in the system directory, but it has taken some work (growing less by the release) to make that possible. We've used a shared network installation of Python for each release from 2.0 on, with only minor tweaking. Initially we had to move the DLLs manually from the installation machine's SYSTEM directory to the network drive. Now the non-admin option resolves that issue. win32all is for us the only remaining issue. We need to include a .pth file with two or three paths in it (even though the package installs itself under site-packages now!). We also still need to set up a sitecustomize.py file which does imports on pythoncom and pywintypes, or an import of win32api (for example) will fail. I don't recall the explanation, but without first importing those (or perhaps just one?) modules you can't import the win32 stuff, but if they have been imported first, then it works fine. Details/help supplied to those with troubles doing this, on request... -Peter From seb.giraud78 at wanadoo.fr Wed Dec 17 03:46:56 2003 From: seb.giraud78 at wanadoo.fr (Sebastien GIRAUD) Date: Wed, 17 Dec 2003 09:46:56 +0100 (CET) Subject: Threads for a newbe Message-ID: <7916961.1071650816818.JavaMail.www@wwinf0303> Hello, First let say that am french and that i'll try to write the best english i can... I'm a python newbe and have the following problem : I try to create 2 threads in a server program and they seems to block each other. I use something like this : start thread waiting for connexion with : server.threadserver = threading.Thread(target = self.__startserver) then do while 1 : socket, host = accept(...) then start a new thread for each new connexion after accept using client.threadclient = threading.Thread(target = self.__receive) and while 1 : client.receive() And here the first thread seems not to work anymore :( . I didn't join threads. Maybe a lock() problem but i don't now how to use the lock() function in Python... Maybe if someone had a multithread server sample source I could understand what is the issue... Regards Seb. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill at rfa.org Sun Dec 28 12:56:47 2003 From: bill at rfa.org (Bill Eldridge) Date: Sun, 28 Dec 2003 18:56:47 +0100 Subject: Unicode from Web to MySQL In-Reply-To: References: Message-ID: <3FEF195F.1020501@rfa.org> Serge Orlov wrote: >>. What's driving me crazy is knowing the encoding >>but still not getting the data all the way through the chain to MySQL. >> >> > >That's because you're trying to create SQL statements manually. > > As opposed to what? > > >>>>2) Convert to unicode before UTF-8 >>>> >>>> >>>Not sure what that means. >>> >>> >>data.decode(None,'strict') >>or >>unicode(data,'unicode','strict') >> >> > >See Francis' excellent post why both of these calls do not make sence at all. > > > Understand, I tried doing absolutely nothing for the supposedly Unicode strings, just taking them as-is and putting them into the database, and I get these ASCII decoding errors. I try decoding them as UTF-8, which supposedly they are, and I get these errors. So then I try stupid stuff just to see if something stupid works. >>>>3) replace quotation marks within the SQL statement: >>>>data2.replace(u'"',u'\\"') >>>> >>>> >>>It's not a unicode problem, is it? >>> >>> >>Occasionally instead of getting the encoding error I get a SQL syntax error, >>and figured somewhere it was misinterpreting something like the end >>delimiter. >>No proof though, just a guess, so I tried the replaces. >> >> > >Uh, I see. If you're creating SQL statement yourself, you have to take care >of escaping. I guess after data2.encode('utf-8') you've got illegal (in SQL) >characters and you have to escape them. Another quick scan of mysql-python >docs reveals that .execute method can be called as >c.execute(''' INSERT INTO junk ( junklet) VALUES ( '%s') ''', args=(data2,) ) >where data2 is a unicode string. Then the python wrapper will take care of >unicode convertions and escaping. Don't forget that you need to .connect with >unicode='utf-8' parameter. > > > Again, what do you mean "creating SQL statement yourself"? and what is the alternative? I'll try out this version of the execute statement. From eppstein at ics.uci.edu Mon Dec 22 20:06:40 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Dec 2003 17:06:40 -0800 Subject: Using both keyword=something and *unknownqty arguments in a function References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: In article , "Francis Avila" wrote: > >def skeptic(first='Zeus', second='Guido', *others) > > print first > > print second > > print others > > return "and I did not think it could ever work!" I think there is not so much problem mixing keyword=something and *unknownqty, as long as you do not also allow named positional arguments. def skeptic(*others, **keywords): print keywords['first'] print keywords['second'] print others return "and I did not think it could ever work!" >>> answer=skeptic('believer', 'non-believer', 'heretic', first='Eric', second='unknown') Eric unknown ('believer', 'non-believer', 'heretic') >>> answer 'and I did not think it could ever work!' -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From martin at v.loewis.de Tue Dec 16 15:14:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Dec 2003 21:14:40 +0100 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031216195525.GJ17021@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> Message-ID: Luke Kenneth Casson Leighton writes: > > Also, it seems that nowhere in your proposal you state how ACLs should > > be integrated into Python: I.e. what objects are protected by ACLs, > > all objects - if an acl is non-null. Does this include functions and bound and unbound methods? > > 3 * 4 > > > > Is that read, write, execute, and which ACL(s) is(are) considered? > > execute, and execute only, because there's no I/O involved. > > on the multiply operation. So what operations require read or write access? > but _only_ if there's an actual ACL set _on_ the multiply function. > > if there's no acl set on the multiply function, there's no > restrictions on the multiply function. So ACLs on the objects 3 and 4 would be irrelevant? Generalizing this, given a class Foo, with a method bar(), and two instances foo1 and foo2: foo1 = Foo("/etc/passwd") foo2 = Foo("/tmp/nonexistant.yet") and considering the calls foo1.bar() and foo2.bar(): Given that *only* the ACL on the operation bar matters: Does that mean that the calls either both succeed or both fail, for a given caller? Regards, Martin From a_bogdan_marinescu at yahoo.com Thu Dec 11 03:26:52 2003 From: a_bogdan_marinescu at yahoo.com (Bogdan Marinescu) Date: Thu, 11 Dec 2003 00:26:52 -0800 (PST) Subject: Looking for ELF/PE library for Python Message-ID: <20031211082652.14128.qmail@web21205.mail.yahoo.com> Hello, Is there a Python library for working with ELF and/or PE(Portable Executable) formats? By "working" I mean handling file structure, dumping structure information, extracting specific parts of the file and even creating "by hand" new sections/relocations. I already searched some locations for such a library, but I couldn't find anything suitable. Thank you for your time. Bogdan M. __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From alanmk at hotmail.com Fri Dec 5 10:08:03 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 05 Dec 2003 15:08:03 +0000 Subject: xml.dom.minidom -> Xpath ? References: <3fcfdfdf$1_2@news.bluewin.ch> <3FD062C7.D79ADB74@hotmail.com> <3fd09122$1_1@news.bluewin.ch> Message-ID: <3FD09F53.558ACD86@hotmail.com> [Alexandre] > Using Xpath sounds realy cool but... can i do that with a DOM object ? > (haven't found any reference to Xpath in DOM or minidom Python's doc?!) You have to install PyXML to get Xpath support. Try here for the software http://pyxml.sourceforge.net/ And there is some Xpath documentation here http://pyxml.sourceforge.net/topics/howto/section-XPath.html HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From max at alcyone.com Thu Dec 4 16:44:12 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 04 Dec 2003 13:44:12 -0800 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <3fcf6605$0$7671$3a628fcd@reader1.nntp.hccnet.nl> <87smk0gtmi.fsf@inf.enst.fr> Message-ID: <3FCFAAAC.77435C1D@alcyone.com> Samuel Tardieu wrote: > You can use one of the three (there are more) > > ([[]]*n)[:] This won't work. [:] makes a shallow copy. This will make a different containing list, but the contained lists will still be identical: >>> s = [[]]*10 >>> s = [[]]*5 >>> t = s[:] >>> id(s) 1076779980 >>> id(t) 1076780300 >>> map(lambda (x, y): x is y, zip(s, t)) [True, True, True, True, True] >>> s[0].append(2) >>> s [[2], [2], [2], [2], [2]] >>> t [[2], [2], [2], [2], [2]] -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ I'm sharing the joy / I'm glowing like sunshine -- Chante Moore From eldada at mdstud.chalmers.se Wed Dec 17 07:54:29 2003 From: eldada at mdstud.chalmers.se (Ali El Dada) Date: Wed, 17 Dec 2003 13:54:29 +0100 Subject: OO issues in python In-Reply-To: References: Message-ID: <3FE05205.8010001@mdstud.chalmers.se> ok that settles everything.. thanks a million!!! Regards, Ali Dada Lutz Horn wrote: > Hi, > > * Ali El Dada [17 Dez 2003]: > >>Albert Hofkamp wrote: >> >>>If the parent and the child class need to share data, you either >>>put the data in the sub-class (ie Child), or you create a new >>>class that holds the data where both the parent and the child >>>have access to. >> >>well the first solution is not feasible with me because i may have >>more classes and subclasses that may need this information (it is >>like a dictionary that has some global information, e.g. about the >>environment) > > > What's the problem with passing the context to every instance of a > subclass? It's only a parameter in a constructor or the call of a > method like setContext(). > > >>so do you advise me to take the second solution, creating a class >>called Global that any other class can access?? as in: (not >>tested) >> >>class Global: >> user_home = os.environ['HOME'] >> my_app_data = 'C:\\Program Files\\MyApp' >> >>class AnyClass: >> self.user_home = Global.user_home > > > No, don't use global data. > > Lutz From duncan at NOSPAMrcp.co.uk Tue Dec 9 09:08:04 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Dec 2003 14:08:04 +0000 (UTC) Subject: sys.traceback + thread References: Message-ID: fowlertrainer at anonym.hu wrote in news:mailman.264.1070976113.16879.python- list at python.org: > This is a thread's run method. > > def run(self): > try: > page=urllib.urlopen(base) > src=page.read() > page=None > self.ResultCode=0 > self.ResultSrc=src > except: > self.ResultSrc="An error occured"+ > the exception's errormessage !!! > self.ResultCode=1 > > I use the traceback module in one threaded application. > But I don't use it in multiple threaded app. > > What can I use/how can I do in except section to get the exception's > message ? > > Please help me. Call sys.exc_info() to get the current exception details, then use the traceback module to format the information as you require. Or you could call traceback.print_exc() if you just want to display the exception and traceback. sys.exc_info() and print_exc() are both thread safe. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From Ax10 at gmx.de Mon Dec 1 14:09:30 2003 From: Ax10 at gmx.de (Mike Abel) Date: Mon, 1 Dec 2003 20:09:30 +0100 Subject: tkFileDialog.askdirectory References: <0u3s91-v42.ln1@6.mabelsoft.org> Message-ID: Mike Abel wrote: > Hello > i have a Linux Mandrake Distribution with Python 2.3 and Tcl/Tk 8.4. > Python 2.2 and Tcl/Tk 8.3.3 returns an String if i made this: > x = tkFileDialog.askdirectory(initialdir="was auch immer", title="xxx") > print type(x) > > With the combination Python 2.3 and Tcl/Tk 8.4 it returns > > I have asked an other user (he used Windows 2000 Python 2.3.2 > Tcl/Tk 8.4) and it returns an string. The reason for this is possibly this: "Calling Tcl methods through _tkinter no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a _tkinter.Tcl_Obj object if no Python equivalent exists. This behavior can be controlled through the wantobjects() method of tkapp objects. When using _tkinter through the Tkinter module (as most Tkinter applications will), this feature is always activated. It should not cause compatibility problems, since Tkinter would always convert string results to Python types where possible. If any incompatibilities are found, the old behavior can be restored by setting the wantobjects variable in the Tkinter module to false before creating the first tkapp object. import Tkinter Tkinter.wantobjects = 0 Any breakage caused by this change should be reported as a bug." Thanks to Klaus From oliver.walczak at momatec.de Thu Dec 18 05:44:46 2003 From: oliver.walczak at momatec.de (Oliver Walczak) Date: Thu, 18 Dec 2003 11:44:46 +0100 Subject: AW: traceback as string In-Reply-To: Message-ID: This seems to be a quite difficult approach. Try this: ##################################################################### import traceback class MyTraceback: def __init__(self): self.clear() def clear(self): self.s = '' def write(self, s): self.s += s def read(self): return self.s def catch(self): traceback.print_exc(None, self) if __name__ == '__main__': myTcb = MyTraceback() try: a = 1/0 except: myTcb.clear() myTcb.catch() print myTcb.read() ###################################################################### Call clear() each time before you expect a new traceback output. You can import this class and don't need to import traceback in your main project. Oliver "John Hunter" wrote in message news:mailman.202.1071593230.9307.python-list at python.org... > > What is the best way to get the traceback as a string. I define the following module "Excepts.py" for logging exceptions in daemon processes: ------------------------------------------ import sys,traceback def error(): tb = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info( )[2]) return tb[len(tb)-1].replace('\n','') def errorstack(): return ''.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.e xc_info()[2])) ------------------------------------------- Colin Brown PyNZ -- http://mail.python.org/mailman/listinfo/python-list From cliechti at gmx.net Mon Dec 8 17:51:14 2003 From: cliechti at gmx.net (Chris Liechti) Date: Mon, 8 Dec 2003 22:51:14 +0000 (UTC) Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> <9b849915.0312080136.867babc@posting.google.com> Message-ID: piir at earthlink.net (Todd Gardner) wrote in news:9b849915.0312080136.867babc at posting.google.com: > Chris Liechti wrote in message > news:... [pyparallel] >> currently i have only py2.2 versions available for download, but i >> can easily build the 2.3 version upon request, > > I would like to request that you build a 2.3 version. at your wish (one line): https://sourceforge.net/project/showfiles.php?group_id=46487&release_id=147 361 (thats the download section of pyserial.sf.net) chris -- Chris From dave at pythonapocrypha.com Fri Dec 12 11:58:17 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 12 Dec 2003 09:58:17 -0700 Subject: do this with list comp? References: Message-ID: <020f01c3c0d1$23c1ff00$891e140a@YODA> > I want to replace all empty fields in a CSV line with 'NULL'. > > Here is a brute force way > > def fixline(line): > ret = [] > for s in line.split(','): > if not len(s): ret.append('NULL') > else: ret.append(s) > return ret > > line = 'John,Bill,,,Fred' > print fixline(line) > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > > I am wondering if there is a way to do it with list comprehensions. I > know how I would do it with a ternary operator..... Prepare to be flooded with answers. ;-) >>> line = 'John,Bill,,,Fred' >>> [x or 'NULL' for x in line.split(',')] ['John', 'Bill', 'NULL', 'NULL', 'Fred'] -Dave P.S. I guess you are sure that the fields themselves don't have commas and that you don't therefore need a "real" CSV parser? From dkuhlman at rexx.com Mon Dec 22 13:29:49 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 22 Dec 2003 10:29:49 -0800 Subject: HTML data extraction? Message-ID: I recently read an article by Jon Udell about extracting data from Web pages as a poor person's Web services. So, I have a question: Is there any Python support for finding and extracting information from HTML documents. I'd like something that would do things like the following: - return the data which is inside a tag which is inside a
  • tag. - return the data which is inside a tag that has attribute href="http://www.python.org". - Etc. It would be a sort of structured grep for HTML. I've found the HTMLParser and htmllib modules in the Python standard library, but I'm wondering if there is anything at a higher level. Web searches did not turn up anything interesting. Thanks for help. Dave -- http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From francisgavila at yahoo.com Sun Dec 7 12:56:14 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 7 Dec 2003 12:56:14 -0500 Subject: New inited instance of class? References: Message-ID: Fredrik Lundh wrote in message ... >Francis Avila wrote: > >> If you're curious, look in the Python Language Reference at the old and new >> style classes to see the differences. There's absolutely no advantage to >> old style classes > >except performance: > >http://www.python.org/~jeremy/weblog/030506.html That's not a big difference, and in any case: http://www.python.org/doc/current/whatsnew/node17.html#SECTION00017200000000 00000000 Creation of new-style instances is faster. I seem to recall Alex Martelli also thinking that new-style classes are faster all-around. In any case, he's gung-ho on new-style classes, even more than I am. >> it's vital for understanding the still poorly-documented new-style classes. > >documentation may also be seen as an advantage, of course. True, but unless one is doing something elaborate (can't even think *what*) or relies on the old mro, the only difference is that base classes will derive from object. If there is code that depends upon the old mro, it should probably be fixed anyway. And it's probably not a problem. From "What's new in 2.3", section 16: """ The method resolution order used by new-style classes has changed, though you'll only notice the difference if you have a really complicated inheritance hierarchy. Classic classes are unaffected by this change. Python 2.2 originally used a topological sort of a class's ancestors, but 2.3 now uses the C3 algorithm as described in the paper ``A Monotonic Superclass Linearization for Dylan''. To understand the motivation for this change, read Michele Simionato's article ``Python 2.3 Method Resolution Order'', or read the thread on python-dev starting with the message at http://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele Pedroni first pointed out the problem and also implemented the fix by coding the C3 algorithm. """ So I still stand by the claim that one should stop using old-style classes. Changing old-style to new-style classes is more problematic, but I don't see that it's much more. If the code is old enough to use changed/depreciated pre-2.2 features, changing classic classes to new-style is the least of your problems. But if it's 2.2 code, the jump to 2.3 is small and nothing but an advantage--only a policy decision should keep anyone in 2.2. What are the serious compatibility problems with changing an old-style class to a new-style class (which I haven't encountered)? My understanding is that the headaches are from *mixing* classic and new-style classes in the same hieararchy. -- Francis Avila From miki.tebeka at zoran.com Tue Dec 30 07:51:33 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 30 Dec 2003 04:51:33 -0800 Subject: Compiler? References: Message-ID: <4f0a9fdb.0312300451.1d4dbc41@posting.google.com> Hello Jim, > I just heard about Python today. Is there a compiler for it, or does it > need to work through the interpreter only? I you mean a true compiler that translates Python code to machine language then I don't think there is (although Psyco comes very close). If you want to send your code to someone who don't have Python installed there are several solutions (py2exe, Installer, freeze ...). All of them bundle the interpreter in the package they create. HTH. Miki From bokr at oz.net Sun Dec 21 17:44:18 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Dec 2003 22:44:18 GMT Subject: memory overhead using from-import? References: <20031221102848.4f901801.wtrenker@shaw.ca> Message-ID: On Sun, 21 Dec 2003 11:31:49 +0000, William Trenker wrote: >William Trenker wrote: > >> Could someone please confirm that if I code the following line in my own module: >> from cgi import escape >> that the only additional memory overhead from the cgi module will be that required to store the escape function's code. > >After some experimenting with the /proc filesystem and a closer reading of the Python docs, I think I've answered my own question. It looks like from-import does import the entire module. So, >from cgi import escape >brings in the entire cgi module but only exposes the escape function to the importing module's namespace. > >The code, below, set me straight. > >Bill > >Python 2.3.2 (#1, Oct 27 2003, 10:19:56) >[GCC 2.95.3 20010315 (release)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import cgi >>>> import os,re >>>> pid = os.getpid() >>>> s = file('/proc/%s/status'%pid,'rb').read() >>>> print re.search('(VmSize:.*?kB).*(VmExe:.*?kB)',s,re.DOTALL).groups() >('VmSize:\t 5300 kB', 'VmExe:\t 712 kB') > >Python 2.3.2 (#1, Oct 27 2003, 10:19:56) >[GCC 2.95.3 20010315 (release)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> from cgi import escape >>>> import os, re >>>> pid = os.getpid() >>>> s = file('/proc/%s/status'%pid,'rb').read() >>>> print re.search('(VmSize:.*?kB).*(VmExe:.*?kB)',s,re.DOTALL).groups() >('VmSize:\t 5300 kB', 'VmExe:\t 712 kB') > I wonder if anyone has tried something like (not that it would avoid temporary memory usage (which might be returned to python free pools rather than the system), and it depends on escape not messing with globals, and who knows what entangling chains of reference there might be, but anyway): >>> execfile(r'D:\Python23\Lib\cgi.py', d) >>> escape = d.get('escape') >>> d.clear() >>> del d >>> help(escape) Help on function escape in module __main__: escape(s, quote=None) Replace special characters '&', '<' and '>' by SGML entities. Looks, accessible still, so >>> escape >>> escape('good site') '<a href="http://www.python.org">good site</a>' BTW, >>> import sys >>> 'cgi' in sys.modules.keys() False Alternatively, I guess some ambitious wizard could code up something so you could write thing, another = from_extract(modulename, thingname) in place of from modulename import thing, another to get the effect you want (or maybe an exception ;-) Regards, Bengt Richter From deets_noospaam at web.de Tue Dec 9 17:58:26 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 23:58:26 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> <2fsBb.423999$0v4.20388116@bgtnsc04-news.ops.worldnet.att.net> Message-ID: >> > filename = "C:\Python22\Canyon.mid" >> > os.system("C:\Python22\playb.exe%s"%filename) >> > ...this causes a dos box to appear which promptly hangs and does > nothing, >> > at which time Python stops responding. Vartiations on this will cause > the >> > dos box to appear with the message "Bad command or file name". >> > >> >> Looks like there is a space missing - >> >> os.system("C:\Python22\playb.exe %s"%filename) >> ^ >> >> Diez >> > There is no space missing. That is the name of the file on my comp. Ok, most probably you'll start to yell at me now, but _there is a space missing_: >>> filename = "C:\Python22\Canyon.mid" >>> print "C:\Python22\playb.exe%s"%filename C:\Python22\playb.exeC:\Python22\Canyon.mid I have no WinBox here - but I bet even windows likes its commandline arguments somehow separated from each other. Try executing the line above, and I bet command.com complains about "Bad command or file name". Diez From EP at zomething.com Mon Dec 22 11:15:05 2003 From: EP at zomething.com (EP) Date: Mon, 22 Dec 2003 08:15:05 -0800 Subject: calling the function police In-Reply-To: <20031222142227.GA21664@intarweb.us> References: <5.2.0.9.0.20031221223023.026e9ba8@mail.zomething.com> <5.2.0.9.0.20031221223023.026e9ba8@mail.zomething.com> Message-ID: <5.2.0.9.0.20031222080423.00b7a690@mail.zomething.com> > > >>> result=function1('Jim Beam', 'Poker',first=parameter,end='noodles') > > > > and got this error: > > > > >TypeError: function1() got multiple values for keyword argument 'first' > > > > 'Jim Beam' is passed as an argument for "first". 'Poker' as an argument >for "end". Then, parameter is passed as an argument for "first", and >'noodles' as an argument for "end". No arguments are passed for the >*argument (I forget what it was called in your example). > > In general, the first argument matches up with the first parameter, the >second with the second, and so forth. This seems to be what is happening but does not seem compatible with the rules (or maybe my expectations): 1) keyword arguments must appear after non-keyword arguments in the call. 2) in the function header, *arguments must come after normal arguments and defaults If I am concluding correctly, this means that keywords cannot be used in a function call for a function header like this def function(value1=x, value2=y, *arguments) Is that right? the two rules mean that keywords will out of "position", source to target; but why would keywords have to be accessed by position, aren't they akin to a dictionary? Not a terrible limitation, was just not expected. Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From eltronic at juno.com Tue Dec 30 16:36:45 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Tue, 30 Dec 2003 16:36:45 -0500 Subject: Project dream Message-ID: <20031230.163649.-231021.3.eltronic@juno.com> On 26 Dec 2003 12:36:48 -0800 hwlgw at NOSPAMhotmail.com (Will Stuyvesant) writes: > Suppose you have the time and the money to start a new project in > Python. What would you like to do? > - An easy to use tool for drawing diagrams, typically > various kinds of arrows and circles and boxes, > that produces nice .eps and .svg files. there was posted a few months back a one file program that let you draw simple flowchart like shapes, move them, resize them. the name, gui & url escapes me now. > - Something for weblogging and todo things, probably via CGI. this is easily a contender for the top overcrowded python application category. I would suggest a moratorium on new projects for a few months to research better names, improve doc strings and documentation, add examples & tests, rclick, provide better API compatibility with existing applications to ease relearn & reuse problems and add external scripting ability to existing applications. usability 101. better names would imply higher score in searches and could cut the number of duplicate started projects. not that all the duplication of effort is wasted. part of what makes python so much fun is that you can whip up a solution from nothing sometimes faster than researching what is available. probably only 10% of the one off scripts posted to c.l.py have the simplest docstring describing what it does and where to get an update if it becomes available. great that people make this available so is just an observation. > What would your favorite be? a timer capable of alarms or starting programs with various ways of specifying the event, weekly monthly don't start untill, stop after date, user defined, etc. b sorting out the os.py mess under "msys" the bash shell for mingw32. is it posix is it win32, are they forwardslash, backslashes or mixed, will python itself ever compile clean in mingw, will readline or any of the 10 variants available ever work without incompatible patching and knashing of teeth. the path to hell is paved with claims of backward compatibility. it is a wonder that as much works as does work so well. but as a dream funded project, this would get my vote. e please forward all spam to "me" ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From vze4rx4y at verizon.net Wed Dec 3 17:43:05 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 03 Dec 2003 22:43:05 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: [Bengt Richter] > >> > Please can we have a name that better expresses the functionality? > >> > > >> > E.g., 'keyfunc', or 'xform' or something that says the method is expecting > >> > a function that will be called with the sorting argument to produce the > >value > >> > used in sorting? "key=" doesn't do it IMO. [Raymond] > >cmpfunc= and keyfunc= were both suggested by several non-Dutch such as myself. > > > >Then, Guido rightly pointed out that the keywords should just be pithy memory > >joggers. Taken in that light, key= and cmp= do the job nicely. [Bengt Richter] > Excuses, rationalizations. I don't wan't to incite a contest, but IMO "key=" is misleading ;-) Since these keywords may take root and sprout-up in several places, now is the time to take action and send your suggestion to either python-dev or to the BDFL. At first, I also didn't like the short forms, but now they feel right as rain -- meaning that I now think it was the right way to go. signature(as_long_hyphenated="good luck on the crusade")-ly yours, Raymond Hettinger Raymond From janeaustine50 at hotmail.com Tue Dec 2 02:06:34 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 1 Dec 2003 23:06:34 -0800 Subject: python's threading has no "interrupt"? References: Message-ID: janeaustine50 at hotmail.com (Jane Austine) wrote in message news:... > As far as I know python's threading module models after Java's. > However, I can't find something equivalent to Java's interrupt and > isInterrupted methods, along with InterruptedException. > "somethread.interrupt()" will wake somethread up when it's in > sleeping/waiting state. > > Is there any way of doing this with python's thread? I suppose thread > interrupt is a very primitive functionality for stopping a blocked > thread. > > Jane Well, I haven't got any answer since I posted it. Meanwhile, I have been searching for it myself. Something new has been added in 2.3 in thread module. That's interrupt_main. But, unfortunately, it is the opposite of what I expected; It interrupts the main thread. After all this, I am a bit disappointed about Python. (it's sad) Jane From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 24 11:38:41 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 24 Dec 2003 17:38:41 +0100 Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: python newbie: >Does anyone currently develop in wxPython and if so, are you using a >dependable tool for debugging in this? I use WingIDE, and it says it supports wxPython: http://wingide.com/doc/wxpython But I haven't developed wxPython programs yet, so I can't vouch for it. -- Ren? Pijlman From jetman516 at hotmail.com Sat Dec 27 17:24:29 2003 From: jetman516 at hotmail.com (The Jetman) Date: 27 Dec 2003 14:24:29 -0800 Subject: Using python to check the status of a program References: Message-ID: Kamuela Franco wrote in message news:... > I would like to use a Python script to periodically check to see if a > program is still running and if it isn't I want to start it up. Could > someone point me on the right path? Thanks in advance. > > Kamuela 1st, which OS are we talking about ? *IF* we're talking about Linux/Unix/FreeBSD, then it only takes a few lines: import os import string f = os.popen( 'ps -ax' ) s = f.readlines() if string.find( s, 'target_pgm' ) > -1: #### we found it, so do something.... If we're talking about Windows, then this would work using the Cygwin utils for ps or one could try Pythonwin. Mark has ported many Windows APIs, so it would be a little more involved, but straight-fwd. HTH....Jet From and-google at doxdesk.com Sun Dec 14 07:28:20 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 14 Dec 2003 04:28:20 -0800 Subject: beginner python cgi question References: <3fdaf1df$0$17571$9b4e6d93@newsread4.arcor-online.net> Message-ID: <2c60a528.0312140428.42e1af3d@posting.google.com> Jochen Wersd?rfer wrote: > Address = fields.get("address", "n/a") (You mean fields.getvalue, natch.) If you don't want to have to deal with cgi returning a list sometimes, what you really want is fields.getfirst('fieldname', 'default'), but this only exists in Python 2.2 onwards. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From jay at jaydorsey.com Sat Dec 6 16:04:56 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sat, 6 Dec 2003 15:04:56 -0600 Subject: Help: Uploading .zip to Python CGI In-Reply-To: References: Message-ID: <20031206210456.GA29197@gentoo.Earthlink.net> On Sat, Dec 06, 2003 at 12:40:43PM -0800, Will Stuyvesant wrote: > I am uploading a .zip file to a Python CGI program, using a form on > a HTML page with > Without being able to see the form, I wonder if you're certain you set the enctype on the form to "multipart/form-data"? You're working across multiple servers and if you're retyping the script each time its easy to forget the enctype of the form. HTH -- Jay Dorsey jay at jaydorsey dot com From gagenellina at softlab.com.ar Fri Dec 26 20:04:23 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2003 22:04:23 -0300 Subject: ProtoCiv: porting Freeciv to Python In-Reply-To: References: Message-ID: <5.2.1.1.0.20031226215958.0202ab30@192.168.0.115> At 25/12/2003 10:45, you wrote: >Show us the money. Let us know when there's something to see. >Until that point, you might heed the advice here: >http://www.sloperama.com/advice/lesson24.html#tal >Scroll to entry 16 if your browser doesn't go for you (Opera, for >example). That's because the tag is wrong, should be instead of . The # is not part of the name but a separator. Given that markup, you could jump directly with http://www.sloperama.com/advice/lesson24.html##tal (Sorry the offtopic...) Gabriel Genellina Softlab SRL From tesserfamily at yahoo.com Fri Dec 19 10:03:39 2003 From: tesserfamily at yahoo.com (Jason Tesser) Date: Fri, 19 Dec 2003 07:03:39 -0800 (PST) Subject: dynamic typing questions Message-ID: <20031219150339.63883.qmail@web60401.mail.yahoo.com> I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from registration to business office. We are considering useing Java or Python. I for one don't like Java because I feel the GUI is clunky. I also think that we could produce quality programs faster in Python. The other programmer here is very concerned about dynamic typing though in Python. He feels like this would be too much of a hinderance on us and too easy for us to make a mistake and not catch it until runtime making debugging harder. OK what are your guys thoughts here? How have you all overcome the lack of static typing? Is Python a bad decision here? By the way we will be using Postgres in the back if that matters to anyone. From halloleo at noospaam.myrealbox.com Tue Dec 16 00:44:01 2003 From: halloleo at noospaam.myrealbox.com (leo) Date: Tue, 16 Dec 2003 16:44:01 +1100 Subject: ZSI ans PyXML version Message-ID: hi there i want to write a little SOAP client and thought about using ZSI. now i have read that ZSI only works with PyXML versions later than 0.6 and earlier than 0.7. unfortunaltly i can find that old versioons of PyXML on sourceforge any more... any ideas? thanks, leo From ny_r_marquez at yahoo.com Mon Dec 8 14:37:00 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 8 Dec 2003 11:37:00 -0800 Subject: Explorer Shell extensions are here! Message-ID: <8a27e309.0312081137.18c2810b@posting.google.com> I just happened to bump into this today when I went to the Win32 Python Extensions page. I think the M.H. and his team are a bit too modest. Quote: "win32com.shell grows many more interfaces, allowing Python to operate as a nearly complete shell extension, and to interact with the shell interfaces. See the win32comext\shell\demos\server directory for examples." This is something I had been waiting for a while, and even submited a "feature request" about it. So, since I hadn't heard any thing about it, I figure there may be a few more like me that would enjoy knowing about this. (Now, if I could only figure out how to make a context menu that would show up for any file of folder... ;) -Ruben From marklists at mceahern.com Tue Dec 9 23:30:19 2003 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 09 Dec 2003 22:30:19 -0600 Subject: exit code on windows Message-ID: <1071030618.11531.59.camel@dev.internal> Is there a straightforward way to get the exit code from a windows process? I want to write a script that runs a bunch of .sql files against SQL Server using osql. I want it to stop if there's an error; e.g., import os import glob server = 'foo' database = 'bar' template = 'osql -s%(server)s -d%(database)s -f%(name)s' for name in glob.glob('*.sql'): cmd = template % locals() stdin, stdout = os.popen2(cmd) output = stdout.read() print stdin.close() print stdout.close() # On Unix I'd use the return value from the fd.close() # to get the exit code, but on Windows the return values # here are: # None # None Does that mean the way I'd get the exit code on Unix has no hope of working on Windows? Thanks, // m From max at cNvOiSsiPoAnMtech.com Tue Dec 9 09:38:20 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Tue, 09 Dec 2003 14:38:20 GMT Subject: Python progamming certification In-Reply-To: References: Message-ID: > to know it once existed because I WROTE it. COOL! BTW they still offer the 1.5 test. That said, I was > *extremely* unimpressed with BrainBench's test design--I have a > background in testing theory (and practice). Don't tell me you too cheated on your SATs :) I did the best possible > within their guidelines, but the best possible was still not > particularly good. > > If you just want a piece of paper, I suppose it doesn't matter how bad a > test is. If you want the certification to actually show something about > takers' abilities... well, don't bother with BrainBench. I should just mention that I got hit up for an interview last week due to my BrainBench C++ test. So they are not entirely worthless (even though there were syntax errors in the test itself). I do not know if the Python test is worth the $45 they are charging from that perspective since I suspect very few potential employers will be looking for Python programmers on BrainBench. From http Tue Dec 30 14:52:01 2003 From: http (Paul Rubin) Date: 30 Dec 2003 11:52:01 -0800 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> <87ad5a2s08.fsf@strauser.com> Message-ID: <7x1xqmccda.fsf@ruckus.brouhaha.com> Kirk Strauser writes: > For production use, I'd factor out the 're' stuff (for performance) and add > descriptive variable names (it doesn't cost anything) like so: > > import re > hexpattern = re.compile(r'[0123456789abcdefABCDEF]*$') > ... > That way, the pattern is only compiled once. It normally only gets compiled once anyway, then cached. If you have a really large number of different regexps I guess the cache can overflow and recompilation happens. From abulka at netspace.net.au Tue Dec 30 18:43:25 2003 From: abulka at netspace.net.au (Andy Bulka) Date: 30 Dec 2003 15:43:25 -0800 Subject: UML tools for python Message-ID: <13dc97b8.0312301543.39192aa2@posting.google.com> Whilst almost responding to the 'dream project' thread I decided that this post warranted its own thread. What about a solid UML tool with round trip functionality for the Python Community? Some attempts at reverse engineering python are PyReverse http://www.logilab.org/projects/pyreverse/ PyUt http://pyut.sourceforge.net/ PyNSource http://www.atug.com/andypatterns/pynsource.htm Boa Constructor http://sourceforge.net/projects/boa-constructor/ IDLE's class browser PythonWin 's class browser all of which have their problems and limitations. E.g. PyUt will hang if it cannot __import__ successfully and its GUI has no zoom nor scroll etc. PyReverse is hard to use, misses a lot of basic information and then what do you do with the XML files? - who will read these? I have to edit them manually to import them into Enterprise Architect http://www.sparxsystems.com.au and the last time I tried, you couldn't import into Poseidon http://www.gentleware.com/products/index.php4 community edition, which is the better descendant of the free Argo. Some Java-centric UML tools I believe do export python, though this is usually very simple and usually broken. For example Object Domain http://www.objectdomain.com/products/od/overview.do claims to import python code, but the last I looked, this particular functionality was fragile. Potential powerful technology that could be used is Bicycle Repair Man http://bicyclerepair.sourceforge.net/ a refactoring tool for Python which could be combined with some sort of Java GUI (with zoom and all those niceties) - since the hard bit of the problem is parsing python reliably and knowing how to change it / regenerate it nicely. Bicycle Repair Man already treads deeply in this territory. Also PyChecker http://pychecker.sf.net/ walks similar territory. Ideal tools would look and behave something like ModelMaker (for Delphi) http://www.modelmakertools.com/ TogetherJ http://www.togethersoft.com/products/index.jsp where you can work in code or in diagrams and the two are seamlessly kept in synch. Its truly cool, and I wish I could do these sorts of things in Python. Does anybody know of any other work being done in this area? Do we think that having a solid UML tool with full round trip facilities plus gorgeous GUI - build specifically for Python is a worthy goal? Is anybody going to bother to build such a tool for free? Andy Bulka http://www.atug.com/andypatterns From hs at bluepacific-technologies.com Sun Dec 14 14:39:52 2003 From: hs at bluepacific-technologies.com (SamX) Date: 14 Dec 2003 11:39:52 -0800 Subject: piddle Message-ID: <31e18870.0312141139.4200d519@posting.google.com> Can PIDDLE plot 3D geometry? such as a set of x, y, z points? This is to plot a 3D fan blade by a set of sections. Each section is specified by a set of x, y coordinates and a z coordinate. Ideally, there will be a coordinate at the origin, the points can be connected by straight lines or even splines, and one can rotate, pan and zoom the display. If Pidlle can not do this, is there another package that can? Thank you in advance From newsgroups at jhrothjr.com Sat Dec 20 07:55:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 07:55:42 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Ville Vainio" wrote in message news:du7r7yzzmw6.fsf at mozart.cc.tut.fi... > "John Roth" writes: > > > > > a third is the ability to forget the empty parenthesis after > > > > a function/method call that doesn't require parameters. > > > > Doesn't this suck big time? How can the interpreter tell whether you > > > are trying to call a function or just want a reference to a callable > > > object? > > > That's the crux of the implementation issue, and I, for one, > > haven't got an answer that doesn't look real ugly (let alone > > break backwards compatability.) That's why I'm not pushing > > this particular issue seriously - I don't see a way of doing it, > > given the rest of Python, and completely independently of any > > "Python philosophy" issues. > > Most importantly, why would anyone even care? Ability to optionally > invoke a "call" operation on an object implicitly seems utterly > worthless to me. That may not be one of your common coding mistakes. My mind doesn't quite get the point of inserting an otherwise useless pair of parenthesis, and consequently it's fairly high on the list of common coding errors I make that causes run time errors. Of course, rigidly applying TDD will bring those errors up rapidly so they don't lurk to cause problems later, but not having them in the first place would be even better. There's a Japanese term used in Lean Manufacturing that basically translates as "mistake proofing." While Python makes it harder to make mistakes than many other languages, it is certainly not perfect in that respect, and this issue is one of several that fall into that category. > It has the feel of perl philosophy (regexps in > language syntaxm anyone? ), and it's not the only instance in Ruby. I > don't really like the Perl philosophy (like most of the people who > "get" Python), and I don't really believe a language whose designers > appreciate the perlisms poses a serious threat to Python. Not even if > they got some things right. I suspect you're missing the point. I'm not advocating Ruby, which has, as far as I am concerned, enough problems that I'm not considering shifting at this time. What I am advocating is looking at what it's doing right and asking if some of those things might not improve Python. > > to Python. Maybe the fact that such industry heavy hitters as Robert > > Martin, David Thomas, and any number of others have switched > > Frankly, I don't know who these "heavy hitters" are, but they probably > have their reasons. Quick googling didn't turn out any useful articles > explaining why either of them has switched from Python to Ruby. Let's see. Dave (the Pragmatic Programmer) wrote the textbook on Ruby, and I think his preface says it quite nicely. > > As far as doing the "right" thing, check the partial list of Ruby > > features I gave, and ask yourself how much each of them would > > break the "feel" of Python. > > I am yet to see a feature list that would inspire me to switch, or > even consider switching. The little advantages Ruby has over Python > are dwarfed by the advantages of Python (of which the least is not > maturity, community and documentation). As I said, my intent is not to inspire anyone to switch. My intent is to ask whether there is anything they're doing that would be (in concept if not in implementation) an improvement to Python. John Roth > > -- > Ville Vainio http://www.students.tut.fi/~vainio24 From dave at pythonapocrypha.com Fri Dec 12 12:56:58 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 12 Dec 2003 10:56:58 -0700 Subject: win32 socket, "Operation not supported" References: Message-ID: <024901c3c0d9$56f6ffd0$891e140a@YODA> David wrote: > I have written an app which opens a TCP connection to a server and uses a protocol to communicate with it. > Specifically, I've written a python IMD client for the molecular dynamics application 'NAMD' (do searches for > IMD and NAMD if you want to learn more). > > The protocol is very simple: both ends of the TCP connection can send messages to the other side at any time; when data is > available on a read socket, a full packet (with known size) is read in a blocking fashion from the socket. Are you doing a select or poll on the socket to ensure the read won't block? (not relevent to your problem, just trying to understand your program) > However, on Windows, I can connect and complete the initial handshake, and receive periodic updates, but when I try to >send a message > to the server, socket.send gets an "Operation not supported". > > >From my reading of the win32 docs, the socket send call returns this in a couple of situations: > when a two-way socket had one half shut down and the send would have used the shut down direction, or > when an out of band message was sent on a socket type which does not support it (such as UDP). > > Neither of these situations are true. When I re-code the app in C, the problem doesn't occur. Anybody got some suggestions? > (PS: the socket I/O is set to blocking, and the Nagle algorithm is disabled). Could you send a stripped-down version of the Python code? If nothing else, other Windows users can try it out too and report back their results. -Dave From werner.warweg at t-online.de Mon Dec 29 00:53:34 2003 From: werner.warweg at t-online.de (Werner.Warweg) Date: Mon, 29 Dec 2003 06:53:34 +0100 Subject: Python deutsch Message-ID: Das Musikprogramm Capella nutzt Python. Ich habe mir die Sprache mal angesehen und m?chte mich damit n?her besch?ftigen. Ich mu? beruflich XP verwenden. Kann mir einer der deutsprachigen Group-Teilnehmer empfehlen: - welche deutschen B?cher? - welche Newsgroup ist die beste? Es gibt so viele! - Ich habe Cobol und Basic immer gern durch Beispielprogramme gelernt. Wo kann ich eine kleine Dateiverwaltung finden (anlegen, ?ndern, l?schen, drucken) z. B. von einem Rechnungsausgangsbuch (Nummer, Betrag, Empf?nger), damit unterschiedliche Datentypen angesprochen werden? Vielen Dank an die .de-IT-ler. MfG Werner Warweg From bkelley at wi.mit.edu Wed Dec 17 10:49:27 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 17 Dec 2003 10:49:27 -0500 Subject: How to access MFC classes in Python using SWIG ? In-Reply-To: <87zndsyja5.fsf@pobox.com> References: <87zndsyja5.fsf@pobox.com> Message-ID: <3fe07ab5$0$579$b45e6eb0@senator-bedfellow.mit.edu> John J. Lee wrote: > harry_chillboy at rediffmail.com (Harish) writes: > > >>I am using Python2.3 version with SWIG-1.3.19 to access C++ interface >>provided by a DLL. >>Some of its function returns MFC class objects like CString , CMap. I >>tried to generate wrapper for these classes using SWIG by including >>respective header files in .i file. >>But it doesn't work. Swig reports hundreds parsing errors in MFC's >>file. the ctypes package may do what you want http://starship.python.net/crew/theller/ctypes/tutorial.html Brian From hjwidmaier at web.de Wed Dec 31 12:19:00 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Wed, 31 Dec 2003 18:19:00 +0100 Subject: Graceful failures References: <85b54e91.0312291414.6e61e535@posting.google.com> Message-ID: It is quite a coincidence that a thread like this pops up right when I feel I have to start one - with almost exactly the same subject - myself. Error handling can easily be the hardest task in a program, and that's why its being neglected most of the time. Am Wed, 31 Dec 2003 05:28:08 +0000 schrieb Samuel Walters: > My "dream error dialog box" would do the following: > > Tell the user in a very neutral and nontechnical manner that it has > encountered a problem and tell the user what it was trying to do when it > failed. > > for instance: > """ > Foo has encountered a problem. > Foo was unable to load the necessary images to continue. > """ I would like it much more detailled, like: """ Foo has encountered a problem. It was trying to load a necessary image from the file '/usr/share/Foo/images/up.png'. This file does apparently not exist. The problem may be caused by a broken installation of Foo. Alas, Foo cannot be continued and will be closed. """ (I'm not the best error message designer, but I hope you get the point: Tell exactly *what* is missing, so an even moderatly experienced user can try to fix it. I *hate* messages like "Cannot find image". What image? Where is it supposed to be?) > The error dialog box should allow the user the option of viewing > technical details, but should clearly label them as technical details. Which means the details I want go there - fine with me. > If possible, the user should be presented with possible courses of > action to correct the problem. +1 > Finally, I really, really wish that users were presented with the option > of being automagically taken to the technical support website where > they're allowed to see and discuss with others how to solve their > particular problem. [snip] This, of course, is a bit overkill for a little freeware program, but sounds good for a "big" application with a hefty price tag. Handling every conceivable error right is quite a challenge and lots of work, especially in the test department. Hans-Joachim Widmaier From bvdpoel at kootenay.com Mon Dec 29 21:48:08 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Mon, 29 Dec 2003 19:48:08 -0700 Subject: When to put my modules Message-ID: <3ff0e744_1@dns.sd54.bc.ca> I'm working on a moderately sized application and I'm planning on having a fair number of modules. The only question in my mind is: where do I put the modules ... and how do I let python know about them? I could put them with the rest of the python lib, but I'm not really presumtious to do that. I can keep them all in the current directory, but that forces the user to chd to a certain location all the time. Best, I think, is to put them in a program specific location. My program needs some other data files, etc. so I'm thinking that I can just put the python stuff in /usr/local/lib/MYPROGRAM/modules. Okay, but what about when I'm just working on them? In this case I'd like them to be in my current working dir. Is there a magic line I need to add to the top of the main module to set the path up? Apologies if this is covered in a document...but I can't see to find anything. Maybe this is a faq? -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From tim.jarman at lineone.net Mon Dec 8 15:05:30 2003 From: tim.jarman at lineone.net (Tim Jarman) Date: Mon, 8 Dec 2003 20:05:30 +0000 Subject: Case sensitive and ludicrous statements In-Reply-To: References: Message-ID: <200312082005.30643.tim.jarman@lineone.net> On Sunday 07 Dec 2003 8:53 pm, Douglas Alan wrote: [snip] > > You will notice that CamelCase was extremely uncommon (if used at all) > before the advent of case-sensitive languages, and there is good > reason for this. It didn't make sense then, and it doesn't make sense > now! (In a case-insensitive language.) > > |>oug Er, I may be missing something, but why is this enthralling discussion taking place in a newsgroup devoted to a case-*sensitive* language? Is this an attempt to wind up the Martellibot or something? From ahmed.mohamed.edigram at wanadoo.fr Fri Dec 19 12:47:01 2003 From: ahmed.mohamed.edigram at wanadoo.fr (Ahmed MOHAMED ALI) Date: Fri, 19 Dec 2003 18:47:01 +0100 Subject: SQL Server Questions References: Message-ID: Hello, if you do MSSQL.connect('my_server', 'my_username', 'my_password', '[my database]') that will work Ahmed "Lindstrom Greg - glinds" wrote in message news:mailman.351.1071842936.9307.python-list at python.org... > Hello- > I am connecting to a Microsoft SQL Server (6.0) via Python 2.3 using the > MSSQL package and have a question about the database name. This particular > database was designed with a two-word name (i.e. "My Database"). When I > try to connect using the MSSQL.connect method, I get a syntax error: > > MSSQL.connect('my_server', 'my_username', 'my_password', 'my > database') > > I get an "Incorrect syntax near My" error. I can't change the name of the > database; too many applications are feeding into it. What do I do? > > Also, I'm connecting to a Microsoft Exchange Mail server using the methods > described in Mark Hammond and Andy Robinson's Book "Python Programming on > Win 32". My problem is that when I connect to the Exchange Server, a dialog > box pops up to verify the connection. Since I'm writing a utility script, > I'd just like to connect without a user having to get involved. Is this > possible? > > Thanks for your help > --greg > > > > > ********************************************************************** > The information contained in this communication is > confidential, is intended only for the use of the recipient > named above, and may be legally privileged. > If the reader of this message is not 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 re-send this communication to the sender and > delete the original message or any copy of it from your > computer system. Thank You. > > From bokr at oz.net Wed Dec 24 15:42:54 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Dec 2003 20:42:54 GMT Subject: Operator overloading and __getattr__ References: Message-ID: On Tue, 23 Dec 2003 11:22:28 -0500, "John Roth" wrote: > >"Samuel Kleiner" wrote in message >news:slrnbue5dp.72h.sam at h41n2fls31o839.telia.com... >> I'm trying to create methods on method access- but __getattr__ fails >> with operator overloading(below) Any suggestions? EG: > >I haven't a clue what you're trying to do, but >I believe it's not possible to install "magic methods" >after the class is defined. Nor can you install >them in the instance. They'll look like they've >been installed, but the interpreter will never >execute them because it does not look there >for them. It looks in special places in the C >language structure for the class definition. > I'm not sure what you mean about not installing methods, but methods are effectively dynamically created when you access functions via a class attribute name, so you can tack them on any time before you access them. If you access them via a class attribute per se, you get an unbound method, and if you access them via a class instance, you get a bound (to that instance) method. E.g., >>> class A(object): pass ... >>> class B(object): pass ... >>> a=A(); b=B() >>> def method_name(self): return 'This is from a method of %s'% self.__class__.__name__ ... >>> A.foo = B.foo = method_name >>> A.foo >>> B.foo >>> a.foo > >>> b.foo > >>> a.foo() 'This is from a method of A' >>> b.foo() 'This is from a method of B' Note the distiction between 'foo' and 'method_name'. Once 'foo' has been used to create the method, only the name of the function is available via the (un)bound method object reference. They happen to match when you do the def inside the class scope, but they don't have to, though the repr string might be a little confusing when they don't. If you use a programming trick to get the function bound as an attribute of a class, that should work just like doing it explicitly as above. Note that the unbound method is not just a reference to the function: >>> A.foo(a) 'This is from a method of A' >>> A.foo(b) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method method_name() must be called with A instance as first argument (got B instance instead) Though you can sneak around to it: >>> A.foo.im_func And it happens to work as a function >>> A.foo.im_func(b) 'This is from a method of B' To get that function we see via A to be an unbound method of B is also possible: >>> A.foo.im_func.__get__(None, B) >>> A.foo.im_func.__get__(None, B)(b) 'This is from a method of B' >>> A.foo.im_func.__get__(None, B)(a) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method method_name() must be called with B instance as first argument (got A instance instead) Regards, Bengt Richter From max at alcyone.com Wed Dec 3 04:54:11 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 03 Dec 2003 01:54:11 -0800 Subject: redirecting Stdin References: Message-ID: <3FCDB2C3.B87DE2BE@alcyone.com> Jon Arter wrote: > Is is Possible to redirect the Python stdin in order to receive stdin > commands from a file ? > The time of redirection can last until exiting the Python and should > be transparent for python it self. Sure: sys.stdin = file('newinput') -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ The map is not the territory. -- Alfred Korzybski From gerrit at nl.linux.org Tue Dec 23 17:17:24 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 23 Dec 2003 23:17:24 +0100 Subject: PIL: jpeg comment Message-ID: <20031223221724.GA2701@nl.linux.org> Hi, how do I read a JPEG comment with the Python Imaging Library? yours, Gerrit Holl. -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From sombDELETE at pobox.ru Mon Dec 15 16:13:30 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Tue, 16 Dec 2003 00:13:30 +0300 Subject: codecs latin1 unicode standard output file References: Message-ID: "Marko Faldix" wrote in message news:brkddv$4evj2$1 at ID-108329.news.uni-berlin.de... > > > In my point of view python shouldn't act in different ways whether > result is > > > piped to file or not. > > > > when you print to a console with a known encoding, Python 2.3 auto- > > magically converts Unicode strings to 8-bit strings using the console > > encoding. > > > > files don't have an encoding, which is why the second case fails. > > > > also note that in 2.2 and earlier, you example always failed. > > > > > > So I just have to use only this: > > print "My umlauts are ?, ?, ?" > > without any encoding-assignment to use for standard output on console AND > redirecting to file. In latter case, it looks nice with e.g. notepad, just > strange on console, so settings for console are to adjust and not python > code. Right? No, the right code is ============================= # -*- coding: iso-8859-1 -*- import locale, codecs, sys if not sys.stdout.isatty(): sys.stdout = codecs.lookup(locale.getpreferedencoding())[3](sys.stdout) print u"My umlauts are ?, ?, ?" ============================= The difference between console and file output is that while there's only one way to output ? on cp850 console, there are many ways to output the same character to file (latin-1, utf-8, utf-7, utf-16le, utf-16be, cp850 and maybe more). So python refuses to guess. Another rule to follow is to store non-ascii character in unicode strings. Otherwise either you will have to track the encodings yourself or assume that all 8-bits strings in your program have the same encoding. That's not a good idea. I'm not sure if you will have proper .upper() and .lower() methods on 8-bit strings. (don't have python here to check) -- Serge. From donn at drizzle.com Sat Dec 20 17:46:10 2003 From: donn at drizzle.com (Donn Cave) Date: Sat, 20 Dec 2003 22:46:10 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: <1071960369.839620@yasure> Quoth "John Roth" : ... | The world changes, and ideas that seemed to be perfectly appropriate | five or ten years ago may no longer be such. Small languages with a limited | audience have a perfect right to be as quirky or as "pure" as their authors | want. Once they get beyond that point, there's a bit of social responsibility | involved in addressing common problems. For some definition of "common problems", that might be somewhat true, though perhaps stretching it a bit even at that. We are after all talking about free as in beer. The things we seem to be discussing in this thread do not at all meet the definition I have in mind. The main point when evaluating a "common problem" in this context is whether it's really a problem. Donn From hungjunglu at yahoo.com Wed Dec 3 15:59:11 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 Dec 2003 12:59:11 -0800 Subject: passing global data to a function References: <3064b51d.0312010855.66f4e2@posting.google.com> Message-ID: <8ef9bea6.0312031259.276c8400@posting.google.com> beliavsky at aol.com wrote in message news:<3064b51d.0312010855.66f4e2 at posting.google.com>... > How can I pass global data to function stored in a separate file? > For example, in file "funk.py" is the code > > ipow = 2 > def xpow(xx): return xx**ipow > > and in "xfunk.py" is the code > > from funk import xpow,ipow > xx = 4.0 > print xpow(xx) > ipow = 3 > print xpow(xx) I am a bit tired of the standard answer, so let us try a funkier approach! :) # funk.py ipow = 2 def xpow(xx): return xx**ipow # xfunk.py import inspect, funk exec inspect.getsource(funk) xx = 4.0 print xpow(xx) ipow = 3 print xpow(xx) And if you want trace information and be able to step through in a debugger, you can use: # funk.py ipow = 2 def xpow(xx): xx = xx / 0 return xx**ipow # xfunk.py import inspect, funk exec compile(inspect.getsource(funk), inspect.getabsfile(funk), 'exec') xx = 4.0 print xpow(xx) regards, Hung Jung From bdesth.tagada at tsoin-tsoin.free.fr Wed Dec 17 07:05:14 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Wed, 17 Dec 2003 13:05:14 +0100 Subject: OO issues in python In-Reply-To: References: Message-ID: <3fe04232$0$7131$626a54ce@news.free.fr> Ali El Dada wrote: > hi all: > > in python, when a class, say Father, has a member that itself is an > instance of another class, say Child, an instance of Father actually > only has a reference to a Child, not the Child object itself, right? I'm not sure I get the point. With Python, you only have symbols that are bounds to objects. > because i know that in eiffel they give the programmer the 2 options, > the second being implemented with an additional keyword (expanded) so as > the eiffel documentation says, > > "Consider the example of a class covering the notion of car. Many cars > share the same originating_plant , but an engine belongs to just one > car. References represent the modeling relation "knows about"; > subobjects, as permitted by expanded types, represent the relation "has > part", also known as aggregation. The key difference is that sharing is > possible in the former case but not in the latter" No such thing in Python. But it comes down to : 1/ an object A is 'shared' by many others B* (composition) : you instanciate A, and pass it to each B that needs to 'know about' it. 2/ an object A is 'part of' an object B (aggregation) : B instanciate A, and no one else keeps a reference to A. > the reason why i'm asking is that i want my Child() instance to know > things about the parent without having to explicitly pass them as > arguments. This seems quite a different problem. AFAICT, the Eiffel mechanism you mention don't let 'part' objects know anything about the object that 'own' them (I may be wrong since I don't know Eiffel that much, but...). > this is not working :( I can't see how it could work. A object instance can only know what you let it know, so unless you pass it a ref to another object, it can't know nothing about it. > eg code that doesn't work: > > class Father: > > def __init__(self): > self.a = 'foo' > self.son = Child() > > class Child: > > def __init__(self): > print f.a where is this 'f' coming from ?-) > > f = Father() > How would you expect the Child *class* to know anything about a symbol that is yet unbound ? You have two options : 1/ class Father: def __init__(self): self.a = a self.son = Child(self) def doIt(self): self.son.somethingElse() class Child: def __init__(self, father): self.father = father print self.father.a def somethingElse(self): print self.father.a 2/ class Father: def __init__(self): self.a = a self.son = Child(self) def doIt(self): self.son.somethingElse(self) class Child: def __init__(self, father): print father.a def somethingElse(self, father): print father.a Note that - with the first solution, you create a circular reference between Father and Child instances - but Python now has a real GC that handle such situations, so this may not be a problem. - with the second solution, you can pass any other Father-like object to a Child instance, which may or may not be a problem. Now there is no "Good" or "Bad" solution, it depends on the problem at hand. HTH Bruno From jjl at pobox.com Sat Dec 6 10:48:27 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Dec 2003 15:48:27 +0000 Subject: How to tell the difference between string and list References: <877k1bmc2g.fsf@pobox.com> <87r7zjui71.fsf@pobox.com> Message-ID: <87brqmx7zo.fsf@pobox.com> bokr at oz.net (Bengt Richter) writes: > On 05 Dec 2003 20:24:02 +0000, jjl at pobox.com (John J. Lee) wrote: > > >bokr at oz.net (Bengt Richter) writes: > >[...] > >> >>> s2 = ['abc','def'] > >[...]> > >> >>> s2 += 'ghi' > >> >>> s2 > >> ['abc', 'def', 'g', 'h', 'i'] > > > >That's not what the code I posted tests for. > > You mean __iadd__? I know, I was just showing ordinary list > behavior, and showed that as well to imply that that's also > something you might want to override in a consistent way if you were > overriding __add__ as in my example. What? list.__add__(self, "") raises TypeError, which means lists do work OK with isstringlike(). [...] > Don't forget, an object's __add__ could be defined to accept > _anything_ for addition, and a string would just be a generic thing, > whose stringness was really irrelevant to the adding object. Are you > making other assumptions based on isstringlike? That's true: especially given the sequence-ness of strings, which was the whole motivation for this function in the first place! In fact, isstringlike(UserList()) is true. Bah. > If so, I think those assumptions should be an explicit part of the > test, or you are setting yourself up for using the test and assuming > the wrong things about some object. You can say you'll use > exceptions will sort those things out, [...] Well, sometimes that's just the problem: exceptions *won't* get raised, because strings are sequences. I guess it's all depends on the particular case. :-( John From mbabcock at fibrespeed.net Mon Dec 8 12:49:00 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 08 Dec 2003 12:49:00 -0500 Subject: Class problem In-Reply-To: References: Message-ID: <3FD4B98C.8000905@fibrespeed.net> > Hello. I'm currently trying to create my first class in python, but > I've ran into a bit of a problem which I fear may just be a simple > error. I created a class called ImagePyramid.py which currently only > contains an _init_ method which takes in 2 parameters and performs a > bunch of things using these parameters. I believe I've followed the > tutorial correctly, but when I import it and try to make an instance > of it, it returns with the error that 'module' is not callable. I'm > kind of new to this language so I believe that it's most likely a > simple error on my behalf. Any advice on what I may be doing wrong > would be greatly appreciated. In the future, please actually post your code with your questions. However, I'll guess you did something like: class foo: def __init__(self, params): print "hello" foo() ... when in reality you need to create an object of type foo ... a = foo() <-- prints "hello" -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From deets_noospaam at web.de Wed Dec 17 07:32:56 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 17 Dec 2003 13:32:56 +0100 Subject: Threads for a newbe References: Message-ID: Hi, > i can... I'm a python newbe and have the following problem : I try to > create 2 threads in a server program and they seems to block each other. > I use something like this : > start thread waiting for connexion with : server.threadserver = > threading.Thread(target = self.__startserver) then do while 1 : > socket, host = accept(...) > then start a new thread for each new connexion after accept using > client.threadclient = threading.Thread(target = self.__receive) > and while 1 : > client.receive() > And here the first thread seems not to work anymore :( . I didn't join > threads. Maybe a lock() problem but i don't now how to use the lock() > function in Python... Maybe if someone had a multithread server sample > source I could understand what is the issue... I recently did implement a socket-server using threads. So if you give me more actual code, I might be able to help you. However, I stepped away from that approach and went for twisted - a really excellent networing framework, which eliminated the need for different threads. You should really look into that, as just having different threads sitting on blocking io-descriptors is abusing them (while I have to admit - its tempting...) Regards, Diez From jstreet10 at cox.net Wed Dec 3 12:07:16 2003 From: jstreet10 at cox.net (jstreet10) Date: Wed, 3 Dec 2003 12:07:16 -0500 Subject: Newbee needs Help ref Using Function Statements not Loops(For) Message-ID: How would i use function statements instead of loops(for) in this code? i have tried some, but not working. # this program is suppose to read fm a file, computes the average and reads fm a file # file grade info: dave, 75; david, 70; davy, 60; john, 70; jon, 60; nina, 55; nino, 50; ray, 65; sherry, 90; terry, 85 import os, sys, string student_table = {} grade_counter = 0 input_file = open("grades.txt","r") sum = 0 for record in input_file.readlines(): grade_counter += 1 record_key , record_value = string.split(record,",") student_table[record_key] = record_value sum += int (record_value) average = sum/grade_counter input_file.close() student_names = student_table.keys() student_names.sort() output_file = open("processed.txt", "w") for student_name in student_names: output_file.write(student_name +"," + student_table [student_name]) output_file.write("Average grade is" + str(average)) output_file.close() From mike at nospam.com Tue Dec 9 13:51:33 2003 From: mike at nospam.com (Mike Rovner) Date: Tue, 9 Dec 2003 10:51:33 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: Nick Vargish wrote: > Rene Pijlman writes: >> Serious question: why? > > How about providing a selection of ways of accessing an mp3 > collection? At the top level you could have /artist, /album, /genre, > /year... It reminds me of Microsoft's promise to combine RDBMS and file system in a new Longhorn OS. Several years ago that idea was highly popular but nothing came out. That approach may be very interesting to allow user to use some plug-ins for the file system (access, security, notification, etc.). Mike From cobracommanders_pusse24 at yahoo.com Thu Dec 18 21:10:58 2003 From: cobracommanders_pusse24 at yahoo.com (cobracommanders_pusse24) Date: Fri, 19 Dec 2003 02:10:58 -0000 Subject: im coming over to fuck you Message-ID: in a black skirt with a see thru thong on. you promised you'd let me stand in front of you while your sitting down and i'll bend over so you can lift my skirt up revealing my wet slit. you promised you'd take 1 finger and slightly pull my thong to one side and slide your tongue up and down my slit while my legs shaked and i moaned loudly telling you to lick deeper inside. you then promised you'd tease me with your cock by rubbing it on slit barley entering me. please dont tease too long. just bend me over your table and furiously rip my skirt off to where i'm just wearing that thong. please rip that off too so my pussy is exposed and you'll be able to see my swollen, wet lips which will make you want to thrust your cock right in with your might as I scream your name to fuck harder and faster. you get so winded by my slippery pussy so you asked to lay on the table.Look me up on my casual sex finder site. http://www.datingcall.com/landing.asp?afl=MYHO From andrew at exit66.com Thu Dec 11 13:26:11 2003 From: andrew at exit66.com (Andrew Barilla) Date: 11 Dec 2003 10:26:11 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd89449$0$565$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: I'm working on a cross platform app which has a standard GUI front end for administration and a kiosk front end for user usage. I'm using wxWindows for the standard GUI and it does port between Windows and Linux without a problem. The only significant difference I've seen is that MDI applications in Linux don't look like the do in Windows. Each child window shows up maximized in the parent window and there are tabs across the top to switch between children. This just maybe the default format and can be changed, but I haven't looked into it yet. For the kiosk I'm using PyGame which ports between Windows and Linux just as well. Andrew Barilla http://www.exit66.com/ From peter at engcorp.com Mon Dec 8 13:48:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Dec 2003 13:48:03 -0500 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: <3FD4C763.488579C1@engcorp.com> Todd Gardner wrote: > > Peter Hansen wrote in message news:<3FD3E423.B53D23DE at engcorp.com>... > > Todd Gardner wrote: > > > > > > I would like to graph two columns of x,y numbers? I would greatly > > > appreciate any pointers or suggestions. > > > > Yes, include more detail about what you want to do. Specifically, > > what platform, do you care if it's wxPython, or Tkinter, or something > > else, etc. There are about a zillion possible answers to your > > question as it stands, and "python graphing" or something on Google > > would likely get you a lot of mileage right now. Maybe after you > > do a little research there you can come back with a more detailed > > question? > > There are LOTS of plotting choices on google. I guess I would like to > narrow them down by tapping into some expertise. > > I would like to do 2D and possibly 3D plotting with python. I am > tending toward wxpython because of it's ease of use. You still haven't really given any information about your goals. Is this program just for visualization of static data? Anything dynamic? Who's the audience? Do you need to do printing of the same output? How precisely does the printed version need to match the screen? Is this part of a program that you will be giving to others, or is it just for personal use? Do you have any limitations with respect to the platform used? Linux only? Windows only? Both? Neither? And you can probably add another dozen questions to the mix. Yes, I understand that you hope someone can say something like "Use X or Y, but skip Z because it sucks", but you really can't expect to get a to-the-point answer if nobody knows what you want this for. -Peter From jzgoda at gazeta.usun.pl Fri Dec 26 02:56:36 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 26 Dec 2003 07:56:36 +0000 (UTC) Subject: indendation error References: Message-ID: km pisze: > File "script.py", line 6 self.x = x ^ IndentationError: expected an > indented block > > kindly enlighten hwo to fix this -- it will be great if someone can > direct me to an online link regarding the rules of indendation. Don't mix tabs and spaces in your code, use either tabs OR spaces. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From exarkun at intarweb.us Mon Dec 15 09:21:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 15 Dec 2003 09:21:53 -0500 Subject: ouput redirection..a newbie question In-Reply-To: <1008670585.21577.4.camel@gautam> References: <1008670585.21577.4.camel@gautam> Message-ID: <20031215142153.GD28160@intarweb.us> On Tue, Dec 18, 2001 at 03:46:26PM +0530, Gautam Pagedar wrote: > Hello, > > i am new to python and need a basic answer. Hope someone would help me > solve this. > > I want to execute a command ls -l and sore its result in a file. > > >>import sys > >>import os > >>os.system("ls -al") > > executes the command how can i redirect the to a file like we do in > shell script using a redirection operator. > This works: os.system("ls -al > foo") Perhaps more usefully, though, the "commands" module allows you to get the output of a program as a string: foo = commands.getoutput("ls -al") And it might be helpful to know that Python itself has functions for listing files: fileList = os.listdir(".") As well as for getting information about them: fileMTimes = [os.path.getmtime(f) for f in os.listdir(".")] filePermissions = [os.stat(f).st_mode for f in os.listdir(".")] For more information, see http://www.python.org/doc/lib/ Jp From bsneddonNOspam at yahoo.com Fri Dec 19 11:16:15 2003 From: bsneddonNOspam at yahoo.com (Bill Sneddon) Date: Fri, 19 Dec 2003 11:16:15 -0500 Subject: any one used googles api? Message-ID: Has anyone used googles API who would be will to share a simple example. I have been wanting to play around with SOAP for a while and this looks like a place to start. I am going to mess with it in ASP when our IT guys set it up for me. I like Python but have not done anything with SOAP yet. http://www.google.com/apis/ From sandorlevi at yahoo.com Sun Dec 7 19:58:16 2003 From: sandorlevi at yahoo.com (Levente Sandor) Date: 7 Dec 2003 16:58:16 -0800 Subject: finding files that have extensions References: <93f5c5e9.0312071154.4e7a1311@posting.google.com> Message-ID: <8b5e42a6.0312071658.1a418c56@posting.google.com> Have a look at the glob and fnmatch modules, they should help. ---- levi hokiegal99 at hotmail.com (hokiegal99) wrote in message news:<93f5c5e9.0312071154.4e7a1311 at posting.google.com>... > Hi, > > I have a working Python script that renames files that don't currently > have PC based file extensions. For example, if there is a MS Word file > that does not have '.doc' on the end of it, the script will append > that. The script also knows to *not* add an extension if the file > already has one. Bascially, here's how I'm doing it: > > for fname in files: > doc_id = string.find(file(os.path.join(root,fname), > 'rb').read(), 'Word.Document.') > doc_skip = string.find(fname,'.doc') > DOC_skip = string.find(fname,'.DOC') > if doc_id >=1 and doc_skip ==-1 and DOC_skip ==-1: > newpath = os.path.join(root,doc_new) > oldpath = os.path.join(root,fname) > os.renames(oldpath,newpath) > > The problem I'm having is that as I add more and more file types to > the script I have to define more and more 'xxx_skip' variables. My > 'if' conditionals are growing larger and larger. Which leads to my > question: How could I define it so that *any* file that already has a > '.xxx' extension (where x = 'abcdefghijklmnopqrstuvwxyz' upper and > lowercase) would be excluded from the rename? I've considered > something like this: > > ext = re.compile('[abcdefghijklmnopqrstuvwxyz]', re.IGNORECASE) > > But I don't know how to pull 'ext' into something like this: > > ext_skip = string.find(fname,'.xxx') > > Any ideas? > > TIA!!! From pclinch at internet-glue.co.uk Fri Dec 12 18:08:23 2003 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 12 Dec 2003 15:08:23 -0800 Subject: HalfLife/Cstrike monitorring References: <3fd84154$0$251$4d4ebb8e@news.nl.uu.net> <3FD8C79C.D7166008@alcyone.com> <3fd8fa1c$0$154$3b62cedd@news.wanadoo.nl> Message-ID: <8cf2994e.0312121508.30e1aa95@posting.google.com> "Guyon Mor?e" wrote in message news:<3fd8fa1c$0$154$3b62cedd at news.wanadoo.nl>... > Thanx for the tip, but actually I wanted to make something, which shows the > stats of a match a bit 'flashy arcade style'. perhaps i'll use pygame for > that part. > > In other words: it should look cool on a beamer :) > > anyway, the decoding stuff I've managed, but I'm still stuck with the UDP (i > think) because somehow no response is given. maybe someone can show me the > light. > > thanx, > > Guyon > > > "Erik Max Francis" schreef in bericht > news:3FD8C79C.D7166008 at alcyone.com... > > "Guyon Mor?e" wrote: > > > > > I want to write a HalfLife/CStrike monitor, to make some nice > > > statistics for > > > an upcoming LAN-party. I've found some pointers on how to use the > > > protocol, > > > but now I have to do the following: > > > > > > 1. make an UDP connection > > > 2. send a string(?) like '\xFF\xFF\xFF\xFFdetails\x00' > > > 3. translate the response into bytes and strings :-s > > > UDP is connectionless, make a socket, send and recv. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto('\xFF\xFF\xFF\xFFdetails\x00', ('127.0.0.1', portnumber )) ret, addr = s.recvfrom(1024) Note that the server is not guaranteed to receive your request, or you receive the reply. Look up select and poll in the doc.s. Python version 2.3 has socket timeouts. > > > for more details on this protocol see: > > > http://dev.kquery.com/index.php?article=31 > > > > > > I hope someone can help me with at least the first 2 steps. > > > > It sounds like you just want a server statistics package, of which there > > are many available. See Google; a good one is PsychoStats. There's > > really no need for you to reinvent the wheel here. > > > > -- > > __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > > / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > > \__/ Dead men have no victory. > > -- Euripides Regards, Paul Clinch From ajsiegel at optonline.com Sun Dec 7 10:07:58 2003 From: ajsiegel at optonline.com (Arthur) Date: Sun, 07 Dec 2003 15:07:58 GMT Subject: Lists and Tuples References: Message-ID: On Sun, 7 Dec 2003 15:09:48 +0100, "Fredrik Lundh" wrote: >Arthur wrote: > >> "Type" is not normally an ambiguous word. > >really? in my experience, "type" and "object" are about as ambiguous >as words can get, especially when you're talking about Python. > > I am sure you are right. On faith. Though its not particularly helpful. Art From max at cNvOiSsiPoAnMtech.com Sun Dec 28 13:28:45 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Sun, 28 Dec 2003 18:28:45 GMT Subject: pointers In-Reply-To: References: Message-ID: No. Lack of direct support for pointers was a conscious decision of the language designer. Raw pointer usage is annecessary evil as far as python's target programs are concerned. If you absolutely need pointer aceess you can get them via 3d party ctypes module. km wrote: > Hi all, > > may i know if there is any plans of introducing the concept of pointers into python language as in C ? (atleast in future versions ?) > > regards, > thanks > KM > > > From fredrik at pythonware.com Sun Dec 7 09:52:30 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 15:52:30 +0100 Subject: Best structure for (binary) trees? References: Message-ID: "Rasmus" wrote: > As partly novice in python I would like a piece of advise of how to > implement (binary) trees the best way? if you're 100% sure you cannot use a standard dictionary, the best way is probably to get ZODB and use its BTrees module... code: http://www.zope.org/Products/ZODB3.2 introduction: http://zope.org/Wikis/ZODB/FrontPage/guide/node6.html From bdelmee at advalvas.REMOVEME.be Wed Dec 3 19:13:59 2003 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Thu, 04 Dec 2003 01:13:59 +0100 Subject: String length ... len(str) In-Reply-To: References: Message-ID: <3fce7c40$0$1127$6c56d894@feed0.news.be.easynet.net> > Why is len(str1) = 4 and len(str2) = 3? Because str1 is a string whereas str2 is a tuple. Both are sequences whose size is returned by len(). You probably meant str2 = "here" + "we" + "are" If you ask "type(str2)" at the python prompt, you'll see exactly what's going on. Cheers, Bernard. From rafael at vexbr.com.br Thu Dec 11 16:05:43 2003 From: rafael at vexbr.com.br (Rafael T. Ugolini) Date: Thu, 11 Dec 2003 19:05:43 -0200 Subject: More than one cookie with urllib2 Message-ID: <1071176742.12610.9.camel@nebula> Im trying to add more than one cookie with urllib2 but im not getting much sucess. An example... >>> req = urllib2.Request('http://localhost','j_username=psyca&j_password=******',{ 'Cookie':'sab=contextUrl+https%3A%2F%2Fwwws.vexbr.com.br%2Fcafedev%2F%7CnasIp+10.50.0.3%7CneedCheckCode+false%7ClocationId+85%7CautoLogout+false%7CserviceProviderId+1%7CorigUrl+%2Findex.html%7CwebContext+cafedev%7CclientIp+192.168.1.107%7CnasId+vex_cafedev%7CloginType+0%7Cclass+class+com.wificom.sab.aaa.dto.SessionDTO%7CloginResumed+false%7CloggedIn+false%7Clanguage+en%7CpricingPlanId+0%7CsslPort+443%7CroamingPriceId+0%7CclientMac+00%3A07%3A95%3AD3%3A0C%3A7C%7CserverUrl+https%3A%2F%2Fwwws.vexbr.com.br%2F', 'Cookie':'JSESSIONID=DFA58D39389BA5E3CEB5C92F9308792C', 'Content-type':'application/x-www-form-urlencoded', 'Content-length':str(len('j_username=psyca&j_password=******'))}) >>> urllib2.urlopen(req) nebula:/home/nebuloso# nc -l -p 80 POST / HTTP/1.0 Host: localhost User-agent: Python-urllib/2.1 Cookie: JSESSIONID=DFA58D39389BA5E3CEB5C92F9308792C Content-length: 34 Content-type: application/x-www-form-urlencoded j_username=psyca&j_password=****** --- and another thing , headers is a dic , you cant add 2 equal keys... dunno how to do it. Thanks. From aahz at pythoncraft.com Tue Dec 9 00:00:33 2003 From: aahz at pythoncraft.com (Aahz) Date: 9 Dec 2003 00:00:33 -0500 Subject: Python progamming certification References: Message-ID: In article , Apollo <_ at _._> wrote: > >Is there a Python programming certification like Sun's Java certificates? Give me US$500, and I'll make you one. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From kirk at strauser.com Sat Dec 27 00:40:06 2003 From: kirk at strauser.com (Kirk Strauser) Date: Sat, 27 Dec 2003 05:40:06 GMT Subject: Using Python to send a DNS update packet References: Message-ID: <8765g27rg1.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-12-24T18:29:03Z, "Matt Whiteley" writes: > Hello all, > > I want to use Python to send a request to a Microsft DNS server to tell it > to update an A record. Ideally, this would be a secure update but primarily, > an unsecure one would do. Are there any python modules that will let me do > it or is there some code knocking around I could use ? > > Thanks > Matt > > The NSUpdate class from my Newtrino project at: http://subwiki.honeypot.net/cgi-bin/view/Freebsd/NewTrino uses the Unix `nsupdate' command to send TSIG-authenticated update messages to a BIND 9 DNS. It may or may not work with an MS DNS - I haven't tested it in that configuration - but it should be easy enough to adapt it to do so. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/7RpS5sRg+Y0CpvERAsl/AJ4tk5uAQCXesYFWIjke/EB+rVhUuwCfShfC 5rtqJbqOKR5XfY0KfhXO9fk= =/+K8 -----END PGP SIGNATURE----- From kirk at strauser.com Tue Dec 30 17:05:05 2003 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 30 Dec 2003 22:05:05 GMT Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> <87ad5a2s08.fsf@strauser.com> <7x1xqmccda.fsf@ruckus.brouhaha.com> <871xqm2ekg.fsf@strauser.com> <7xbrpqgety.fsf@ruckus.brouhaha.com> Message-ID: <87vfny0xq9.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-12-30T21:45:13Z, Paul Rubin writes: > You're using an extreme example and seeing the cost of the cache lookup in > the first example. The OP may be coding in an extreme situation. Given the free performance gain without requiring any more work, resources, or syntax, I can't think of a good reason *not* to pre-compile any regexp used more than a few times. > You're certainly not seeing the pattern get recompiled a million times in > 5 seconds. Doing would be many times slower. Regardless of the cause, there's still a 400% increase in overhead in my example by not pre-compiling the pattern. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/8fZB5sRg+Y0CpvERAnMHAKCcnpcvqnFwtoexLImr9RzkMe5AugCfeZf4 YsqhMvp9d2+XG8aQFphRJqA= =WvXA -----END PGP SIGNATURE----- From r.s at XXmindspring.com Fri Dec 5 16:19:27 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Fri, 05 Dec 2003 21:19:27 GMT Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: "Mel Wilson" wrote ... > It's more because the `a` in `a=` is simply a name, and > the rule for assigning to a name is to forget the previous > binding (if any) and create a new binding. [beginner here] Ok, I thought I understood that, but then I was reading about some special named objects being pre-defined (e.g. `0` through `99`), so I tried the following (using `is`, which I understand compares the identities of the objects whose names are given to it): >>> a = 1 >>> a is 1 True >>> a = 100 >>> a is 100 False ... so far so good, and then experimenting: >>> a = [] >>> a is [] False ... which, like the result for `100`, I *thought* was explained like this: When the interpreter encounters the `[]` on the RHS, there is no object named `[]`, so it creates one and binds it to the name `a` (forgetting the old binding for `a`). Then on the second line, when the `[]` is encountered, again there's no object with that name, so a new one is created and found to be in a location different than the one just named `a`. But something's wrong with that explanation, because of the following: >>> a = 'gobble' >>> a is 'gobble' True Surely `'gobble'` is not the name of an already-existing object, so I expected exactly the same result as for `100` and `[]`. What's going on there? (`[]` and `'gobble'` differ with respect to mutability, but how does that explain the different result (if it does))? Thanks. -- r.e.s. From Samwatson at yahoo.com Fri Dec 12 17:14:03 2003 From: Samwatson at yahoo.com (Sam Watson) Date: Fri, 12 Dec 2003 17:14:03 -0500 Subject: Building a new app in python and need some architecture advice. References: <5h7dtv4k4mmd1ovconager5lbggbv86jcr@4ax.com> Message-ID: Got ya. Thanks for the example eddie! From sombDELETE at pobox.ru Wed Dec 17 14:45:39 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Wed, 17 Dec 2003 22:45:39 +0300 Subject: filter and map / deprecated? References: Message-ID: "Logan" wrote in message news:pan.2003.12.17.18.35.25.713854 at phreaker.nospam... > I read in PEP 279 the following comment by GvR: > > "filter and map should die and be subsumed into list > comprehensions, not grow more variants." > > Actually, I am using 'filter' and 'map' a lot in my scripts > (not really because they are necessary, but more because I > like them). Should I avoid the usage of 'filter' and 'map' > in the future? The above comment by GvR makes me a little > bit afraid that they will become deprecated one day and that > I will have to change many of my scripts then. You will have to port and and test your scripts on the new Python. You aren't going to use them untested, are you? In case of filter & map you will just have to (my guess) insert: from legacy import filter, map Using filter & map these days is discouraged, use itertools module. Anyway I think before they disappear they should be removed from documentation and _books_ first. I mean old books should become obsolete, new books and documentation should briefly mention them in the legacy chapter. These are should be no trace of them in the main chapters. And then the functions can be actually removed from the Python core. I beleive this is the least painful way to get rid of them. The cost of keeping them in the core is very low, the main problem is documentation. So the process of deprecitation should focus on the documentation. -- Serge. From gh at ghaering.de Tue Dec 16 03:01:51 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 16 Dec 2003 09:01:51 +0100 Subject: Advice for PostgreSQL In-Reply-To: <3fde873c$1@clarion.carno.net.au> References: <3fde873c$1@clarion.carno.net.au> Message-ID: <3FDEBBEF.3050209@ghaering.de> Steve wrote: > Hi, > > Can someone please point me out to some module/library for using > PostgreSQL from python? Either one of these will do fine: - http://pypgsql.sourceforge.net/ - http://initd.org/software/initd/psycopg Both contain documentation, but not tutorial-like, AFAIK. > Perhaps a tutorial as wel? Thanks! http://www.linuxjournal.com/article.php?sid=2605 It uses soliddb as a module, but all these modules implement the Python DB-API 2.0, so the major differences are the import statement and the call to .connect(). -- Gerhard From ich at jan-kesten.de Fri Dec 19 11:28:51 2003 From: ich at jan-kesten.de (Jan Kesten) Date: Fri, 19 Dec 2003 17:28:51 +0100 Subject: Module for Informix Database? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Olaf Ferger wrote: | AFAIK it's definitely possible to use module 'informixdb' | (http://starship.python.net/crew/sturner/informixdb.html) with | Python2.x (although installing the module for Python 2.x is tricky)! | And it only implements version 1.0 of the DB-API specification. But, | that was good enough for me ;-) I saw this module - but I didn't manage to compile and/or install it into Python 2.x. I have made a work around for me a while ago, so I used isql from Informix to unload the results into a textfile and then read it with Python. But if there is more than one access at a time this (of course) leads into trouble.. So if you still know, how you got "informixdb" to work with Python 2.x please let me know. Cheers, Jan -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE/4ydDvvmCkIIgH8QRAhL/AJ9fBES/1cGrhwvuiGf59csoe1DPkgCgq780 lwNckQMM8hjdIFTp0fEP2Qk= =deuO -----END PGP SIGNATURE----- From spiffy at worldnet.att.net Tue Dec 9 17:44:14 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 22:44:14 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <2fsBb.423999$0v4.20388116@bgtnsc04-news.ops.worldnet.att.net> "Diez B. Roggisch" wrote in message news:br5hu8$em2$01$1 at news.t-online.com... > > Here is the code used to call it from Python: > > import os > > filename = "C:\Python22\Canyon.mid" > > os.system("C:\Python22\playb.exe%s"%filename) > > ...this causes a dos box to appear which promptly hangs and does nothing, > > at which time Python stops responding. Vartiations on this will cause the > > dos box to appear with the message "Bad command or file name". > > > > Looks like there is a space missing - > > os.system("C:\Python22\playb.exe %s"%filename) > ^ > > Diez > There is no space missing. That is the name of the file on my comp. From __peter__ at web.de Sat Dec 13 18:35:24 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Dec 2003 00:35:24 +0100 Subject: Shell quoting as part of the standard library? References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: David M. Wilson wrote: > I've been using Python in a couple of different environments for a few > years now. I have quite often found that I have needed to deal with > filenames which may contain characters that confuse the UNIX shell > (space and double quote in particular). > > Quite a while ago I came up with two simple functions which allowed me > to safely build a shell command line quickly. I've used the functions > hundreds of times by now, and find myself constantly cut/pasting them > into new projects. It is very likely that someone other than myself > would find these functions to be useful, and I was wondering if such a > thing might find a home in the standard library. > > http://botanicus.net/dw/tmp/shellquote.py > > Does this sort of thing have a home in the standard library? It > doesn't really apply across platforms, which is my only real concern. > Where should it be added to? shutil? >>> from commands import mkarg >>> mkarg("one silver $") " 'one silver $'" >>> mkarg("one's own $") ' "one\'s own \\$"' So something very similar for argument preparation is already there. The joining, as far as I know, currently has to be done manually: >>> "".join([mkarg(a) for a in ["a a", "$'"]]) ' \'a a\' "\\$\'"' Peter From billk at cts.com Sat Dec 20 16:06:12 2003 From: billk at cts.com (Bill Kelly) Date: Sat, 20 Dec 2003 21:06:12 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: <8R2Fb.23477$nG3.12519@twister.socal.rr.com> "Xah Lee" wrote: > i have a bunch of java files that has spaced-out formatting that i > want to get rid of. I want to replace two end of line characters by > one end of line characters. The files in question is unix, and i'm > also working under unix, so i did: > > perl -pi'*~' -e "s@\n\n@\n at g" *.java > > but this to no avail. Here are two Ruby solutions, both of which have Perl equivalents: ruby -i~ -e '$/=nil; puts gets.gsub(/\n\n/,"\n")' *.java ruby -i~ -e '$/="\n\n"; while(gets)do puts chop end' *.java You may also want to check out http://astyle.sourceforge.net/ which is a free source code beautifier for C/C++/Java. > after many minutes of checking and rechecking and lots of trial and > error with frustration, i realized that the fucking perl to my > expectations again cannot do this simple fucking thing. Nor can the > unix utility tr. Fucking stupid perl couldn't do a simple task of > replacing strings. > > let me just take this opportunity to explain one shit from the > thousands from perldoc. [...] http://www.wavlist.com/movies/135/str-francis.wav "Lighten up, Francis." Regards, Bill From j-y.nief at wanadoo.fr Mon Dec 15 16:09:26 2003 From: j-y.nief at wanadoo.fr (Jean-Yves Nief) Date: Mon, 15 Dec 2003 22:09:26 +0100 Subject: question on multithreading, pipes Message-ID: <3FDE2306.4050707@wanadoo.fr> hello, I have written a script which is performing some tasks in multithreading mode: the main thread is opening a connection to a distant server and all the threads that I start will have to perform actions on the remote server using the connection initiated by the main thread. At first sight, the only way I could achieve that in a proper manner (ie without having to open a connection to the remote server in every single thread and close it at the end of the thread) would be to use a pipe that I would use in all the threads, for example: * main thread: fw, fr = os.popen2('/bin/ksh') fw.write('Sinit') etc... * other threads: fw.write('perform action') etc... but if I do that, I need to queue the events, which means I have to serialize the jobs perform by the threads, which is clearly not what I want as I am using threads :-) so my question is: how could I get around this without giving up multithreading ? any help appreciated. thanks, JY From opengeometry at yahoo.ca Fri Dec 12 15:17:04 2003 From: opengeometry at yahoo.ca (William Park) Date: 12 Dec 2003 20:17:04 GMT Subject: Python code to replace shell scripts References: <3fd9832d.385255327@news.blueyonder.co.uk> Message-ID: Alan Gauld wrote: > On 12 Dec 2003 01:58:23 GMT, William Park > wrote: > > In any case, although Python does something well, shell does most > > things better. (It's okey... I've got my helmet on.) > > Shell is generally better at quickly gluing together existing > commands. But does so at a significant cost in machine resources and > often execution time. Python provides a different approach that is > generally better where the solution must be repeated often or where no > suitable set of commands already exists. That is true, until you learn and program in shell. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From tim.one at comcast.net Mon Dec 1 22:50:04 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 1 Dec 2003 22:50:04 -0500 Subject: Equivalence of dictionary keys? In-Reply-To: <3FCC058C.6070205@irl.cri.nz> Message-ID: [Blair Hall] > I would like to determine whether two dictionaries have the > same set of keys. Can anyone tell me if I HAVE to sort > the key sequences as in this code snippet: Yes, you do. > # d1, d2 already created > k1 = d1.keys() > k1.sort() > k2 = d2.keys() > k2.sort() > > # are the keys the same? > same = (k1 == k2) > > I am guessing that two dictionaries with the same keys > will sort them in the same order but is this true? Not necessarily. The order is an implementation accident, and especially in the presence of hash collisions *will* differ between two dicts with the same keys if they were inserted in a different order. If you can afford the memory, a slicker trick is to compare two derived dicts with the same keys and known to have equal values. In 2.3, same = dict.fromkeys(d1) == dict.fromkeys(d2) is enough. This doesn't sort under the covers, either. Another trick, which should work with any modern Python version: if len(d1) == len(d2): temp = d1.copy() temp.update(d2) same = len(temp) == len(d1) else: same = False From tr at jotsite.com Sun Dec 14 16:10:25 2003 From: tr at jotsite.com (Hoang) Date: Sun, 14 Dec 2003 21:10:25 GMT Subject: install multiple versions of activepython References: Message-ID: <5l4Db.71454$jg1.2929@newssvr25.news.prodigy.com> > Binary extension modules are a different matter, exactly, I was using Audiere and it worked with 2.2. Since the upgrade, I've been unable to use it until the Audiere project updates their binaries. So I was wondering if it was possible to keep both ActivePython versions (2.2 and 2.3) installed under Windows.... anyone else run into such a need? Hoang Do From bokr at oz.net Tue Dec 30 23:07:01 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Dec 2003 04:07:01 GMT Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: On Wed, 31 Dec 2003 04:04:47 +0200, Christos "TZOTZIOY" Georgiou wrote: >On 31 Dec 2003 00:08:47 GMT, rumours say that bokr at oz.net (Bengt >Richter) might have written: > >>The other way is to take advantage of functions' roles as decriptors and the mechanism that >>makes bound methods with a self as the first arg, but the rest apparently normal. I.e, >>we can put the r parameter in the place of self (not specifically tested) >> >> def uses_self(r, x): >> pass >> uses_self = uses_self.__get__(re.compile("...")) > >It's much more general to use new.instancemethod. See: I think I did use new.instancemethod, through another door ;-) >>> def uses_self(r, x): ... pass ... >>> import re >>> uses_self = uses_self.__get__(re.compile("...")) >>> type(uses_self) >>> myim = type(uses_self) >>> myim >>> import new >>> myim is new.instancemethod True ;-) >>> def foo(self, *args, **kw): print 'self=%r, args=%r, kw=%r'%(self, args, kw) ... >>> myim(foo, 'dummy self', object) # object per your usage >>> foom = myim(foo, 'dummy self', object) # object per your usage >>> foom(1,2,3,hi='Hello') self='dummy self', args=(1, 2, 3), kw={'hi': 'Hello'} I didn't make voodoo out of it though. Interesting, but all that nested calling at call-time seems like it would make for a performance hit? Unless maybe it is all packed up in slots that C can get to very fast?? > >def voodoo(function, *its_arguments): > from new import instancemethod > def child(function, first_argument, *rest_of_arguments): > if rest_of_arguments: > return child( > instancemethod(function, first_argument, object), > *rest_of_arguments > ) > else: > return instancemethod(function, first_argument, object) > return child(function, *its_arguments) > >The import statement is in the voodoo just for completeness including it >here. >The function above recurses in order to allow stuff like: > >getter = voodoo(getattr, my_object, "its_attribute") > >or the more modern > >getter = voodoo(operator.itemgetter("its_attribute"), my_object) > >and similarly > >setter = voodoo(operator, my_object, "its_attribute") > >allowing > >setter(value) > >at good speeds. > > >I have a module predicates.py defining All and Any classes for >iterables, and the trick above plus itertools allows *some* operations >to run faster than correspondent python code... Interesting. Gotta go. Regards, Bengt Richter From jacek.generowicz at cern.ch Fri Dec 12 04:47:50 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Dec 2003 10:47:50 +0100 Subject: Function application optimization. Message-ID: Given fncs = [func1, func2, ..., funcN] args = [arg1, arg2, ..., argN] How should one spell results = map(lambda f,a: f(a), fncs, args) in order to get the result most quickly ? Unfortunately "apply" takes a tuple of arguments, and there is no "funcall"[*] in Python. [*] def funcall(fn, *args): return fn(*args) From swalters_usenet at yahoo.com Tue Dec 30 17:50:40 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Tue, 30 Dec 2003 22:50:40 GMT Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312240207.5fb1914c@posting.google.com> Message-ID: On Wed, 24 Dec 2003 02:07:10 -0800, Stormbringer wrote: > I wrote a similar version of what I wanted a couple of years ago not > using a database, just C/C++ code, something like this (I think a > similar method was suggested in this thread) : I was processing messages > in batches, so for each 10000 messages or so I would make in memory a > list of words and in what messages occur, and for each word I would > write all messages that contain it as consecutive entries in a file. > Then I would update the global word index (kept in another file), which > for each work kept a linked list of zones in the other file where msgIds > containing this word were. > > Worked pretty well, but this was for a server I controlled, i.e. at all > times I was sure I had enough space and I was controlling it. For an > application to be deployed to end-users I need more safety. That is why > I am playing with sql. For future reference: If you're like me, and have a lot of c/c++ code that you've built and are happy with, pyrex ( http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ ) can come in handy for reusing that code within python. Pyrex is easier to write and maintain than the direct c-to-python API, and with a little bit of practice, you can learn how to easily marshal data back and forth between the two languages. Essentially, it takes all the grunt-work out of writing making c/c++ calls from python. It's especially tasty when you need to make use of some shared library that python has no interface to. Sam Walters From fredrik at pythonware.com Sun Dec 7 16:29:51 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 22:29:51 +0100 Subject: Lists and Tuples References: Message-ID: Robert Brewer wrote: > Now if somebody can just figure out why: > > threading.Thread(args=()) > > but: > > threading.Timer(args=[]) > > we'll have this topic nailed down pretty well. ;) different authors; the threading module itself is really old (1.5?), but the Timer class was added in 2.2, and nobody spotted the inconsistency at that time. not sure if this can/should be fixed; there might be someone out there doing: t = threading.Timer(interval, function) t.args.append(value) t.start() From tjreedy at udel.edu Sat Dec 27 15:23:34 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Dec 2003 15:23:34 -0500 Subject: Some optimization tale References: Message-ID: "Stephan Diehl" wrote in message news:bskcb0$36n$00$1 at news.t-online.com... > All of this can be found at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252177 > > What I was most surprised at was the inefficency of the trivial solutions > (and that the right algorithm makes indeed a difference). A common surprise. The science of algorithms (including empirical testing) gives real benefits. > -- os.path.commonprefix -------------------------------------------------- > > def f1(m): > "Given a list of pathnames, returns the longest common leading > component" > if not m: return '' > prefix = m[0] prefix = m.pop() # avoids comparing prefix to itself as first item > for item in m: > for i in range(len(prefix)): > if prefix[:i+1] != item[:i+1]: I am 99% sure that above is a typo and performance bug that should read if prefix[i:i+1] != item[i:i+1]: since all previous chars have been found equal in previous iteration. > prefix = prefix[:i] > if i == 0: > return '' > break > return prefix Perhaps you could retest this with the two suggested changes. It will be somewhat faster. > The problem with this algorithm is the copying of all those small strings. Since Python does not have pointers, comparing characters within strings requires pulling out the chars as separate strings. This is why using C-coded comparison functions may win even though more comparisons are done. The reason f1uses slicing (of len 1 after my correction) instead of indexing is to avoid exceptions when len(item) < len(prefix). However, all the +1s have a cost (and I suspect slicing does also), so it may pay to truncate prefix to the length of item first. The simplest fix for this (untested) gives def f9(m): # modified f1 == os.path.commonprefix "Given a list of strings, returns the longest common prefix" if not m: return '' prefix = m.pop() for item in m: prefix = prefix[:len(item)] for i in range(len(prefix)): if prefix[i] != item[i]: if not i: return '' prefix = prefix[:i] break return prefix > This can be easily fixed > --- optimized os.path.commonprefix ---------------------------------------- > > def f2(m): > "Given a list of pathnames, returns the longest common leading > component" > if not m: return '' > if len(m) == 1: return m[0] > prefix = m[0] > for i in xrange(len(prefix)): > for item in m[1:]: > if prefix[i] != item[i]: > return prefix[:i] > return prefix[:i] and easily messed up;-) If len(item) < len(prefix), item[i] throws exception. For this approach to work, prefix should be set as shortest string of m in preliminary loop. Also, you reslice m several times. Do it once before outer loop. > It is just not nessesary to compare all strings in the list. Every string has to be compared to something at least once. > It is enough to sort the list first > and then compare the first and the last element. Sorting compares all strings in the list to something at least once, and most more than once. > Even though the 'sort' algorithm is coded in C and is therefore quite fast, > the order of runtime has changed. The C part is what makes f3 faster. In your timings, 128 is not large enough for the nlogn component to be noticeable. > Michael Dyck then pointed out that instead of using 'sort', 'min' and 'max' > should be used. While tests suggest that this is true, I have no idea why > that should be, since finding a minimum or maximum uses some sorting anyway No. max and min each do a linear scan. No sorting. But each does at least as many character comparisons as modified f1 or f2. The speedup is from looping and comparing in C, even though at least twice as many compares are done. > You might have realized that the optimization so far was done one the number > of strings. There is still another dimension to optimize in and that is the > actual string comparing. > Raymond Hettinger suggests using a binary search: Since this only affects the final comparison of min and max, and not the n comparisons done to calculate each, the effect is minimal and constant, independent of number of strings. Since this compares slices rather than chars in each loop, I wonder whether this is really faster than linear scan anyway. I would like to see timing of f5 with min/max of f4 combined with linear scan of f3. (Basically, f3 with sort removed and min/max added.) Since you changed two parts of f3 to get f4, we cannot be sure that both changes are each an improvement even though the combination of two is. def f5(seq): if not seq: return '' s1 = min(seq) s2 = max(seq) n = min(len(s1), len(s2)) if not n: return '' # not required since s1[0:0] == '' for i in xrange(n) : if s1[i] != s2[i] : return s1[0:i] return s1[0:n] Terry J. Reedy From theller at python.net Fri Dec 12 13:18:40 2003 From: theller at python.net (Thomas Heller) Date: Fri, 12 Dec 2003 19:18:40 +0100 Subject: Trouble building Python2.3.3c1 on WinXP: where's pythonnt_rc.h? References: Message-ID: <1xr96gsf.fsf@python.net> "vincent wehren" writes: > Hi, > > I'm running into trouble building Python2.3.3c1 from source on a Windows XP > machine. > > I'm getting C:\Python-2.3.3c1\PC\python_nt.rc(14) : fatal error RC1015: > cannot open include file 'pythonnt_rc_d.h' > > Is this some magic involving "make_versioninfo.dsw"? > What gives? > I am lost here... I assume you try to build from the tarball downloaded from www.python.org. This one has the problem (which will be fixed in 2.3.3 final) that the make_versioninfo.dsp file has unix-style line endings, and MSVC refuses to load the project file then. (The make_versioninfo project creates the header file you mention). Try to convert make_versioninfo.dsp to DOS stype line endings (loading it into wordpad - not notepad - and saving it again is one possibility), reload the workspace and it should build. Thomas From mkent at webmd.net Fri Dec 12 16:48:26 2003 From: mkent at webmd.net (Mike Kent) Date: 12 Dec 2003 13:48:26 -0800 Subject: Problem with frozen app: compatibility between Unixware and SCO Unix Message-ID: <83846327.0312121348.f50f468@posting.google.com> I need to deploy a Python app on both SCO Unixware and old SCO Unix boxes. We freeze the app under Unixware, and set the compatibility flag ('elfmark -t udk') on the resulting executable. We successfully did this using Python 1.5.2. Recently, we decided to upgrade the app to use Python 2.3.2. Unfortunately, we've just discovered a nasty surprise. Under 2.3.2, os.path.isdir() returns True on Unixware for an existing directory (/tmp, for example), but returns False under SCO Unix. Ouch. Note that this has been verified using a test program that is frozen under Unixware, then run on Unixware and SCO Unix. We don't currently have a python interpreter on the SCO Unix box. Because of the way a frozen app is involved, I'm thinking that this is a binary compatibility problem, and will investigate further. We do the same 'compile under Unixware, deploy under SCO Unix' thing for many other apps that are written in C, without encountering this problem. Does anyone have any suggestions on how I can best proceed? Have you heard of this kind of problem before? What additional information would you like to read? Thanks From andrew-pythonlist at puzzling.org Tue Dec 9 18:44:37 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 10 Dec 2003 10:44:37 +1100 Subject: Base conversion method or module In-Reply-To: References: <0b88tvo38l9ca8fhc3127mskqegdpfocn7@4ax.com> <20031208235718.01860.00000479@mb-m18.aol.com> Message-ID: <20031209234437.GA18894@frobozz> On Tue, Dec 09, 2003 at 11:20:43PM +0000, Jeff Wagner wrote: > On Tue, 9 Dec 2003 17:45:20 +1100, Andrew Bennetts wrotf: > > > >In Python, integer literals beginning with '0' are in octal, just as how > >literals beginning with '0x' are in hex, so 01011010 really is 266760: > > > >>>> print 01011010 > >266760 > > > >So it looks like gmpy is functioning correctly. > > > >-Andrew. > > > > Ok, so I get rid of the leading 0 and here is what I get: > > >>> gmpy.digits(1011010,10) > '1011010' > > why? How do I tell gmpy that 1011010 is binary and I want it to convert to decimal or hex? You seem to be confusing the value of a number with its representation. Python's 'int' type simply holds a value. It doesn't know the difference between 90, 0x5A, and int('1011010', 2). They are all the same number, even though they represented differently in source code. So, what you *really* are trying to ask is: "How do I take a representation of a number in binary (i.e. base 2), and convert it to a representation in decimal or hex?" The answer is to first convert your representation to a value -- python's builtin int can convert string representation of numbers with any base from 2 to 36, e.g.: >>> int('1011010', 2) 90 >>> int('5A', 16) 90 (I wouldn't be surprised if gmpy also could do this, but I don't know gmpy) Note that I am passing strings to int, not bare literals! If I wrote "int(1011010, 2)", python would compile 1011010 as a number in base 10, and pass that number to int instead of the string representation of the number we really want. Then you want to pass this value to gmpy.digits, e.g. num = int('1011010', 2) print gmpy.digits(num, 16) -Andrew. From deets_noospaam at web.de Sat Dec 13 09:46:15 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Sat, 13 Dec 2003 15:46:15 +0100 Subject: do this with list comp? References: Message-ID: John Hunter wrote: > > I want to replace all empty fields in a CSV line with 'NULL'. > > Here is a brute force way > > def fixline(line): > ret = [] > for s in line.split(','): > if not len(s): ret.append('NULL') > else: ret.append(s) > return ret > > line = 'John,Bill,,,Fred' > print fixline(line) > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > > I am wondering if there is a way to do it with list comprehensions. I > know how I would do it with a ternary operator..... This should work: res = [[s, 'NULL'][not len(s)] for s in line.split(",")] Diez From newsgroups at jhrothjr.com Wed Dec 3 20:01:24 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 3 Dec 2003 20:01:24 -0500 Subject: Adding attribute to object References: Message-ID: "marco" wrote in message news:bql1gc$r9c$2 at s1.read.news.oleane.net... > hi > > I've got a class "myClass" ... and i CAN'T EXTENDS this class! > But i can add NEW methods to "myClass", like that : > > method = new.instancemethod( myNewMethod , None, myClass) > myClass.__dict__[method.__name__] = method > > i'd like to add NEW attributs to "myClass" ... > i'm pretty sure it's possible (with "get/set-attr") ... but i don't know how > to do that > in fact, i'd like to wrap an newAttribut to an existingAttribut ... > can anyone drop me 3 lines on how to do that ? I'm not at all sure what you're trying to do, since new. simply isn't necessary. if you have a class class FooBar(object): pass and you want to add an attribute to it, just do it. FooBar.newAttr = "Hi, There." Of course, Jay O'Connor is also correct - why would you want to do that? (There are reasons why you might, it just doesn't seem like a novice type thing to do.) John Roth > > > > From lkcl at lkcl.net Tue Dec 16 13:35:41 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 18:35:41 +0000 Subject: rexec.py unuseable In-Reply-To: <1071587601.3fdf2111afc59@mcherm.com> References: <1071587601.3fdf2111afc59@mcherm.com> Message-ID: <20031216183541.GH17021@lkcl.net> On Tue, Dec 16, 2003 at 07:13:21AM -0800, Michael Chermside wrote: > Suppose that had some code which had an object representing a > directory, with a method "open(filename, mode='r')" that opened > files in the directory. Given this object, you could imagine > constructing new objects with more limited capabilities. yep. in a very simple manner, with capabilities lists. > For > instance, you might create a readOnlyDirectory object which had > a method "open(filename)" that didn't allow specifying the mode > as anything but 'r'. Or you might open a file and then pass a > file object with "read()", "write()", "seek()", and other such > methods, which would only access that file. this could be achieved very simply by setting a CCL with "deny everything" permissions on an object that, ordinarily, had a full set of functions with NO restrictions, but leaving read() alone. _and_ also, importantly, adding a CCL onto the __builtins__ etc as already discussed to restrict bypassing. > So _IF_ the only way to access files were through this object (and > that's a BIG if), then you could imagine a world where HAVING and > object was equivalent to being able to do something. If a bit of > code had access to a read-only-file object then it could read that > file, but couldn't write to it, or do anything else with the file > system unless it ALSO had access to some OTHER objects. yep. > That's > capabilities... and it would work for most kinds of restricted > resources, not just the file system. The key idea is that HAVING > a pointer to the object is equivalent to having the permission to > USE that object, and whatever it provides access to. ah... that's where you and i differ, based on my experience of ACLs in NT. i envisage a separate "execute" permission from a "read" and "write" permission, a bit like directory permissions on a POSIX filesystem. under such a scheme where "execute" capability permission exists as well as "read" and "write", simply having access to an object does NOT guarantee you any rights to CALL that object, because if it doesn't have "execute" permission you can't execute [viz, call] it! ... but what you _can_ do is pass that object to another function which _does_ have execute permissions. how the hell is _that_ achieved, i hear you say??? well imagine a CCL as follows: [('totally_restricted_function, 'DENY', 'All permissions'), ('slightly_less_restricted_function', 'ALLOW', 'execute and read')] and this CCL is applied to the above-mentioned readOnlyDirectory object. if totally_restricted_function() calls slightly_less_restricted_function(), passing a readOnlyDirectory object to it, then according to the CCL above, ONLY slightly_less_restricted_function() may call functions in that object. cute, huh? l. From http Sat Dec 27 06:31:07 2003 From: http (Paul Rubin) Date: 27 Dec 2003 03:31:07 -0800 Subject: Project dream References: <3fecb9f1$0$326$e4fe514c@news.xs4all.nl> Message-ID: <7xbrpujy4k.fsf@ruckus.brouhaha.com> hwlgw at hotmail.com (Will Stuyvesant) writes: > How long do you think a new roguelike from scratch would take in > Python and where the most time is spent? These things can be as simple or as complicated as you like. Remember that the original Rogue ran on a PDP-11 so it can't have been that large. > I am afraid of a lot of work on options like magic and +ToHit etc., > while I am more interested in a smaller set of options but with a > really smart AI. Well, that's lots of work too. From gh at ghaering.de Tue Dec 2 09:19:47 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 02 Dec 2003 15:19:47 +0100 Subject: Can Python be run off of a CD-ROM? In-Reply-To: References: <3FCC8C92.406@ghaering.de> Message-ID: <3FCC9F83.7050405@ghaering.de> Fredrik Lundh wrote: > Gerhard H?ring wrote: > >>Here's the HOWTO, in one sentence: >> >>Grab a Python directory, copy the python{major}{minor}.dll from >>%SYSTEMROOT%\system32 into this Python directory. > > is the part after the comma really necessary? > > (all installers I've ever used or created install the core DLL in the > Python directory as well. are there installers out there that don't > do that?) The Pythonlabs (or should it be called python-dev installer by now?) installer doesn't do this. At least not in the Windows 2000 and XP installations I use. -- Gerhard From spiffy at worldnet.att.net Tue Dec 9 16:49:39 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 21:49:39 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Fredrik Lundh" wrote in message news:mailman.261.1070970251.16879.python-list at python.org... > "Spiffy" wrote: > > > > How can I run this other program from a python script and pass the > > filename > > > as a parameter? > > > > import os > > > > filename = "myfile" > > os.system("program %s" % filename) > > > > > > > > Fredrik, the example you provided is virtually the same as the one from the > > "Learning Python" book. > > that indicates that it's supposed to work, don't you think? IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? > > When I run it, the dos command line appears with the message 'Bad command > > or file name". > > that indicates that Windows cannot find the command, don't you think? > > > Both the .exe and the .mid file are in the python path and the spelling has > > been checked. > > you mean sys.path? IF I HAD MEANT sys.path, I WOULD HAVE SAID sys.path, DON'T YOU THINK? that's the problem, most likely. As mentioned in the > documentation, os.system() executes the command just as if you've typed > it in a "DOS box". Windows doesn't look at the Python path when you do > that, so to make sure Windows finds the command, you have to add it to > the Windows path (the PATH environment variable), or provide the full path > to os.system(). > > program = r"x:\full\path\to\program" > filename = "..." > os.system("%s %s" % (program, filename)) > > the os.path.abspath() function can be useful in cases like this; it makes sure > that if your program can find a file, another program can also find it: > > program = os.path.abspath("x:/somewhere/program") > filename = os.path.abspath("somefile") > os.system("%s %s" % (program, filename)) > > (if the filename may contain spaces, you may have to add quotes around > the second %s) TYPING THE FULL PATH GIVES ME THE SAME RESULT: NOTHING. THE ABOVE CODE USING os.path.abspath CAUSES A DOS BOX TO APPEAR AND DO NOTHING WHILE PYTHON CRASHES. > the relevant manual page contains more information on os.system, and > mentions a couple of alternatives (os.startfile, os.spawnlp, etc): > > ?http://www.python.org/doc/current/lib/os-process.html > > > Pardon me for being a newbie, but if you don't have an answer, why do you > > have to give me attitude? > > os.system() is still the answer; the problem is in how you used it and what > you expected from it, not in the function itself. You cannot expect people > to read your mind, and then complain when they fail. I DID NOT ASK ANYONE TO READ MY MIND, NOR DID I COMPLAIN THAT ANYONE COULD NOT READ MY MIND. I DO NOT THINK THE PROBLEM IS IN HOW I USED THE FUNCTION NOR WHAT I EXPECTED FROM IT. > From __peter__ at web.de Mon Dec 29 03:31:57 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Dec 2003 09:31:57 +0100 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Martin v. Loewis wrote: [RTL Mini-Howto] Yup. Your outline made it clear that the problem does not lend itself to a quick hack that trades simplicity against proper cut-and-paste behaviour. > Then, for AL runs, you need to replace European numerals with Arabic > numerals (but keeping the LTR order). I always thought of numbers as most significant digit first. But the above suggests that they are least significant digit first, preserving the original RTL directionality. Peter From bhan at andrew.cmu.edu Thu Dec 25 13:43:48 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Thu, 25 Dec 2003 13:43:48 -0500 (EST) Subject: Threaded server: what's wrong with this code? In-Reply-To: References: Message-ID: Ah - never mind. When reading SocketServer.py I found I should have used ThreadingTCPServer instead of TCPServer (and I don't even need to create threads myself!). Thank you for the reply though. Ben On Thu, 25 Dec 2003, Ahmed MOHAMED ALI wrote: > Hi, > Sorry for my bad english because i am French-speaking. > The problem is in JMSocketThread.handle .When this function terminates its > execution flow,the parameter "self.request" is not longer valid. > So the thread work with an invalid socket.For this reason,you got the 'Bad > file descriptor' error. > To correct the problem here's the modified code. > > #---Modified JMHandler class > > class JMHandler (SocketServer.BaseRequestHandler): > def handle (self): > print 'Client connected...' > threadEvent = Event() # create an event to wait for the thread > JMSocketThread(self.request,threadEvent ).start() # don't forget > to pass the event parameter here > print 'Request handed off to a thread.' > threadEvent.wait() > > #---Modified JMSocketThread class > > class JMSocketThread (threading.Thread): > def __init__ (self, theSocket): > > threading.Thread.__init__(self,target=self._myRun,args=[theSocket,theEvent]) > # don't forget to pass the event here > def _myRun (self,theSocket,theEvent): #don't forget to pass the event > here too > global THREAD_COUNT > THREAD_COUNT+=1 > print 'Threaded request started (%d)...'%THREAD_COUNT > input='' > while 1: > input += theSocket.recv(1024) > if len(input) and input[-1]=='\n': break > input=input.strip() > > print 'Got input: \'%s\''%input > if input=='Is it you?': > theSocket.sendall('Yes honey.\n') > > print 'Threaded request finished.' > THREAD_COUNT-=1 > theEvent.set() # set the event here to tell the handler to exit > > > Best regards, > Ahmed > > > "Fortepianissimo" wrote in message > news:ef08387c.0312241345.26a1430d at posting.google.com... > > Below are three simple scripts: jmSocketLib.py contains library code > > for socket server and client, server.py instantiates a server binding > > to port 50000+ (grab the first available port), and client.py > > simulates 1000 consecutive connection requests to the server (stress > > test). The client searches from port 50000 for the server, and sends a > > challenge "JM?" and expects to get a response "0_87" - otherwise > > anything that happens to own a port 50000+ would be mistaken to be the > > real server. > > > > The code: > > > > ---------- jmSocketLib.py ---------- > > #!/usr/bin/env python > > > > import SocketServer,socket,threading > > > > PORT_MIN=50000 > > PORT_MAX=50005 > > > > THREAD_COUNT=0 > > > > class JMSocketThread (threading.Thread): > > def __init__ (self, theSocket): > > > threading.Thread.__init__(self,target=self._myRun,args=[theSocket]) > > def _myRun (self,theSocket): > > global THREAD_COUNT > > THREAD_COUNT+=1 > > print 'Threaded request started (%d)...'%THREAD_COUNT > > input='' > > while 1: > > input += theSocket.recv(1024) > > if len(input) and input[-1]=='\n': break > > input=input.strip() > > > > print 'Got input: \'%s\''%input > > if input=='Is it you?': > > theSocket.sendall('Yes honey.\n') > > > > print 'Threaded request finished.' > > THREAD_COUNT-=1 > > > > > > class JMHandler (SocketServer.BaseRequestHandler): > > def handle (self): > > print 'Client connected...' > > JMSocketThread(self.request).start() > > print 'Request handed off to a thread.' > > > > > > class JMServer (SocketServer.TCPServer): > > def __init__ (self): > > port=PORT_MIN > > while port > try: > > SocketServer.TCPServer.__init__(self,('',port),JMHandler) > > print 'Bound port %d'%port > > break > > except: > > port+=1 > > > > class JMClient: > > def __init__ (self): > > port=PORT_MIN > > > > while port<=PORT_MAX: > > try: > > self.socket=socket.socket(socket.AF_INET, > > socket.SOCK_STREAM) > > self.socket.connect(('',port)) > > self.socket.sendall('Is it you?\n') > > print 'Query sent...' > > reply='' > > while 1: > > reply += self.socket.recv(1024) > > if len(reply) and reply[-1]=='\n': break > > reply=reply.strip() > > > > print 'Got reply: \'%s\''%reply > > > > if reply == 'Yes honey.': > > print 'Found the server at port %d'%port > > break > > else: raise None > > except: > > self.socket.close() > > port+=1 > > > > > > ---------- server.py ---------- > > #!/usr/bin/env python > > > > from jmSocketLib import * > > > > if __name__ == '__main__': > > jmServer=JMServer() > > jmServer.serve_forever() > > > > ---------- client.py ---------- > > #!/usr/bin/env python > > > > from jmSocketLib import * > > > > if __name__ == '__main__': > > # stress test > > for i in range(1000): > > print i > > JMClient() > > > > > > > > > > Now the problem is, every now and then I got this error from the > > server side: > > > > ---- ERROR on server side ---- > > Client connected... > > Threaded request started (1)... > > Request handed off to a thread. > > Got input: 'Is it you?' > > Exception in thread Thread-125: > > Traceback (most recent call last): > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > > line 436, in __bootstrap > > self.run() > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > > line 416, in run > > self.__target(*self.__args, **self.__kwargs) > > File "/Users/ben/temp/jmSocketLib.py", line 25, in _myRun > > theSocket.sendall('0_87\n') > > File "", line 1, in sendall > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/socket.py", > > line 143, in _dummy > > raise error(EBADF, 'Bad file descriptor') > > error: (9, 'Bad file descriptor') > > -------------------------- > > > > Of course the client then freezes: > > > > > > ---- Client output ---- > > 124 > > Query sent... > > (and freezes) > > > > > > Does anyone have an explanation why this didn't work? Thanks a lot! > > > From __peter__ at web.de Fri Dec 19 13:21:01 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 19:21:01 +0100 Subject: Parsing environment variables in ConfigParser files References: <3a8e83d2.0312190936.1746d659@posting.google.com> Message-ID: Matthew Barnes wrote: > I'm considering submitting a patch for Python 2.4 to allow environment > variable expansion in ConfigParser files. The use cases for this > should be obvious. I'd like to be able to specify something like the > following in a configuration file: > > [section_name] > data_file=${HOME}/mydata.dat > > ...(where HOME=/home/matt) and have ConfigParser automatically expand > it to: > > [section_name] > data_file=/home/matt/mydata.dat > > The change is pretty straight-forward, but I'm interested in feedback > on whether this is a good idea, what the syntax for environment > variable references should look like (currently I'm thinking > ${varname}), or whether there are any hidden complexities or > backward-compatibility concerns. > > Matthew Barnes I think this can be easily achieved by subclassing the ConfigParser: >>> from ConfigParser import ConfigParser >>> class ExpandingParser(ConfigParser): ... def getexpanded(self, section, option): ... import os ... return self._get(section, os.path.expandvars, option) ... >>> p = ExpandingParser() >>> p.read("expand.ini") >>> p.get("paths", "mydir") '$HOME/of/the/brave' >>> p.getexpanded("paths", "mydir") '/home/peter/of/the/brave' >>> If you will bother with the library implementation at all, I would prefer this level of explicitness, i. e. a dedicated getexpanded() method in ConfigParser, or alternatively a subclass that overrides _get() to always expand in the getXXX() methods. With both approaches you can stay safely away from backwards compatibility problems. Peter From chrishad95 at yahoo.com Mon Dec 1 10:54:26 2003 From: chrishad95 at yahoo.com (Chris Hadley) Date: 1 Dec 2003 07:54:26 -0800 Subject: Install problem on AIX References: Message-ID: Hi Donn, Thanks for your reply. I thought that having the 2.3b2 already installed may be causing problems so I modified the makefile version to be 2.3.2 instead of 2.3 which caused the make install to go to the /usr/local/lib/python2.3.2 directory. This seems to have worked. The make install completed. From noemail at noemail4u.com Thu Dec 18 13:32:25 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 18 Dec 2003 18:32:25 GMT Subject: newbie architecture question References: Message-ID: <4fd88d597a851c9fa36401f4f2051f7e@news.teranews.com> On Fri, 12 Dec 2003 08:35:39 -0500, "Joe Poniatowski" wrote: >I wish to define a hierarchy of classes - something like book, chapter, >page, where books are made of one or more chapters, and chapters consist of >one or more pages. Should the definitions be nested, or all at the module >level with just the instantiations nested? That sounds more like a hierarchy of containers, rather than a hierarchy of classes. A class hierarchy is used when the "is-a" relationship is always true. A book is not a chapter is not a page. Given that, they should be defined at the same level (or at least *not* nested), and then instances of one can contain instances of the other. E.g., a book object can contain instances of chapter objects, which can contain instances of page objects. --dang From emile at fenx.com Sat Dec 6 17:19:20 2003 From: emile at fenx.com (Emile van Sebille) Date: Sat, 6 Dec 2003 14:19:20 -0800 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com><8089854e.0312050419.2cf36e34@posting.google.com><30oAb.9577$aw2.4588872@newssrv26.news.prodigy.com> Message-ID: Skip Montanaro: > [ quoting me ] > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > >>> b = intern('foo bar') > >>> a = 'foo bar' > >>> a is 'foo bar' > False > >>> b is 'foo bar' > False > > Emile> That apparent space requirement should really be better documented. > > The fact that the current implementation of CPython automatically interns > strings which look like identifiers is simply an efficiency consideration. > It's not part of the language definition, so doesn't bear documenting. The > correct way to compare two strings is using '==' (which is independent of > CPython's implementation details), not 'is'. > > Skip > OK. But does intern() intern? I (thought I) only used is to show that it wasn't intern()'d, and as the documentation holds intern'ing up as an optimization technique, does it _only_ apply to strings that look like identifiers? How else might you know? Emile van Sebille emile at fenx.com From Raaijmakers, Vincent (IndSys, Wed Dec 10 17:59:24 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Wed, 10 Dec 2003 16:59:24 -0600 Subject: Invocation, how to Message-ID: <971323274247EB44B9A01D0A3B424C85043457B1@FTWMLVEM02.e2k.ad.ge.com> Oh.. this is soooooo easy. python rules Thanks. -----Original Message----- From: python-list-bounces+vincent.raaijmakers=ge.com at python.org [mailto:python-list-bounces+vincent.raaijmakers=ge.com at python.org]On Behalf Of Robert Brewer Sent: Wednesday, December 10, 2003 4:44 PM To: python-list at python.org Subject: RE: Invocation, how to One way would be: getattr(foo, "method")(arg1, arg2, ...) FuManChu > -----Original Message----- > From: Raaijmakers, Vincent (IndSys,GE Interlogix) > [mailto:Vincent.Raaijmakers at ge.com] > Sent: Wednesday, December 10, 2003 1:32 PM > To: python-list at python.org > Subject: Invocation, how to > > > I admit.. must be in the manual but can't find it. > > > If my method is a string, say "method" > > How to call foo."method" ? > This is invocation in java, but how to do it in python? > > Thanks, > Vincent > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list From bwglitch at hotpop.com Thu Dec 4 08:43:42 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Thu, 04 Dec 2003 08:43:42 -0500 Subject: py2exe question from a total beginner In-Reply-To: References: Message-ID: sarmin wrote: > Hi Gurus... > > I am using pythonwin to write the programming code and boa > constructor to build the GUI... the GUI and the python code work > fine when run through pythonwin platform... > > i m now trying to create an executable python code that can be used > on computers that do not have python software installed... py2exe is > the definitely the one i m looking for... however i m simply not > sure how to use this software (py2exe)... moreover i havent got a > clue about using the python distutils function... > > for simplicity, i dont understand the followings: > run: > > python setup.py py2exe --help > > setup.py is the distutils setup-scripts... > > how do i run this command?? is it through the pythonwin interactive > mode?? by the way, i m a total beginner in using python (i m a > python baby, less than 1 month old)... > > any helps are very much appreciated... Here it explains how to write the setup.py http://starship.python.net/crew/theller/py2exe/ Once you got the setup.py, run it in the command prompt: python setup.py py2exe That should work. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "... Have some faith in me!" "As much as you'd like to think so, Cheetor, this isn't about you." -- Cheetor and Optimus Primal, "Equal Measures" From parken at ferger.de Thu Dec 18 16:17:42 2003 From: parken at ferger.de (Olaf Ferger) Date: Thu, 18 Dec 2003 22:17:42 +0100 Subject: Module for Informix Database? References: Message-ID: On Thu, 18 Dec 2003 17:24:12 +0100, Jan Kesten wrote: >does anybody know, if there is a module to connect to an Informix >database? I looked around, but I have seen there only modules for Python >1.x - and this ones do not work with 2.x ;-( AFAIK it's definitely possible to use module 'informixdb' (http://starship.python.net/crew/sturner/informixdb.html) with Python2.x (although installing the module for Python 2.x is tricky)! And it only implements version 1.0 of the DB-API specification. But, that was good enough for me ;-) -- EOP From mwh at python.net Sun Dec 14 09:34:03 2003 From: mwh at python.net (Michael Hudson) Date: Sun, 14 Dec 2003 14:34:03 GMT Subject: ANN: lunatic-python 0.1 References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> Message-ID: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > In article <7xd6atgnwx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >Gustavo Niemeyer writes: > > > [snip] > >But you left out the most important question: WHY? > > Not the reason cited on the page, but: Python is great for writing > apps (that is, for _me_), and Lua is great for simple (even easier > than Python) scripting of apps (that is, for the _user_). So that's > one possible use... I also happen to know that a) apt-rpm is scriptable with lua b) Gustavo Niemeyer is involved with the development of apt-rpm c) Gustavo likes Python I suspect there may be connections between the above statements :-) Cheers, mwh -- >> REVIEW OF THE YEAR, 2000 << It was shit. Give us another one. -- NTK Now, 2000-12-29, http://www.ntk.net/ From newsgroups at jhrothjr.com Tue Dec 23 11:22:28 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Dec 2003 11:22:28 -0500 Subject: Operator overloading and __getattr__ References: Message-ID: "Samuel Kleiner" wrote in message news:slrnbue5dp.72h.sam at h41n2fls31o839.telia.com... > I'm trying to create methods on method access- but __getattr__ fails > with operator overloading(below) Any suggestions? EG: I haven't a clue what you're trying to do, but I believe it's not possible to install "magic methods" after the class is defined. Nor can you install them in the instance. They'll look like they've been installed, but the interpreter will never execute them because it does not look there for them. It looks in special places in the C language structure for the class definition. John Roth > > class NewM(dict): > def __getattr__(self,name): > def fi(m): > if type(name) in self: > self[type(name)]=self[type(name)].__dict__[name](m) > else: > self[type(name)]=m > return fi > > p=int(2) > s=NewM() > print p.__add__(2) > print s.__add__(2) > print p+2 > print s+2 > > Causes TypeError on the last line > > -- > "I know, there is no Nobel Prize in preternatural biology. That's > because Alfred Nobel's wife was seduced by a vampire." --Andrew Plotkin From tjreedy at udel.edu Thu Dec 11 14:01:04 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Dec 2003 14:01:04 -0500 Subject: HalfLife/Cstrike monitorring References: <3fd84154$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: <1sSdnUzIifRyI0WiRVn-sQ@comcast.com> "Guyon Mor?e" wrote in message news:3fd84154$0$251$4d4ebb8e at news.nl.uu.net... > Hi all, > > I want to write a HalfLife/CStrike monitor, to make some nice statistics for > an upcoming LAN-party. I've found some pointers on how to use the protocol, > but now I have to do the following: > > 1. make an UDP connection > 2. send a string(?) like '\xFF\xFF\xFF\xFFdetails\x00' > 3. translate the response into bytes and strings :-s > > for more details on this protocol see: > http://dev.kquery.com/index.php?article=31 > > I hope someone can help me with at least the first 2 steps. Try Googling 'Python HalfLife monitor' (200+ hits). 'Python UDP monitor' gets you to more general info (first is UDP support in Twisted). TJR From jay at jaydorsey.com Sun Dec 21 19:29:33 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sun, 21 Dec 2003 18:29:33 -0600 Subject: Count Files in a Directory In-Reply-To: <93f5c5e9.0312211545.363b91a6@posting.google.com> References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: <20031222002933.GA12400@gentoo.Earthlink.net> On Sun, Dec 21, 2003 at 03:45:31PM -0800, hokiegal99 wrote: > I'm trying to count the number of files within a directory, but I > don't really understand how to go about it. This code: > Do you want the total number of files under one directory, or the number of files under each directory? > for root, dirs, files in os.walk(path): > for fname in files: > x = str.count(fname) > print x > > Produces this error: > > TypeError: count() takes at least 1 argument (0 given) str.count() is a string method used to obtain the number of occurences of a substring in a string (try help(str.count)) >>> n = "this is a test" >>> n.count("test") 1 > > for root, dirs, files in os.walk(path): > for fname in files: > x = list.count(files) > print x > > TypeError: count() takes exactly one argument (0 given) > > Also wondered why the inconsistency in error messages (numeric 1 vs. > one)??? Using 2.3.0 Similar problem here, for a list method ( try help(list.count)). >>> n = ["test", "blah", "bleh"] >>> n.count("test") 1 In your example, fname would be an individual file name within a directory list of files (in your example, the variable files). What you probably want is len(), not count(). If you want the number of files in each directory try: >>> for root, dirs, files in os.walk(path): ... print len(files) Or, for the total number of files: >>> filecount = 0 >>> for root, dirs, files in os.walk(path): ... filecount += len(files) >>> print filecount hth -- Jay Dorsey jay at jaydorsey dot com From skip at pobox.com Sat Dec 27 16:52:22 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 27 Dec 2003 15:52:22 -0600 Subject: lists with zero-valued elements In-Reply-To: <3c228754.0312271335.4acfe0fb@posting.google.com> References: <3c228754.0312271335.4acfe0fb@posting.google.com> Message-ID: <16365.65302.582207.577255@montanaro.dyndns.org> Nick> Any body knows a trivial way to enumerate a list with n Nick> zero-valued elements? I'm not sure what you're asking. I'd enumerate a list with n zero-valued elements the same way I'd enumerate one with m zero-valued elements: nelements = len(somelist) If I wanted to count how many elements were zero, I might do something like: nzeros = 0 for element in somelist: if element == 0: nzeros += 1 or more succinctly: nzeros = len([element for element in somelist if element == 0]) Skip From buzzard at urubu.freeserve.co.uk Sat Dec 27 14:01:03 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 27 Dec 2003 19:01:03 -0000 Subject: callable classes References: Message-ID: "anton muhin" wrote in message news:bsi06a$d532h$1 at ID-217427.news.uni-berlin.de... > Duncan Smith wrote: > > I recently started to rewrite a class and decided to take a bunch of related > > methods and put them in a separate callable class. (They're all what I > > would call pointwise operations on pairs of instances, they raise exceptions > > for identical reasons, and they all return a new instance). It seemed like > > a good idea at the time, but now I'm not so sure. So my very general > > questions are: > > > > Is this a reasonable use for a callable class? > > > > In what circumstances are callable classes particularly useful? (Maybe I > > haven't racked my brains long enough.) > > > > Cheers. TIA. > > > > Duncan > > > > What do you mean by 'callable class'? Classes are callables. Ot you mean > a class that defines __call__ method? In this case it's really useful. > > regards, > anton. Yes, I meant a class that defines a __call__ method. Cheers. Duncan From bjorn.pettersen at comcast.net Fri Dec 26 05:13:44 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Fri, 26 Dec 2003 04:13:44 -0600 Subject: Socket Programming References: Message-ID: [posted and mailed] "trainee" wrote in news:S6LGb.5854$UB3.2232 @nwrddc03.gnilink.net: > Do you think you could recommend a book on Python that includes sockets? Starting on the web first (it's free :-) the socket howto is probably your best bet: http://www.amk.ca/python/howto/sockets/ You can also look at asynchronous sockets at: http://squirl.nightmare.com/medusa/async_sockets.html When it comes to books, most of them seem to have decent chapters on it. I like "(the eff-bot guide to) The Standard Python Library", but my copy is severely dated :-) I think he finally published it as a "real" book, but I haven't seen a recent copy... "Python Programming on Win32" has a short section on sockets that might be enough, and if you're going to work on win32 systems I'd definitely recommend it. The Python Cookbook has a couple of receipes on sockets (and everything else ;-) You can get the receipes on the web at http://aspn.activestate.com/ASPN/Python/Cookbook/ Finally, I'd be very surprised if "Python in a Nutshell" by Alex Martelli didn't have the best coverage of them all, however that book is still on my list so I'll have to let someone else comment on it... -- bjorn From p at trick.lu Sun Dec 7 12:24:08 2003 From: p at trick.lu (Patrick Useldinger) Date: Sun, 07 Dec 2003 18:24:08 +0100 Subject: OT: Spell checker Message-ID: Hi all, off-topic, but related: In order to write a decent User Guide for Software, I want to spell check the text in English (German and French would be nice too.) The doc is written using txt2tags, so it's basically pure text. Therefore, I am looking for a spell-checker that works on pure text files. Not the kind where you can enter *one* word at a time, and not the kind that will work only with an online connection. I have spend a lot of time googling, but to no avail. Can anybody point me into the right direction? -PU -- visit my homepage at http://www.homepages.lu/pu/ From mcfletch at rogers.com Wed Dec 3 14:02:42 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Dec 2003 14:02:42 -0500 Subject: diferences between 22 and python 23 In-Reply-To: References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> Message-ID: <3FCE3352.2040504@rogers.com> Fredrik Lundh wrote: >Enrique wrote: > > > >>running a script that works fine in python 22 in python 23 i find something >>like: >> >>unicodedecodeerror: "ascii" codec dan+t decode byte 0xed in position >>37:ordinal not in range (128) >> >>Usually major versions of python were courteus with the previous versions... >> >> > >0xED has never been a valid 7-bit ASCII character. > > Sure, but Python used to accept 8-bit characters in the platform's default encoding as part of string characters... Most likely Enrique has a \xED somewhere in a string literal in his code that is intended to be an i-accent-ague. That would have worked fine in all versions of Python before 2.3, but started failing in 2.3 due to the decision that all string literals would be converted to unicode and back and that the default encoding for such conversions would be ASCII (whereas previously it would most closely have been approximated by "platform's local 256-char encoding"). PythonWin 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> print '23\xED' 23? So, Enrique, what you're probably looking for is this: # -*- coding: ISO-8859-1 -*- for latin-1, or # -*- coding: cp1252 -*- for Windows code-page. You add these "magic" comments to the top of your Python source files to tell the interpreter that you're using a particular encoding for your Python string literals. Even if you're just using string literals to store binary data, you'll still need to use a dummy encoding, such as latin-1. Yes it's a bit of a pain, but the decision was made, so we have to deal with it :) . I'm assuming that somewhere in the "new in 2.3" pages is a huge warning to the effect that this breaks lots of old code, but Enrique can be forgiven for missing it, as I think I managed to miss it too, all I found was this: *Encoding declarations* - you can put a comment of the form "# -*- coding: -*-" in the first or second line of a Python source file to indicate the encoding (e.g. utf-8). (PEP 263 phase 1) Which doesn't actually mention the breakage of code that results. True, theoretically the code was never valid, but *lots* of people used 8-bit encodings quite happily with earlier versions and do find their code breaking in 2.3 because of this. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bokr at oz.net Wed Dec 17 15:57:48 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Dec 2003 20:57:48 GMT Subject: Converting integer to binary representation References: <3fe04d14$0$127$3a628fcd@reader1.nntp.hccnet.nl> <3fe0879e$0$3323$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: On Wed, 17 Dec 2003 17:39:52 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > >> >>> list(10) >> >>> [True,False,True,False] > >Sorry, I was dead wrong here, or maybe not, it all depends on the >future. > >The code below here would make the positions of the booleans >correspond to the powers of two: > > >>> list(10) > >>> [False,True,False,True] > >But the other interpretation has some merit too since it corresponds >to the way we use strings to denote numbers. There is a choice between >left-to-right and right-to-left here, analogous to the "most >significant bit" issue. > >Because these interpretations are more or less equally valid, there is >no obvious way of doing it. Making an explicit choice here would be >good since that would remove the ambiguity. Guido could use his time >machine to make one of these alternatives the obvious way to do it. > IMO little-endian is a better choice. The value of a number in terms of bits is pretty naturally spelled sum([bit*2**pow2 for pow2, bit in enumerate(bitlist)]) i.e., >>> bitlist = [False,True,False,True] >>> sum([bit*2**pow2 for pow2, bit in enumerate(bitlist)]) 10 Regards, Bengt Richter From tjreedy at udel.edu Sat Dec 13 14:36:18 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Dec 2003 14:36:18 -0500 Subject: ANN: lunatic-python 0.1 References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message > But you left out the most important question: WHY? Generically, people experiment because they find a project interesting or challenging. Besides ego, they post in case there are at least a couple of the thousands of readers and archive searchers interested in the topic. [second post] > Well, yeah, but Python is sort of similar, and somebody who chooses > one has generally decided that it fills their needs better than the > other. So why such a fancy interface between them? Suppose a Python afficionado, like me, find an app that he wants to use that has Lua as the scripting engine (I have seen such) and the person, like me, does not really want to learn Lua. A bridge requiring only a minimum of Lua knowledge would make the app more interesting. Terry J. Reedy From Mike at kordik.net Fri Dec 26 19:37:29 2003 From: Mike at kordik.net (Mike) Date: Fri, 26 Dec 2003 19:37:29 -0500 Subject: How to determine if an instance of your program is already running? Message-ID: Does python support named semaphores for Linux? I saw that ActivePython for Win32 does. Can I get a list of currently running processes? I already posted in the GTK forum about looking for the window title. Thx From mwh at python.net Thu Dec 11 09:33:10 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 11 Dec 2003 14:33:10 GMT Subject: how do i get a "wide build" precompiled python w support unicode higher than 'ffff' References: Message-ID: "Posadas, Dennis" writes: > I don't want to have to compile python, but I need one ready to support > unicode that includes CJK. Umm. I didn't think CJK characters went beyond the basic multilingual plane (think that's what it's called). Python doesn't ship with any CJK codecs, though -- is that what you're complaining about? You can get them from somewhere -- somewhere on SF I think, but it seems to be doing the "down for maintenence" thing right now. Cheers, mwh -- This makes it possible to pass complex object hierarchies to a C coder who thinks computer science has made no worthwhile advancements since the invention of the pointer. -- Gordon McMillan, 30 Jul 1998 From fredrik at pythonware.com Wed Dec 17 16:46:22 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Dec 2003 22:46:22 +0100 Subject: change dpi without changing pixels dimensions with PIL? References: <3fe01f2a$0$44014$e4fe514c@dreader9.news.xs4all.nl> Message-ID: "duikboot" wrote: > In Photoshop I can, when I want to change the dpi(dots per inch) of a > picture, arrange that the picture won't be resized. Do you know of a way, I > can accomplish this in python with PIL? If I use this script it changes the > dpi, but the picture becomes huge. > > Thanks > > Arjen > > import sys > import Image > import os > a=sys.argv[1] > print a > c="or"+a > b=os.system("rename %s %s" % (a, c)) That's usually spelled os.rename(a, c) > im=Image.open(c) > print im.info["dpi"] > im.save(a, dpi=(150, 150)) I think you're confusing image size with file size. "Image.open" loads the image into a PIL Image object, and "save" creates a new file from the contents of that object. The image size (in pixels) doesn't change when you do this. However, the file size may change. For some file formats, PIL can read compressed files but not write files using the same compression (usually for legal reasons). GIF is one such example. TIFF LZW is another one. If you can, use PNG instead. From FBatista at uniFON.com.ar Thu Dec 11 09:22:38 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 11 Dec 2003 11:22:38 -0300 Subject: check disc space Message-ID: dw-google.com at botanicus.net wrote: #- But "if estimated_space > int(free_space * 1.05): ..." might not be #- such a bad thing when there is no other route to sanity available. But, what is "free disk space"? Remember that a file of 10 bytes, doesn't get 10 bytes of disk. So, if you want to write 10 files of ten bytes each, how much "free disk space" will you want? In what OS? With what filesystem? . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From R.Byrom at rl.ac.uk Mon Dec 1 10:08:50 2003 From: R.Byrom at rl.ac.uk (Byrom, R (Rob) ) Date: Mon, 1 Dec 2003 15:08:50 -0000 Subject: gzipping several files Message-ID: hi, Does anyone know how to read-in several files and then batch all together into a *.zip format? I've looked at the gzip module but I'm not sure how to use this with several files. Any help gratefully received! Rob From max at alcyone.com Thu Dec 18 00:05:27 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 17 Dec 2003 21:05:27 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: <3FE13597.9CE3A583@alcyone.com> "Brandon J. Van Every" wrote: > "Richard Brodie" wrote in message > news:brpop1$1636 at newton.cc.rl.ac.uk... > > > That said, Brandon's claim was fairly contentious and likely to get > > someone to bite. It's a well worn debate though, and c.l.py probably > > isn't the best place to renew it. > > It was a comment made in passing, and it takes quite a Trollhunter to > make > it otherwise. Outstanding! You're so paranoid about being called a troll you whine about being called one even when you weren't! -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I'm the woman whose / Three wishes came true -- Lamya From fowlertrainer at anonym.hu Fri Dec 5 10:30:32 2003 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Fri, 5 Dec 2003 16:30:32 +0100 Subject: How to I delete key from dictionary ? Message-ID: <12928164127.20031205163032@anonym.hu> Hello python-list, How to I delete key from dictionary ? Like this: d={1:'a'} d.delete(1) ???? -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From jdhunter at ace.bsd.uchicago.edu Tue Dec 16 11:39:32 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 16 Dec 2003 10:39:32 -0600 Subject: traceback as string Message-ID: What is the best way to get the traceback as a string. I tried def exception_to_str(s = None): sh = StringIO.StringIO() if s is not None: print >>sh, s traceback.print_stack(sh) return sh.getvalue() but got Traceback (most recent call last): File "/home/jdhunter/seizure/python/eegdb/eegview/eegview.py", line 944, in on_menuFileOpen_activate msg = exception_to_str('Could not read data:') File "/hunter/jdhunter/python/projects/jdh/jdh/cbook.py", line 707, in exception_to_str traceback.print_stack(sh) File "/usr/local/lib/python2.3/traceback.py", line 235, in print_stack print_list(extract_stack(f, limit), file) File "/usr/local/lib/python2.3/traceback.py", line 266, in extract_stack lineno = f.f_lineno Thanks! John Hunter From r.s at XXmindspring.com Tue Dec 2 16:04:13 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Tue, 02 Dec 2003 21:04:13 GMT Subject: Stuck newbie References: <20619edc.0312020958.4c1700cb@posting.google.com> Message-ID: "Diez B. Roggisch" wrote ... > The last approach would be to create a class new_record: > > class new_record: > def __init__(self): > self.flags = 0 > self.list1 = [] > self.list2 = [] [another beginner here] Suppose I do the above, followed by this: records = [] rec = new_record() rec.flags = 1 rec.list1 = [10] rec.list2 = ['a'] records.append(rec) print records # [] print records[-1] # print records[-1].flags, records[-1].list1, records[-1].list2 # 1 [10] ['a'] Is there a simpler way to accomplish the last line (as I expected the simplest "print records" to do)? Thanks. -- r.e.s. From jjl at pobox.com Sat Dec 13 09:10:45 2003 From: jjl at pobox.com (John J. Lee) Date: 13 Dec 2003 14:10:45 +0000 Subject: Recording web page URLs References: Message-ID: <87d6askdui.fsf@pobox.com> "Phil D." writes: [...] > I'm building a python application that will monitor a person's > behavior with his mouse while surfing the web (probably using > Internet Explorer). I want to record the URLS of the pages he > visits. Is there a simple way to do this in python? Yes. What's the purpose of this application, Phil? John From newsgroups at jhrothjr.com Sat Dec 20 12:49:33 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 12:49:33 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Skip Montanaro" wrote in message news:mailman.374.1071937108.9307.python-list at python.org... > > > Python's design doesn't admit the option of calling functions without the > parens. Perl's and Ruby's do. On the other hand, functions are first-class > objects in Python. I don't know about Ruby, but in Perl, whether or not a > function is called or treated as a piece of data is very context-dependent, > to the point of near madness for people like myself who don't use it day in > and day out. That's one of the reasons it was a rather bad choice of example. As far as I can tell, it would be quite hard to do in any comprehensible fashion, and not backward compatible. > > John> The jihad against the "functional" builtins is a good case in > John> point. The replacements for apply, map and filter seem to be > John> adequate, and in the case of list comprehensions, pretty darned > John> useful although I think that it's a rather baroque addition to an > John> otherwise very clear and comprehensible language. > > Why do you call it a "jihad"? Guido has stated on multiple occasions that > he regretted adding functional constructs to the language. I still can't > get to the Python website (have to wait another two hours for my ISP to > reload its tables), but here's a Google pointer to an HTML-ized version of > his OSCON 2002 Powerpoint slides: > > http://216.239.41.104/search?q=cache:2QztD1KncJgJ:www.python.org/doc/essays/ppt/regrets/PythonRegrets.ppt+OSCON+%22python+regrets%22&hl=en&ie=UTF-8 I've read it before. I'm in complete agreement that the replacement for apply makes the lanugage cleaner, and I've no particular objection to list comprehensions replacing map and filter. > John> There is no replacement for lambda in sight, even though lambda is > John> arguably the ***largest single*** one of the functional constructs > John> that needs work, and has obviously needed work for a long time. > > Once again, you desire Python to be something it is not. If you want a > strong functional language, program in Lisp or Haskell. > > John> The obvious replacement for lambda, which is some form of inline > John> block, has not been seriously discussed, with proposed syntax and > John> examples, anywhere I've seen it. Clearly, I'm not ominiscient, so > John> that doesn't mean it hasn't, though. > > Anonymous blocks are not a replacement for lambdas, named functions are. > How do you pass parameters to an anonymous block? By putting them in the first line. Again, I'm not a language purist, and if the term 'block' means something to someone that causes confusion, then I regret it. Frankly, I don't think that anyone is going to come up with the ideal syntax for anonymous functions. The thing that becomes more and more apparent every time I think of it is that one of Python's real strengths, it's automatic indentation, also makes it very hard to incorporate statement syntax within expressions. > You seem to have a burr under your saddle about this stuff. I'm not sure > why. Maybe it's time to get out the curry comb. The world changes, and ideas that seemed to be perfectly appropriate five or ten years ago may no longer be such. Small languages with a limited audience have a perfect right to be as quirky or as "pure" as their authors want. Once they get beyond that point, there's a bit of social responsibility involved in addressing common problems. John Roth > > Skip > From fumanchu at amor.org Mon Dec 8 19:16:47 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 8 Dec 2003 16:16:47 -0800 Subject: using modules from different paths Message-ID: You could try something like: import os, sys localDir = os.path.dirname(__file__) sys.path.append(localDir) ...to manually add the current directory to sys.path (cut-n-paste relative paths from there)? Not sure if that would be available then to the import statement. Hope that sends you in the right direction. Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: sashan [mailto:nothing at important.com] > Sent: Monday, December 08, 2003 12:08 PM > To: python-list at python.org > Subject: using modules from different paths > > > Hi > > How do you import a module in a path that's not in sys.path. > I've got a > project and would like to split the .py files into several differrent > directories, say dir_a, dir_b, dir_c. Then I would like some > modules in > dir_a to be able to import modules from dir_c. How do I do this? > > -- > http://mail.python.org/mailman/listinfo/python-list > From r.s at ZZmindspring.com Wed Dec 31 16:12:47 2003 From: r.s at ZZmindspring.com (r.e.s.) Date: Wed, 31 Dec 2003 21:12:47 GMT Subject: PYTHONPATH unnecessary with PythonWin? References: Message-ID: "Jeff Epler" wrote ... > Python searches some directories by default. The documentation probably > describes this in more detail. Using PYTHONPATH, you can > add to that list. For instance, it's often useful (particularly on > Unix) to have a personal directory listed in PYTHONPATH (like > ~/lib/python) for your own modules. I've created one folder for that purpose, namely C:\Python23\Lib\site-packages\MyProjects and I put all my own modules in various subfolders of that one. It seems to work, but maybe I'm breaking some protocols? From mikit at zoran.co.il Mon Dec 1 03:17:51 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 1 Dec 2003 00:17:51 -0800 Subject: segfault in extension module References: Message-ID: <6250403b.0312010017.27f5f341@posting.google.com> Hello Nat, > I've written a function in C to perform protein sequence alignment. This > works fine in a standalone C program. I've added the necessary packaging > to use it in Python; Which one? Are you using the C API? > it returns three strings and an integer. However, as > soon as the function is complete, I get a segfault and the interpreter > dies. Looks like refcount problems, check out http://www.python.org/doc/current/ext/refcounts.html . IMO just avoid all this stuff and use SWIG/Boost.Python/Pyrex. HTH. Miki From oren-py-l at hishome.net Wed Dec 17 04:53:58 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 17 Dec 2003 04:53:58 -0500 Subject: Python as a numerical prototyping language. In-Reply-To: References: Message-ID: <20031217095358.GA34626@hishome.net> On Tue, Dec 16, 2003 at 09:16:33PM +0100, Carl wrote: > I have been using Python for quite some time now and I love it. I use it > mainly for explorative computing and numerical prototyping, ie testing and > trying out different kinds of algorithms and computational schemes. The use > of Python as my first-choice language has made me extremely productive. > > Now, I have always believed that Python is a poor performer in terms of > numerical speed. My experience, however, is that the efficient use of > dictionaries, lists, precompiled numerical libraries, etc makes Python a > higly competitive language for scientific computing (in comparison with > more traditional languages such as C, C++ and different versions of > Fortran). > > Where is Python heading? Will it be a viable replacement for traditional > number-crunching languages in the near-term future? It already is. When dealing with large vectors Numerical Python is your friend. The overhead of the interpreter is negligible since most of the time is spent in highly optimized vector operations. When operations are done on individual objects Python is significantly slower than compiled languages but psyco is making great progress in this area. It already approaches the performance of C for simple code using only integers and floats. Oren From news at lepidium.de Fri Dec 12 11:03:19 2003 From: news at lepidium.de (Sebastian Kress) Date: Fri, 12 Dec 2003 17:03:19 +0100 Subject: python on websites Message-ID: Hi, I'm terribly sorry for this very easy question, but I really would like to know that :). I've been programming in Python quite a while now and mostly coped quite ok. Now my Webhoster sent an eMail that they now offer support for Python on their servers, too. Since I only programmed stand-alone-software in Pyhton, I don't have a clue how to integrate Python-skripts into websites. Could anybody please tell me where to find a good online-tutorial on that? Thanks in advance, Sebastian From bobx at linuxmail.org Wed Dec 10 17:37:51 2003 From: bobx at linuxmail.org (Robert) Date: Wed, 10 Dec 2003 22:37:51 GMT Subject: [Windows] Installation/Upgrade question Message-ID: <3fNBb.1864$Zq2.1463894@news2.news.adelphia.net> When Python comes out with a bug fix version (2.3.2->2.3.3 being the next) can the setup just run and overwrite the previous installation or is an uninstall/reinstall what needs to happen? Robert From b.hall at irl.cri.nz Wed Dec 10 00:07:39 2003 From: b.hall at irl.cri.nz (Blair Hall) Date: Wed, 10 Dec 2003 18:07:39 +1300 Subject: using shelve correctly? Message-ID: <3FD6AA1B.8000804@irl.cri.nz> I am having trouble understanding the correct use of 'shelve'. I have a number of small programs that read and write to a single shelve file (not multithreading though). It seems that by writing to an existing entry I sometimes corrupt the database. For instance, I get the problem when a Python script has opened the file and read and written a few objects it then tries to overwrite an existing entry: cf = {} FILE['correction factor'] = cf FILE.sync() The program then closes the file and terminates. Now if I go back and look at the keys to the data base I find that 'correction factor' is no more and instead there is apparently 'correction factorr' (repetetion of last letter), however is I try to use that key to access the data I get a KeyError. I get the same pattern of corrupted key with other entries too (last letter repeats). It appears that by deleteing the entry before hand del FILE['correction factor'] FILE['correction factor'] = cf the problem does not occur. But I didn't think that this should be necessary. Am I using shelve incorectly? From tim.one at comcast.net Thu Dec 18 16:09:13 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 18 Dec 2003 16:09:13 -0500 Subject: cleanup after exceptions In-Reply-To: Message-ID: [Peter Otten] > ... > There seems to be some dark corner of the exception infrastructure > that exc_clear() doesn't touch. It's probably just an artifact of running in interactive mode. Then you also have to worry about sys.last_traceback (see the sys docs). From newsgroups at jhrothjr.com Sun Dec 21 08:02:18 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 08:02:18 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <2rkeb1-fs3.ln1@beastie.ix.netcom.com> Message-ID: Whoops! Forget my last response - you're absolutely right. Exec2 was a CMS language, I was thinking of Clist2 John Roth "Dennis Lee Bieber" wrote in message news:m4ofb1-123.ln1 at beastie.ix.netcom.com... > John Roth fed this fish to the penguins on Saturday 20 December 2003 > 13:13 pm: > > > languages.) It grew beyond there, but not by all that much. > > Part of it's quirky charm is the way that it's i/o system faithfully > > mirrored the old VM/CMS system. > > > That's the one feature the Amiga version did not duplicate > > Of course, since it was written to be a replacement for exec2, it > probably was quite tied to the base capabilities of IBM's OS. But in > that environment, REXX is essentially the equivalent of a shell script, > not a program running independent of a shell. > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From aahz at pythoncraft.com Tue Dec 23 14:16:42 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Dec 2003 14:16:42 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <3FE8652D.2E8F21A8@engcorp.com> <3FE889D3.368E3AF5@engcorp.com> Message-ID: In article <3FE889D3.368E3AF5 at engcorp.com>, Peter Hansen wrote: >Aahz wrote: >> In article <3FE8652D.2E8F21A8 at engcorp.com>, >> Peter Hansen wrote: >>> >>>P.S. My heartfelt thanks to whomever it was who posted the Lewis Carroll >>>reference lately... I'm _still_ trying to find my old copy of Through the >>>Looking Glass to find that section! >> >> Forgotten the Power Of Google? >> >> http://www.literature.org/authors/carroll-lewis/through-the-looking-glass/chapter-08.html > >Thanks, but I shouldn't have implied as I did that I was interested >only in that one section. As I don't recall the passage at all, I'm >now quite eager to read the entire book again. I think it's been >twenty years since I read it last. You could read the whole book on-line, of course, but if you want to read the whole book, I agree that paper is better. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From eppstein at ics.uci.edu Fri Dec 19 15:05:18 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 19 Dec 2003 12:05:18 -0800 Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: In article <92c59a2c.0312191113.569724ca at posting.google.com>, jcb at iteris.com (MetalOne) wrote: > def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) The actual answer to your question is that when you recursively call a generator, its return value (the iterator of its results) needs to be used not ignored. But the reason I'm posting is to suggest an alternative approach: bitIndices = dict([(1L< References: Message-ID: <16336.59925.934194.67341@montanaro.dyndns.org> >> list = [ x for x in tuple ] Roy> What's wrong with the even simplier: Roy> aList = list (aTuple) It doesn't use the language feature du jour. ;-) Skip From adsl5lcq at tpg.com.au Tue Dec 23 03:23:09 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Tue, 23 Dec 2003 19:23:09 +1100 Subject: How to use a 5 or 6 bit integer in Python? In-Reply-To: <20031220131211.GB99675@hishome.net> Message-ID: > ... > It's about 35 times faster than ''.join([chr(x) for x in the_array]) Thanks, I'm implementing that now. Glen From oren-py-l at hishome.net Sat Dec 20 08:12:11 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 20 Dec 2003 08:12:11 -0500 Subject: How to use a 5 or 6 bit integer in Python? In-Reply-To: References: Message-ID: <20031220131211.GB99675@hishome.net> On Fri, Dec 19, 2003 at 06:27:59AM +0000, Rainer Deyke wrote: > Encoding the key tuples as strings is easy (''.join([chr(x) for x in > the_tuple]). Encoding the ints in the data tuples is just as easy. I'm not > sure if those are enough to solve your problem. Using strings is a really, really good idea. Strings are compact and Python dictionaries are highly optimized for use with string keys with tricks like caching of the string hash and faster code paths for special cases like dicts that have only string keys. There is a much faster way for converting tuples of integers to strings. Instead of using the Python tuple type use arrays of bytes and then apply the array object's .tostring() method: >>> from array import array >>> the_array = array('b', range(40)) >>> the_string = the_array.tostring() It's about 35 times faster than ''.join([chr(x) for x in the_array]) >>> back_to_array = array('b', the_string) Oren From deets.nospaaam at web.de Mon Dec 1 07:32:27 2003 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Mon, 01 Dec 2003 13:32:27 +0100 Subject: how to show a bitmap? References: Message-ID: Yun Mao wrote: > Could you please be a little more specific? ;) Its well documented on www.pygame.org. You have to look into the module surfarray, which makes it possible to access and manipulate pixel data using - guess what - Numeric arrays. Look in the code examples for some effects that utilize this - AFAIK there is something like a fire or motion blurring. These access pixel data. Just plug in your array, and you should be done. Regards, Diez From ramen at lackingtalent.com Fri Dec 19 11:39:55 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 19 Dec 2003 16:39:55 -0000 Subject: Save the pythons. References: Message-ID: In article , f29 wrote: > I don't believe that noone has yet spotted that python is becoming > java. Each new version is fully equipped with more garbage than > before. Classes are great, but once there are 1000 of them, inheriting > from each other, I cannot avoid comparing this unpleasant situation to > java. Python's not becoming Java. It's too busy becoming LISP. If it appears that Python is becoming Java, it's only because Java is becoming LISP, too. There are 1000s of classes of languages, each inheriting from LISP. It's just a matter of how many methods they override, and this number is asymptotically approaching zero. > Python power is in it's syntax, not addons. Let's not copy perl's > experience and one java is already far too much for earth. Great. Let's feature-freeze Python now. That way, when Java has finally become LISP, Python will still be Python. Of course, we'll all be using LISP by then, but it'll be a fine piece of nostalgia to keep on an old hard drive in the garage. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From usenet_spam at janc.invalid Wed Dec 3 23:44:46 2003 From: usenet_spam at janc.invalid (JanC) Date: Thu, 04 Dec 2003 04:44:46 GMT Subject: String length ... len(str) References: <8adtsvoen2vb4akhk3nsib151kfjel9mja@4ax.com> Message-ID: Jeff Wagner schreef: > Cool ... who ever came up with the word tuple? That's a weird name. I'm not sure but it may come from words like "quintuple"... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From arjen.dijkstraNoSpam at hccnet.nl Thu Dec 18 05:20:16 2003 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Thu, 18 Dec 2003 11:20:16 +0100 Subject: Coffee script :) References: <3fe17a79$0$246$4d4ebb8e@news.nl.uu.net> Message-ID: <3fe17f6e$0$44017$e4fe514c@dreader9.news.xs4all.nl> I've made something like that too, with a Gui in Tkinter. It's very handy at work so you know ;-) Arjen "Guyon Mor?e" schreef in bericht news:3fe17a79$0$246$4d4ebb8e at news.nl.uu.net... > I just wrote this to decide who's going to get the next round of coffee here > in the office. > Who knows it might be usefull to other people who also have endless > discussions on who is gonna get the coffee :) > > cheers, > > Guyon > > coffee.py > ------------------------------------------------------------------------- > > # who's gonna get coffee? (tm) > # > # Guyon Moree 2003 > > import random > > candidates = [ 'employee1','employee2','employee3','employee4' ] > > print "%s is the chosen one!" % (random.choice(candidates)) > > From joconnor at cybermesa.com Mon Dec 1 13:35:36 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Mon, 01 Dec 2003 11:35:36 -0700 Subject: Python for web ? In-Reply-To: References: Message-ID: Robert Brewer wrote: >Jay O'Connor wrote: > > >>Same here. I do the backend programming and usually give the >>designer a >>page (See these marks? Don't touch them, the rest of the page is >>yours) Works well because I'm *not* a graphices designer and >>I get much >>better results when I make it work and I give it to a friend >>to make it look good. >> >> > >Heh. I'm trying to move into the opposite situation: I do the design and >give a backend programmer a page (See these marks? Touch them and them >only; the rest of the page is mine). Works well because the design is >not then driven by someone who's not a designer. :) > > Good point. I've actually done it both directions...graphics designer gives me a page with static data as ane example and says "fill in these values based on the current [user|context|etc} >Robert Brewer >MIS >Amor Ministries >fumanchu at amor.org > Your name is famailiar, does "IWETHEY" ring a bell? From bwglitch at hotpop.com Mon Dec 22 21:45:54 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Mon, 22 Dec 2003 21:45:54 -0500 Subject: return statement in functions In-Reply-To: <93f5c5e9.0312221718.23e42dac@posting.google.com> References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: hokiegal99 wrote: > I was told earlier (w/o explanation) that functions should return > something. I was under the impression that it was OK with Python to > leave the return statement off. Could someone enlighten me on why or > why not to use a return statement when defining functions? Below is > the bit of code I was told should return something: > > def fs_object_count(path): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > file_count += len(files) > dir_count += len(dirs) > print "Number of Files Examined: ", file_count > print "Number of Folders Examined: ", dir_count > print "Total Number of FS Objects:", file_count + dir_count All Python functions return None by default. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "I can suffer your treachery, Lieutenant ... but NOT your incompetence! ... Treachery requires NO mistakes." -- Megatron to Tarantulas, "Master Blaster" From Padraig at Linux.ie Fri Dec 12 04:55:51 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Fri, 12 Dec 2003 09:55:51 +0000 Subject: Linux GUI for python? In-Reply-To: References: Message-ID: <%hgCb.450$HR.1581@news.indigo.ie> Jules Dubois wrote: > On Thu, 11 Dec 2003 23:20:01 GMT, in article > , Lord Jester wrote: > > >>Looking for any suggestions for a GUI for python >>under linux. > > > I used Tkinter for about 10 weeks. I didn't like it at first but the more > I used it the more I liked it. There's some good (but incomplete) > documentation at > > http://www.nmt.edu/tcc/help/lang/python/docs.html > > Alan Gauld has written a useful tutorial but I've lost the URL. > > PyGTK looks very good to me. There is a very nice tutorial at > http://www.moeraki.com/pygtktutorial/ and reference at > http://www.moeraki.com/pygtkreference/ There's a mailing list for PyGTK; I > get it through NNTP courtesy of the nice people at http://www.gmane.org/ Don't forget about glade which can speed things up immensely. E.Gs are always nice: http://www.pixelbeat.org/talks/pygtk cheers, P?draig. From whisper at oz.net Sat Dec 27 23:44:00 2003 From: whisper at oz.net (David LeBlanc) Date: Sat, 27 Dec 2003 20:44:00 -0800 Subject: Project dream In-Reply-To: Message-ID: > > John J Lee wrote: > > ... I looked at the web site (www.thebrain.com), and decided that > > life is too short to decode marketing hype <0.5 wink> > > I'm with you there. :-) But if you have Java enabled in your > browser, you're > actually getting a test run of their software right there at the > top of the > page. That's "The Brain" running up there. Go to Demos and then > WebBrain for > a more comprehensive demo. > > BTW, that twirling thingamajig in the middle is an important > feature--it has > to do with releasing your intuition or something like that. It's > interesting, but all the swoopy zoomy stuff is not really to my taste. I > guess I like my information plain and simple. > > -Mike > "The Brain" is an example of so-called mind mapper[tm] or mind map[tm] software. Some developers seem to conflate the idea with outliners, but they are virtually the opposite of those in my mind. They're great at mapping non-linear/3-d ideas. General idea is a graph of graphs. Each node on a "parent" graph can drill down to a sub-graph with the node clicked on in the parent graph as the central node. Use of colors and iconography is supposed to make it more useful, but... "The Brain", as a company is also an example of smug arrogant twits who charge far more than their product is worth IMO. They have a patent on some aspect of it, probably to do with how the graph rotates to put the selected node in the center of the diagram. I recall reading on http://www.memes.net/ that there is some dispute about the patent. (Paper) mind mapping itself dates from the 50's. Incidentally, memes.net is a great site and it's software, Lucid Fried Eggs (PHP), is pretty interesting in it's own right. Interesting project I just discovered Fenfire: http://savannah.nongnu.org/projects/fenfire. Oiks! it's in Python! (I'm writing this as I look into the software, so shoot me! ;) ). It's RDF based. It's CVS is behind SSH which I'm not running on Windows - if anyone can snarf it and send it to me, I'd be obliged. More later - Windows seems to be losing consiousness. Dave LeBlanc Seattle, WA USA From dave at pythonapocrypha.com Mon Dec 29 15:25:56 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 29 Dec 2003 13:25:56 -0700 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> <3fef7965.439576157@news.blueyonder.co.uk> Message-ID: <03d501c3ce49$f6ec4680$6401fea9@YODA> Alan wrote: > On Sun, 28 Dec 2003 14:28:42 +0100, Pjer Holton > wrote: > > If you want to get the Windows "kite-mark" then probably Python > is not the best solution Why? Just curious, but what specifically are you thinking of? The OP's question was pretty vague, so it's hard to tell what the question was really about. > quickly and cheaply... Pick the tool for the job. Most commercial > apps on Windows are still written in C++ for performance reasons Hmmm... most Windows programs are purely event driven and therefore spend oodles and oodles of time idle waiting for user input. If in fact most are still written in C++ I'd say it has more to do with habit and/or tools like Visual Studio rather than because of performance reasons. > and because you get access to all the windows stiuff when you > need it. That's what ctypes is for. :) -Dave From missive at frontiernet.net Sun Dec 28 14:54:07 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 28 Dec 2003 19:54:07 GMT Subject: Simple way to get the full path of a running script? References: Message-ID: > #!/usr/bin/env python > > import sys > import os > > me = sys.argv[0] > print "This is how you invoked me: %s" % (me,) > print "This is the absolute path: %s" % (os.path.abspath(me),) > > Usage: > > mark at dev /var/tmp/buffer > $ python ../junk.py > This is how you invoked me: ../junk.py > This is the absolute path: /var/tmp/junk.py > Is this going to work well cross platform? How about from IDLE? I was using sys.path[0] which I thought was working well, but apparently fails when the script is run from IDLE on windows. From djstuart at tconl.com Thu Dec 11 01:13:06 2003 From: djstuart at tconl.com (Doug) Date: Thu, 11 Dec 2003 00:13:06 -0600 Subject: python w/expat compiled on one box doesn't work on another Message-ID: I am running solaris 7 on two machines. I compiled python 2.2.1 with expat parser on one machine. The python binary is located in /usr/local/bin and the libraries are located in /usr/local/lib. I was told that if I would tar up the /usr/local/lib/python2.2 directory from the one machine. I could transfer that and the binaries from /usr/local/bin to another machine running solaris 7 and all should be fine. Machine 1 acts as a hub for receiving and redirecting soap messages between machines on a WAN. I know that it's parser is working. Machine 2 is supposed to take an input message, parse it and send a soap message to Machine 1. However, I get an error that says that it can't find the expat parser. The environments on the two machines are nearly identical (any differences deal with unrelated items). Can someone point me in the right direction as to why it doesn't find the expat parser on the other machine. I can see the expat files in the /usr/local/lib/python2.2/xml/parsers directory. TIA for any assistance. Doug From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 07:30:01 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 13:30:01 +0100 Subject: Programming language from python References: <8fk2vvg18hgvocrmm09b86epekpdnuc02t@4ax.com> Message-ID: Rene Pijlman: >Alejandro Lombardo: >>If it isn?t could you please tell me the name of the best computer >>programming language development tool > >Eiffel. Waitaminute... you're not asking for a programming language, but for a programming language development tool? Do you mean things like lex and yacc? -- Ren? Pijlman From cl at 127.0.0.1 Fri Dec 5 18:45:32 2003 From: cl at 127.0.0.1 (Chris Lee) Date: Fri, 05 Dec 2003 23:45:32 +0000 Subject: Newbie question: Any way to improve this code? In-Reply-To: References: Message-ID: Gustavo Campanelli wrote: > I'm begining to work in a program that cicles through a list of phrases > (basically, a changing signature file). I started yesterday, and I only > have abput 8 full hours of real Python experience. > > So far I produced a code that succesfully reads an process the file, > separating the phrases. Is there any way to optimize this code, so that > I don't have to use the if for the first list member? > > Now for the data. > The file is firmas.txt, it contains the following three example phrases > > Frase 1 > Frase 2 > Frase 3 > > Note that this phrases are separated by newline characters. Upon reading > the full file (it won't be long) I get this: > > 'Frase 1\nFrase 2\nFrase 3\n' > > so, as you can see, the newlines are there. > > My code is this (I know I should close the file, but so far the runtime > is so small it doesn't really matter, that'll change) > > import string > f = open("firmas.txt",'r') # open the file > texto = f.read () > n = range (len (texto)) > frases = [0] > frase ="" > cant = 0 > for a in n: > if texto [a] != "\n": > frase = frase + (texto [a]) > else: > if cant == 0: > frases [0] = frase > else: > frases.append (1) > frases [cant] = frase > cant +=1 > frase = "" > > Well, that's it, thanks. > > Gustavo Campanelli > Ok, so I'm probably talking too soon (...30 minutes of python learning) but python has a readline() function for the file object. f = open("firmas.txt",'r') # open the file texto=f.readline() #texto contains the first line There is also a readlines() method (note the plural) which reads all of the lines in a file f = open("firmas.txt",'r') # open the file texto=f.readlines() #texto contains an list of all the lines There is also (I'm learning quickly) the iterator method f = open("firmas.txt",'r') # open the file for line in f: print line #or whatever ...And I spent most of this week thinking the STL was cool. From dave at pythonapocrypha.com Tue Dec 16 16:11:18 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 16 Dec 2003 14:11:18 -0700 Subject: ignore References: Message-ID: <030c01c3c419$266a40f0$891e140a@YODA> Robin wrote: > Elaine Jackson wrote: > > testing > > There are groups like misc.test for this kind of post; please use them > instead of comp.lang.python. > > Thank you. Just curious: what's the community-friendly way of testing if you don't use comp.lang.python (the Usenet group) but instead use python-list (the Mailman-managed list)? From gh at ghaering.de Fri Dec 5 10:01:37 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Dec 2003 16:01:37 +0100 Subject: How to tell the difference between string and list In-Reply-To: <16336.40180.980551.605191@montanaro.dyndns.org> References: <1070635589.841.8.camel@marigold> <16336.40180.980551.605191@montanaro.dyndns.org> Message-ID: <3FD09DD1.1010705@ghaering.de> Skip Montanaro wrote: > Jan> I need to recognize 'var' and ['var'], usually I would use: > > ... > > Try > > if isinstance(a, str): > pass > elif isinstance(a, list): > pass This requires Python 2.2 or later, but ZOPE still uses Python 2.1 AFAIK, so you can try one of the Python 2.1 compatible solutions that I proposed. -- Gerhard From sebb at linuxcult.com Wed Dec 31 12:49:55 2003 From: sebb at linuxcult.com (sebb) Date: 31 Dec 2003 09:49:55 -0800 Subject: Maybe a stupid idea Message-ID: <56f42e53.0312310949.39826ffd@posting.google.com> I'm kind of newbie to programming, but I thought of something and I want some opinions on that. It's about a new instruction block to do some cycles. I thought about that because it's not very easy to program a cycle. Here is a simple example : b=0 while b < 50: b+=1 print "*" * b while b > 0: b-= 1 print "*" * b It takes two while blocks to do a cycle. I know that cycles is not a structure of any programming language, but I want some opinions the know if my idea is stupid or not. If the idea is not so stupid, python may be the first language to have a completely new structure block :-) Note : English is not my mother tongue so the message can have mistakes. From miki.tebeka at zoran.com Sun Dec 28 08:21:06 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 28 Dec 2003 05:21:06 -0800 Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> <3fee1d7d.350511859@news.blueyonder.co.uk> <3fee224a.65125244@news.iprimus.ca> Message-ID: <4f0a9fdb.0312280521.171a2806@posting.google.com> Hello Midas, > Part 1) Create 10 new assorted objects > Part 2) Link up the objects, somehow, so they can communicate with each other directly, like parts of an electrical circuit. > Part 3) Call the first object, which calls another, etc. like an electrical circuit. > > To change the circuit, I would only change part 2 and perhaps part 3. > > For example, ObjectX could have an input, for a string, and two outputs. > If the input is "TurnOnS", it calls ObjectY.Input3 > If the input is "TurnOnT", it calls ObjectZ.Input7 > > ObjectX would call either, ObjectY.Input3 or ObjectZ.Input7, because it was connected that way in part 2. > > I could then later change part 2 so ObjectX called either ObjectE.Input2 or ObjectF.Input9 > In other words, I could "re-wire" the circuit without changing anything in the objects. >>> class Wired: def __init__(self): self.sisters = {} def register(self, msg, func, *args): self.sisters[msg] = (func, args) def process(self, msg): func, args = self.sisters[msg] func(*args) >>> w1 = Wired() >>> w2 = Wired() >>> def p(msg): print msg >>> w2.woof = lambda m: p("Woof: %s" % m) >>> >>> w2.woof("X") Woof: X >>> w1.register("woof", w2.woof, "HELLO") >>> >>> w1.process("woof") Woof: HELLO >>> HTH. Miki From http Tue Dec 30 19:05:05 2003 From: http (Paul Rubin) Date: 30 Dec 2003 16:05:05 -0800 Subject: selecting a random item from a set References: <7xsmj1dgox.fsf@ruckus.brouhaha.com> Message-ID: <7x7k0ddf7y.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > > for n, randomElement in enumerate(s): > > if random() < (1.0 / (n+1)): > > e = randomElement > > 0 <= random() < 1 > 1.0/(n+1) == 1 for n == 0, so this will always choose the first element. It will always select the first element, but then on some (random) subsequent passes through the loop, it will replace the selection. For example, suppose there are two elements. On the first pass, e gets set to the first element. On the second pass, e gets set to the second element if random() < 0.5, i.e. 50% of the time. So after the loop is done, e is either the first or the second element, with equal probability. With k>2 elements, it works the same way. From martin at v.loewis.de Sat Dec 6 12:20:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Dec 2003 18:20:57 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > >> Why, when unicode includes all? > > > >Because at the end, you would produce a byte string. Then the question > >is what type the byte string should have. > Unicode, of course, unless that coercion was not necessary, as in ascii+ascii > or latin-1 + latin-1, etc., where the result could retain the more specific > encoding attribute. I meant to write "what *encoding* the byte string should have". Unicode is not an encoding. > Why not assume latin-1, if it's just a convenience assumption for certain > contexts? I suspect it would be right more often than not, given that for > other cases explicit unicode or decode/encode calls would probably be used. This was by BDFL pronouncement, and I agree with that decision. I personally would have favoured UTF-8 as system encoding in Python, as it would support all languages, and would allow for as little mistakes as ASCII (e.g. you can't mistake a Latin-1 or KOI-8R string as UTF-8). I would consider chosing Latin-1 as euro-centric, and it would silently do the wrong thing if the actual encoding was something else. Errors should never pass silently. Unless explicitly silenced. > >name = u'Martin L?wis' > >print name > Right, but that is a workaround w.r.t the possibility I am trying to > discuss. The problem is that the possibility is not a possibility. What you propose just cannot be implemented in a meaningful way. If you don't believe me, please try implementing it yourself, and I'll show you the problems of your implementation. Using Unicode objects to represent characters is not a work-around, it is the solution. > Care to elaborate? I don't know what difficult questions nor > non-intuitive behavior you have in mind, but I am probably not the > only one who is curious ;-) As I said: What would be the meaning of concatenating strings, if both strings have different encodings? I see three possible answers to this question, all non-intuitive: 1. Choose one of the encodings, and convert the other string to that encoding. This has these problems: a) neither encoding might be capable of representing all characters of the result string. There are several ways to deal with this case; finding them is left as an exercise to the reader. b) it would be incompatible with prior versions, as it would not be a plain byte concatenation. 2. Convert the result string to UTF-8. This is incompatible with earlier Python versions. 3. Consider the result as having "no encoding". This would render the entire feature useless, as string data would degrade to "no encoding" very quickly. This, in turn, would leave to "strange" errors, as sometimes, printing a string works fine, but seemingly randomly, it fails. Also, what would be the encoding of strings returned from file.read(), socket.read(), etc.? Also, what would be the encoding of strings created as a result of splice operations? What if the splice hits the middle of a multi-byte encoding? > No, I know that ;-) But I don't know how you are going to migrate towards > a more pervasive use of unicode in all the '...' contexts. Whether at > some point unicode will be built into cpython as the C representation > of all internal strings Unicode is not a representation of byte strings, so this cannot happen. > or it will use unicode through unicode objects > and their interfaces, which I imagine would be the way it started. Yes, all library functions that expect strings should support Unicode objects. Ideally, all library functions that return strings should return Unicode objects, but this raises backwards compatibility issues. For the APIs where this matters much, transition mechanisms are in progress. > Memory-limited implementations might want to make different choices IWG, > so the cleaner the python-unicode relationship the freer those choices > are likely to be IWT. I'm not too concerned with memory-limited implementations. It would be feasible to re-implement the Unicode type to use UTF-8 as its internal representation, but that would be tedious to do on the C level, and it would lead to really bad performance, given that slicing and indexing become inefficient. > >> import m1,m2 > >> print 'm1: %r, m2: %r' % (m1.s1, m2.s2) > >> > >> might have ill-defined meaning > > > >That is just one of the problems you run into when associating > ^--not ;-) > >encodings with strings. Fortunately, there is no encoding associated > >with a byte string. > So assume ascii, after having stripped away better knowledge? No, in current Python, there is no doubt about the semantics: We assume *nothing* about the encoding. Instead, if s1 and s2 are , we treat them as byte strings. This means that bytes 0..31 and 128..256 are escaped, with special escapes applying to 10, 13, ..., and bytes 34 and 39. > It's fine to have a byte type with no encoding associated. But > unfortunately ISTM str instances seem to be playing a dual role as > ascii-encoded strings and byte strings. More below. No. They actually play a dual role as byte strings and somehow-encoded strings, depending on the application. In many applications, that encoding is the locale's encoding, but in internet applications, you often have to handle multiple encodings in a single run of the program. > How will the following look when s == '...' becomes effectively s = > u'...' per above? I don't know. Because this question is difficult to answer, that change cannot be made in the near future. It might be reasonable to have str() return Unicode objects - with another builtin to generate byte strings. > BTW, is '...' =(effectively)= u'...' slated for a particular future > python version? No. Try running your favourite application with -U, and see what happens. For Python 2.3, I managed python -U to atleast enter interactive mode - in 2.2, importing site.py will fail, trying to put Unicode objects on sys.path. Regards, Martin From ababo_2002 at hotmail.com Tue Dec 30 10:43:34 2003 From: ababo_2002 at hotmail.com (Daniel Pryde) Date: Tue, 30 Dec 2003 15:43:34 +0000 Subject: Array neighbourhoods Message-ID: Hi again. One thing I forgot to include in my post the other day. I was wondering if anyone knew of any fast algorithms for returning the surrounding neighbours of an array element, or even the neighbours of a group of array elements. I'm using a function which affects neighbourhoods of a value with a diminishing effect (i.e. a gaussian distribution), so I need to be able to get the neighbourhood (of size 1) of the first array entry, as well as the neighbourhood of the returned neighbourhoods! Hope that all makes sense. Daniel _________________________________________________________________ Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo From ajsiegel at optonline.com Mon Dec 8 07:30:18 2003 From: ajsiegel at optonline.com (Arthur) Date: Mon, 08 Dec 2003 12:30:18 GMT Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: <92r8tv0jrg27ijqschovr2orgit1c9c0gu@4ax.com> On Sun, 07 Dec 2003 22:42:17 -0500, Roy Smith wrote: >In MVP (Microsoft Visual Python), the "auto-correct" function would just >silently change the ()'s to []'s as you typed them. If you tried to >change them back, clippy would pop up on the screen and say, "You seem >to be trying to do something un-pythonic. Would you like some >assistance?". If you tried to make clippy go away, it would offer to >"install this critical security patch immediately". Give some credit. The unitype system will have been inplemented by then. One's decoded DNA sequence will be accessed (some people thought web services would be a bust, back in aught 3), with reference to which, one's intentions are determined. Programming now called "hinting". CH4E. Art From hamish_lawson at yahoo.co.uk Tue Dec 2 06:25:05 2003 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 2 Dec 2003 03:25:05 -0800 Subject: Separation of content and code for web (was Re: Python for web ?) References: <3FCB8535.F8F89132@engcorp.com> Message-ID: <915a998f.0312020325.7edb7fa@posting.google.com> Peter Hansen wrote: > By far the most rigorous separation that I've seen to date, and one > we're experimenting with more right now, is to have a pure-HTML (or XHTML) > web page with *no* code or funky little embedded crap of any kind at > all, and rely exclusively on "id" attributes on the dynamic parts. > ... > Anyone know of a Python-based approach using the same core concept? PyMeld Hamish Lawson From ptmcg at users.sourceforge.net Mon Dec 22 16:43:58 2003 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Mon, 22 Dec 2003 21:43:58 GMT Subject: Getting line-level timings using hotshot Message-ID: I've googled and scanned docs and tried and errored, but have not seemed to find the right combination of steps to get line-level timing and profiling using hotshot. >From the docs, I *think* I'm supposed to: 1. Create a hotshot.Profile object, giving the name of the output stats file, and setting the lineevents and linetimings arguments to 1. 2. Run the code to be timed using the Profile object's run() method. 3. Close the output file by calling the Profile object's close() method. This should create an output stats file containing the lineevents, with timing information. Now, I need to create a hotshot.stats StatsLoader object, using hotshot.stats.load(filename). At this point, things get fuzzier for me. The examples I find on the web typically follow load() with a call to strip_dirs(), but without much explanation why. Then the crucial question - what are the args to pass to sort_stats()? I can enumerate the options, but I'm afraid none of them are self-evident. Here is the table of options from the ActivePython online docs: 'calls' = call count 'cumulative' = cumulative time 'file' = file name 'module' = file name 'pcalls' = primitive call count 'line' = line number 'name' = function name 'nfl' = name/file/line 'stdname' = standard name 'time' = internal time (This question is complicated by the ability to specify multiple options in the sort_stats() call. But no matter what combination I try, I still only get function level time reporting.) Lastly, print_stats(n) gets called, to list out the 'n' highest entries in the sorted list. Can anyone help me out? I know which functions are most time consuming now, but what lines in those functions? What are the missing steps to get line level timing for performance tuning? Thanks, -- Paul From remco at localhost Mon Dec 15 06:48:44 2003 From: remco at localhost (remco) Date: Mon, 15 Dec 2003 12:48:44 +0100 Subject: cPickle from 2.2 to 2.1 References: Message-ID: <3fdd9fa4$0$210$e4fe514c@news.xs4all.nl> paul wrote: > >Thanks for pointing that out (seems rather obvious now ;). I thought >pickle is a fast and convenient method to store/restore data. Now I see >the drawbacks. These drawbacks (backward/forward incompatibilities) occur nearly everywhere. I've used the Berkley db module, when it got updated, i had to deinstall Python, reinstall an old version, check out all my data to another format, deinstall the older python, and reinstall the latest version. Next i had to create a new Berkley database and put the data back in. And i thought Berkley would never change again :)) >BTW: It was a hack to avoid the xml.dom.minidom/unicode/non ASCII >charset/codec/writer mess. Seems like I have to look at that once more. Therefore i use libxml2 instead of minidom, have once written a nice function that will quote all the unicode stuff you're problems will be over. On the other hand, you can't edit pickled data with text editor. With xml you can, so it's an advantage. If this doesn't matter: why not UUencode any unicode string when writing it to the xml? It worked for me.. And last but not least; there's allways the old .ini format 8) Cheers Remco Boerma From martin at v.loewis.de Thu Dec 4 02:23:54 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Dec 2003 08:23:54 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> Message-ID: Peter Hansen writes: > Wait a sec... are you telling me that my code, which has strings containing > binary data (which I believe has *always* been permitted) >From a language specification point of view, it was never permitted. You should use escape codes for binary data in source code. Regards, Martin From andreif at mail.dntis.ro Fri Dec 26 09:46:51 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 26 Dec 2003 06:46:51 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> <7xr7yvjle5.fsf@ruckus.brouhaha.com> <21bb8d55.0312240144.4eb9caab@posting.google.com> <7xk74mik64.fsf@ruckus.brouhaha.com> Message-ID: <21bb8d55.0312260646.19f7e79f@posting.google.com> Fred Pacquier wrote in message news:... > Paul Rubin said : > > >> Even if it was limited i/o traffic I am not sure how to do profiling > > > > A crude but maybe useful thing you can do is just observe the CPU load > > while the program is running. If the CPU load is low but you hear the > > disk banging around, you're i/o bound. > > I love this one. It would make a great intro quote for the next DrDobbs > weekly summary ! ;-) I ment I didn't know how to do profiling in this case, to find out if the program was cpu or disk bound, although if I would have sit down and thought for 5 seconds it was obvious. Profiling in general is another fish and I consider myself able to spot the places where my programs consumes cpu cycles. Cheers, Andrei From andreif at mail.dntis.ro Wed Dec 24 05:07:10 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 24 Dec 2003 02:07:10 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> Message-ID: <21bb8d55.0312240207.5fb1914c@posting.google.com> Skip Montanaro wrote in message news:... > andrei> So my problem now is what should I use to store my data and > andrei> still be able to retrieve all messages for a given word very > andrei> quickly. > > There's the rub. PySQLlite consumes a lot of disk space presumably to > support efficient access to the data (hashing keys, etc). If you want > compact storage you aren't likely to do much better than > > wordid1:msgid1 > wordid2:msgid2 > ... > > Unfortunately, searching that will probably be a bit slow. Well - I want to use this storage to speed up my searches so searching will really need to be fast. I didn't want the most compact storage, but at 88 bytes to store a couple of integers is just way too much. Another reason I wanted to use a database like sqlite is that it presents some safety guarantees. If something goes wrong when updating (like no diskspace left on end-user's disk) then the data is still says safe, i.e. the latest transaction is not commited and that's it. I wrote a similar version of what I wanted a couple of years ago not using a database, just C/C++ code, something like this (I think a similar method was suggested in this thread) : I was processing messages in batches, so for each 10000 messages or so I would make in memory a list of words and in what messages occur, and for each word I would write all messages that contain it as consecutive entries in a file. Then I would update the global word index (kept in another file), which for each work kept a linked list of zones in the other file where msgIds containg this word were. Worked pretty well, but this was for a server I controlled, i.e. at all times I was sure I had enough space and I was controling it. For an application to be deployed to end-users I need more safety. That is why I am playing with sql. > If the word ids and msg ids have fixed maximum sizes you might try zero- or > space- padding them so your records are of fixed length. You can then store > the file sorted by wordid and do a binary search in the file looking records > of interest. Still would be too slow for a search, and search is the main reason for this structure. > Another possibility, assuming your database keys are integers, is to try the > bsddb recno format database. I've never used it before (not as much call > for a database file with integer keys), but it seems to be *relatively* > space-efficient. I believe it doesn't actually need to store the keys, > since they are implicit. > > I built a recno db file containing the pickle of the squares of the numbers > in range(1, 100000): > > >>> for n in range(1,100000): > ... db1[n] = pickle.dumps(n*n) > ... > > The total string length of the pickled squares was 1.3MB. The file size was > 2.1MB. Interesting. Fortunately I found lupy which suits me, but if I were not I might have been tempted to experiment with that. Andrei From skip at pobox.com Mon Dec 22 17:06:44 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Dec 2003 16:06:44 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <20031222213900.GC24252@unpythonic.net> References: <21bb8d55.0312221204.51d86182@posting.google.com> <16359.24377.5101.789601@montanaro.dyndns.org> <20031222213900.GC24252@unpythonic.net> Message-ID: <16359.27380.260552.535448@montanaro.dyndns.org> >>>>> "Jeff" == Jeff Epler writes: Jeff> On Mon, Dec 22, 2003 at 03:16:41PM -0600, Skip Montanaro wrote: >> How about: >> >> def howmanyatstart(s, pfx): >> return (len(s) - len(s.lstrip(pfx)))/len(pfx) >> >> ? This works for prefixes which are longer than a single character: >> >> >>> howmanyatstart(">>>>message1", '>') >> 4 >> >>> howmanyatstart("bobbobbob>>>>message1", 'bob') >> 3 Jeff> strip() doesn't work that way: >>>> "bbbbbbbxxx".strip("bob") Jeff> 'xxx' Then it looks like a bug in one or the other to me. Skip From a.schmolck at gmx.net Tue Dec 30 22:04:28 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 31 Dec 2003 03:04:28 +0000 Subject: selecting a random item from a set References: Message-ID: "Tim Peters" writes: > [Alexander Schmolck] > > Quite a few algortihms prominently feature choosing/removing a single > > random element from a set at a time. > > Really? Feature selection schemes, for example? > > On first sight I can't think of anything better to achieve this with > > `sets.Set` than something along the lines of: > > > > for dummy, randomElement in zip(range(randrange(len(s)+1)), s): pass > > It's too obscure for my tastes, And buggy (a misplaced paren). > but something like that would certainly work. Probably not. I'm not > convinced there's a real need, and given the implementation of sets there's > no way to do it essentially more efficient than the way you've already > figured out > (it can be done using O(1) space instead, s/zip/izip/ s/range/xrange/ ? > but it still takes O(len(s)) time -- the implementation of sets is > lumpy, so the O(1)-time indexing trick used by random.choice() can't apply). The complexity might be the same, but you could certainly do it with a lot less overhead (with C implmented sets, at least). But if really not that many people need it, that's of course not enough of a justification. > If you think this is important enough to be worth the bother , you > could define a hybrid data structure combining a set and a list, keeping > them in synch. random.choice() can then be applied to the list part to get > a random element in constant time. The only tricky part is deletion of an > element. You need another dict under the covers to map each key to its > index in the list. When it comes time to delete a key, you *overwrite* the > list position it occupied with the last key in the list (and update that > key's index), then reduce the length of the list by 1. That keeps deletion > constant-time (expected-case) too. Yep, such a scheme might be interesting. I currently haven't profiled any of the (unfinished) code yet or thought hard about it, so I don't know the relative importance of large constant factors vs. complexity. I'm not entirely bitten by the premature optimization bug however -- I know that most of the time in an existing implementation of what I want to do in another language is spent doing these set operations and takes minutes to hours to come up with its outputs. 'as From engSpideRlem at pdxThiS.edu Sat Dec 6 09:18:00 2003 From: engSpideRlem at pdxThiS.edu (Mark Engle) Date: Sat, 06 Dec 2003 08:18:00 -0600 Subject: Moving around in a string References: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> Message-ID: <5PSdndqm1duFeEyiRVn-sw@sysmatrix.net> Peter Otten wrote: > Mark Engle wrote: > > http://www.python.org/doc/current/lib/module-string.html > > > > One caveat (only for the string module), quoting from the above > document, but easily overlooked: > > "Many of the functions provided by this module are also defined as > methods of string and Unicode objects; see ``String Methods'' > (section 2.2.6) for more information on those." > > So whenever you're tempted to write string.somefunc(s, moreargs), > rather use s.somefunc(moreargs). > > Peter Thank you. Time to do some more reading. Mark From mbabcock at fibrespeed.net Fri Dec 12 12:05:14 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 12 Dec 2003 12:05:14 -0500 Subject: do this with list comp? In-Reply-To: References: Message-ID: <3FD9F54A.2010506@fibrespeed.net> python-list-request at python.org wrote: > > Subject: > do this with list comp? > From: > John Hunter > Date: > Fri, 12 Dec 2003 10:46:58 -0600 > To: > python-list at python.org > > >I want to replace all empty fields in a CSV line with 'NULL'. > >Here is a brute force way > > def fixline(line): > ret = [] > for s in line.split(','): > if not len(s): ret.append('NULL') > else: ret.append(s) > return ret > > line = 'John,Bill,,,Fred' > print fixline(line) > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > >I am wondering if there is a way to do it with list comprehensions. I >know how I would do it with a ternary operator..... > > def replace_blank_with_null(data): if not data: return "NULL" return data new_list = [ replace_blank_with_null(line) for line in old_list ] Or something more like: line_items = [ replace_blank_with_null(item) for item in line.split(",") ] -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From mgerrans at mindspring.com Thu Dec 11 03:24:56 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 11 Dec 2003 08:24:56 GMT Subject: Dealing with hex References: <0JwBb.7784$rP6.6115@newsread2.news.pas.earthlink.net> <6clka1-ksi.ln1@dman13.dyndns.org> Message-ID: Derrick 'dman' Hudson wrote: > > Hoops? For example : > > print "%x" % long( zlib.crc32( buffer ) ) > > > > That seems simple enough to me. Simple indeed. In fact it's so simple it doesn't work: >>> print "%x" % long( zlib.crc32('test') ) -278081f4 Dan Bishop wrote: > Or if you wanted the old semantics: > > def unsigned(n): > return n & 0xFFFFFFFFL > > print "%x" % unsigned(zlib.crc32(buffer)) This avoids the FutureWarning, but the PEP mentions that the L-suffix notation will also be phased out, so I wanted to avoid that in the solution and that can be done like this: def unsigned32(n): return n & 4294967295 since the large decimal of 0xffffffff value will automatically be a long. It seems kind of clunky to have to throw this extra function call into the mix whenever dealing with 32-bit values. I don't think 32-bit values will be made obsolete by 64-bit systems for quite a while to come. This particular update to Python seems a little pie-in-the-sky and un-pragmatic. From rainerd at eldwood.com Mon Dec 1 02:45:27 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Mon, 01 Dec 2003 07:45:27 GMT Subject: Implementing Iterators in, e.g., Linked Lists References: Message-ID: adeleinandjeremy wrote: > AFAIU, in my LinkedList class, I can either have the LinkedList be its > own iterator by making its __iter__() method return self and defining > a next() method, or I can have a separate iterator called from > LinkedList's __iter__(). My view is that it would be best to have the > LinkedList be its own iterator - is that the case? Or is an external > iterator preferable in this case? External iterators are always preferable for two reasons. 1. They allow multiple iterators over the same collection. 2. They keep the interface of the base object clean by separating other functionality. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From rainerd at eldwood.com Fri Dec 5 23:31:36 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 06 Dec 2003 04:31:36 GMT Subject: memory usage References: Message-ID: Dave wrote: > In another window on my Linux system I then run top. The python > process is now using 155 MB of memory. Why is python using such a > large amount of memory, nearly nearly 16 bytes for a float in this > case? 2 lists. 10000000 floats. 10000000 integers. 20000002 reference counts. 20000002 type identifiers. Whatever extra memory the memory manager uses to keep track of 20000002 separately allocated small blocks of memory. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From marklists at mceahern.com Wed Dec 10 07:37:28 2003 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 10 Dec 2003 06:37:28 -0600 Subject: About the use of **args In-Reply-To: References: Message-ID: <1071059821.11531.77.camel@dev.internal> On Wed, 2003-12-10 at 03:24, Graham Ashton wrote: > [snip] > I've not run that so it may have syntax errors. It should illustrate the > principle though; you can use attributes directly until you want to take > actions when you set them. Then you can make the attribute "private" and > replace it with a property that access the real attribute, and does > whatever else you want to do when it's accessed. A couple of points on Graham's example: 1. You have to subclass from object in order to use property. 2. When Graham nominalizes private, he means that you can still access the attribute variable directly--and that's by design. See example below. Cheers, // m #!/usr/bin/env python class Shoe: def __init__(self): self._size = None def getSize(self): print "In getSize..." return self._size def setSize(self, size): print "In setSize..." self._size = size size = property(getSize, setSize) class Shoe2(object): def __init__(self): self._size = None def getSize(self): print "In getSize..." return self._size def setSize(self, size): print "In setSize..." self._size = size size = property(getSize, setSize) s = Shoe() # Since we haven't subclassed from object, the property descriptor # doesn't work; notice that setSize() isn't getting called... s.size = 1 print s.size # We can still access the "private" member variable. In Python, # private is merely a convention. print s._size # Now that we've subclassed from object, our get/set methods are # called. s2 = Shoe2() s2.size = 1 print s2.size # And we can still access the "private" member variable. print s2._size From noemail at noemail4u.com Mon Dec 22 08:34:11 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 22 Dec 2003 13:34:11 GMT Subject: Anybody ever use Pippy? References: <3FE30E59.9010104@lawson.com> Message-ID: On Fri, 19 Dec 2003 08:42:33 -0600, "William S. Perrin" wrote: >I've just downloaded and installed Pippy (http://pippy.sourceforge.net/) >for my Palm. It's called 1.52+. I'm not sure what the plus is. It seems >to run ok. Anyone else have any experience? > >One short side is no floating point capability. > >Thanks, WSP I've used it a few times, for programmable calculator type things (w/o floating point), but could never get my source files to import, so I ended up doing a lot of manual import (copy/paste). As Ganesan points out, it doesn't seem to be supported. I think the "+" is for the few Palm-specific modules. There are a few modules with interesting names (palmform, palmdm, palmevent), but I couldn't find examples or documentation. Another short side is no regex/re module. I don't have stuff to scan on the PDA, but it would be convenient at times to experiment with an expression. --dang From peter at engcorp.com Tue Dec 23 11:09:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Dec 2003 11:09:41 -0500 Subject: pymozilla ([Python-Dev] RELEASED Python 2.3.3 (release candidate 1) - custom Py_Initialize()) References: <87fzfgoqn0.fsf@pobox.com> Message-ID: <3FE868C5.BF75685C@engcorp.com> "John J. Lee" wrote: > > JZ writes: > > > On Fri, 19 Dec 2003 04:30:53 +0100, "Wiktor Sadowski" > > wrote: > > > > >The main problem was to have it run from CD (client requirement) without > > >installing anything (Mozilla/Python) > > > > I had the same problem. I solved it using Webware and SQLite. > > What's the problem? Does Python not like having nowhere to save .pyc > files? Python has no problem with that. We frequently run code from a CompactFlash module with a read-only Linux partition, without .pyc files being written and with no related issues. -Peter From raims at dot.com Wed Dec 17 18:08:43 2003 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 18 Dec 2003 00:08:43 +0100 Subject: Using python with SSH? References: <3fe0dfd7$1@clarion.carno.net.au> Message-ID: <8765gf82kk.fsf@mobile.foo> Steve writes: > ssh -l user host "/path/to/program" > > prompts for a password and I don't know how to supply one via a python > script. Is there an easy way out? Can I log onto to the other machine via > ssh somehow? Does a python script support this? Thanks! Try something like this: import os ssh_pipe = os.popen("ssh -l user path") ssh_pipe.write(password) ssh_pipe.write("\n") ssh_pipe.flush() ssh_pipe.close() hope this helps -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From andreif at mail.dntis.ro Mon Dec 22 15:04:21 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 22 Dec 2003 12:04:21 -0800 Subject: Counting how many chars equal to a given char are in the beginning of a string Message-ID: <21bb8d55.0312221204.51d86182@posting.google.com> Hi, Given a string s and a char c, is there a short & elegant way to determine how many consecutive occurences of c are in the beginning of s ? For example if s = ">>>>message1" and c = ">" then the number I am looking for is 4 (the string begins with 4 '>'). Thanks, Andrei From jepler at unpythonic.net Wed Dec 31 14:18:55 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Dec 2003 13:18:55 -0600 Subject: Maybe a stupid idea In-Reply-To: <87wu8cx1xh.fsf@strauser.com> References: <56f42e53.0312310949.39826ffd@posting.google.com> <87wu8cx1xh.fsf@strauser.com> Message-ID: <20031231191854.GG18443@unpythonic.net> On Wed, Dec 31, 2003 at 06:45:05PM +0000, Kirk Strauser wrote: > >>> def cycle(a,b): > ... return range(a,b)+range(b,a,-1) > ... > >>> cycle(0,10) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] You might also define cycle as an iterator >>> def cycle(a, b): ... return itertools.chain(xrange(a, b), xrange(b, a, -1)) >>> list(cycle(0, 10) Furthermore, you might want to treat the one-argument version similarly to range: >>> def cycle(a, b=None): ... if b is None: a, b = 0, a ... return itertools.chain(xrange(a, b), xrange(b, a, -1)) >>> list(cycle(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] You could also change it to support a step argument: >>> def cycle(a, b=None, c=1): ... if b is None: a, b = 0, a ... return itertools.chain(xrange(a, b, c), xrange(b, a, -c)) >>> list(cycle(5, 10, 2)) [5, 7, 9, 10, 8, 6] ... though that last result looks a bit odd. This must be the problem with hypergeneralization I hear so much about. Jeff From hogus at invalid.tld Thu Dec 11 21:58:57 2003 From: hogus at invalid.tld (Jules Dubois) Date: Thu, 11 Dec 2003 19:58:57 -0700 Subject: Linux GUI for python? References: Message-ID: On Thu, 11 Dec 2003 23:20:01 GMT, in article , Lord Jester wrote: > Looking for any suggestions for a GUI for python > under linux. I used Tkinter for about 10 weeks. I didn't like it at first but the more I used it the more I liked it. There's some good (but incomplete) documentation at http://www.nmt.edu/tcc/help/lang/python/docs.html Alan Gauld has written a useful tutorial but I've lost the URL. PyGTK looks very good to me. There is a very nice tutorial at http://www.moeraki.com/pygtktutorial/ and reference at http://www.moeraki.com/pygtkreference/ There's a mailing list for PyGTK; I get it through NNTP courtesy of the nice people at http://www.gmane.org/ Finally, Alex Martelli says (Message-ID: <7Ypob.72491$e5.2660364 at news1.tin.it>), "Yes, eric + pyqt + qt _IS_ a great RAD [...]". From raims at dot.com Sat Dec 27 15:42:05 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 27 Dec 2003 21:42:05 +0100 Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> Message-ID: <87smj656xu.fsf@mobile.foo> MidasOneTwo at hotmail.nospam.com (Midas) writes: > In my "main" code, I would like to create two > new objects (ObjectA and ObjectB) and have > ObjectA directly call an ObjectB method. In > order to do this I believe ObjectA must hold > a reference to ObjectB. What about the name > of the method? Must it be hardcoded in > ObjectA? You could simply do something like this: class A: def __init__(self): self.ObjectB = B() class B: def someMethod(self): pass if __name__ == "__main__": ObjectA = A() ObjectA.ObjectB.someMethod() HTH -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From guettli at thomas-guettler.de Tue Dec 16 10:41:11 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 16 Dec 2003 16:41:11 +0100 Subject: Python in a spreadsheet References: <3064b51d.0312151318.277c8c06@posting.google.com> Message-ID: Am Mon, 15 Dec 2003 13:18:21 -0800 schrieb beliavsk: > Is it possible to call a Python function from Calc (the Open Office > spreadsheet) or Microsoft Excel? Are their web sites or books > describing how to do this? > > I would prefer not to write any more VBA :). I once posted a way to batch convert files into a different format with pyuno. Maybe this helps you http://groups.google.com/groups?threadm=pan.2003.11.27.16.41.02.989568 at thomas-guettler.de Depending on your problem, I would suggest to use XML instead. I think it is more stable to export the office file to XML, process it with your script, and import it again. The remote procedure call solutions (COM, pyUNO) don't scale well. thomas From dw-google.com at botanicus.net Tue Dec 9 07:42:16 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 9 Dec 2003 04:42:16 -0800 Subject: Understanding and working with __metaclass__ References: <99dce321.0312081149.2a32575d@posting.google.com> Message-ID: <99dce321.0312090442.59fcc7fb@posting.google.com> "Mike C. Fletcher" wrote... > http://members.rogers.com/mcfletch/programming/metaclasses.pdf > Is intended to answer exactly this question. Thanks, this is _very much_ appreciated and exactly what I was after. The "Quickie Definitions" slide probably deserves a print-out and getting stuck on my wall for the next week or two until it properly sinks in. :) Thanks again, David. From dialtone#NOSPAM#.despammed at aruba.it Sat Dec 13 08:59:53 2003 From: dialtone#NOSPAM#.despammed at aruba.it (Valentino Volonghi aka Dialtone) Date: Sat, 13 Dec 2003 14:59:53 +0100 Subject: "Do this, and come back when you're done" References: Message-ID: <878ylges2u.fsf@vercingetorix.caesar.org> Kamus of Kadizhar writes: > Is there any way to rewrite each half of the function to run in the > background, so to speak, and then have a master process that waits on > the results? This would cut execution time in half more or less. Why don't you use twisted? It's a net framework with a lot of protocols (and you can define your own ones) and it's based on async sockets which let you write programs avoiding threads for most of the times. www.twistedmatrix.com I'm sure you will find out that's the best thing ever done for python :) -- Valentino Volonghi, Regia SpA, Milan Linux User #310274, Gentoo Proud User From image9n at hotmail.com Sun Dec 7 11:50:13 2003 From: image9n at hotmail.com (Agency) Date: 7 Dec 2003 08:50:13 -0800 Subject: how to display clock? Message-ID: <1cca69c7.0312070850.79db07ee@posting.google.com> I'm still working on the bpm counter. I need to have at least 2 displays that are not static. One would be a clock/running time and the other would should the current beat count. How would I do this in Tkinter? I was thinkning of canvas-text, but there must be a widget for doing this kind of display. I'm a bit lost and would appreciate some help. From deets_noospaam at web.de Wed Dec 10 18:39:24 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 11 Dec 2003 00:39:24 +0100 Subject: sys.argv with quoted strings as option argument References: Message-ID: > However, sys.argv breaks the arguments whenever it encounter spaces, > like this: > ['./myprogram.py', '--includedir=/usr/include', '/usr/local/include', > '--libdir=/usr/lib', '/usr/local/lib'] > > So I can't seem to use getopt or optik to process such cases. Is there a > good way where I can preserve such option arguments with whitespaces? Under Linux, this works. So most probably this is a problem of your shell (under windows?) Anther solution might be to specify every argument with its own key like this: ./myprogram --include-dir=foo --include-dir=bar Using getopt, you can build up the list on your own. Diez From news at woody.datatailors.com Tue Dec 9 08:49:29 2003 From: news at woody.datatailors.com (Peter van Kampen) Date: Tue, 9 Dec 2003 14:49:29 +0100 Subject: Using XUL with python References: Message-ID: > Gabriele Farina wrote: > Hi guys, > > hiow can I create a XUL application that runs with python?? Which libreries > I need?? Learn to use the tools at your disposal. http://www.google.com/search?hl=en&q=XUL+python&a=http%3A%2F%2Fwww.google.com%2Fsearch&btnG=go PterK -- Peter van Kampen pterk -- at -- datatailors.com From __peter__ at web.de Tue Dec 9 06:46:52 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 12:46:52 +0100 Subject: Instance Exception Oddity: Implicit and Explicit not the same? References: Message-ID: RT Lange wrote: > but if o is an instance of an E subclass (hence isinstance(o, E) is still > true), > shouldn't the first form raise an exception with type E (not E's subclass) > and value o? Again: "If it is an instance of the class, the *instance* *becomes* the *exception* *value*" Or, directly from the source: /* if the value was not an instance, or is not an instance whose class is (or is derived from) type, then use the value as an argument to instantiation of the type class. */ (comment in function PyErr_NormalizeException() in error.c) As clear as you can get. I cannot comment on the rationale of that design decision, though. I would replace the raise E, args # disallow in 3.0? form completely with raise E(args) which would avoid the ambiguity altogether. Peter PS: I think you owe me an answer to Aahz' pending question now :-) From ajs at optonline.net Tue Dec 2 01:58:25 2003 From: ajs at optonline.net (Arthur) Date: Tue, 02 Dec 2003 01:58:25 -0500 Subject: Can Python be run off of a CD-ROM? References: Message-ID: <000501c3b8a1$aed647f0$1c02a8c0@BasementDell> > Hi all, > > I teach middle school and am currently trying to bring some computer science > to the students. Our district has a wonderfully linked network throughout > all our schools... done via MS Windows Network. In order to protect the > network, our district's IT department does not want things installed on the > system (or at least makes it VERY difficult to get it done). SO, I am using > MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it > off of them. I would take a look at Knoppix: http://www.knoppix.net/ Its a bootable iso image of a Gnu/Linux operating system which has recent Python distro included. Linux being a Very Good Thing for educational use, IMO. Perhaps even better for your purposes is FREEDUC Live CD-ROM of free software for schools http://www.ofset.org/freeduc-cd/ Knoppix based, stocked with free educational software meant for the grade levels you are concerned with. What I don't know if either has IDLE readily accessible. Certainly Freeduc should, if it doesn't. Art From ac007 at bluewin.ch Fri Dec 5 10:19:14 2003 From: ac007 at bluewin.ch (Alexandre) Date: Fri, 5 Dec 2003 16:19:14 +0100 Subject: xml.dom.minidom -> Xpath ? References: <3fcfdfdf$1_2@news.bluewin.ch> <3FD062C7.D79ADB74@hotmail.com> <3fd09122$1_1@news.bluewin.ch> <3FD09F53.558ACD86@hotmail.com> Message-ID: <3fd0a1f3_2@news.bluewin.ch> Thanks again for your help. Alexandre "Alan Kennedy" a ?crit dans le message de news:3FD09F53.558ACD86 at hotmail.com...> You have to install PyXML to get Xpath support. > > Try here for the software > > http://pyxml.sourceforge.net/ > > And there is some Xpath documentation here > > http://pyxml.sourceforge.net/topics/howto/section-XPath.html > > HTH, > > -- > alan kennedy > ------------------------------------------------------ > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/contact/alan From stain at stud.ntnu.no Wed Dec 17 01:32:03 2003 From: stain at stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 17 Dec 2003 06:32:03 +0000 (UTC) Subject: New style classes and rich comparison References: <9ASDb.132858$_M.686674@attbi_s54> Message-ID: * Rainer Deyke spake thusly: > Consider: > > class A(object): > def __hash__(self): return 5 > print hash(A) # Which function should this call? The hash method of A's class, ie. A.__class__.__hash__, usually type.__hash__. Hmmm. I think I get your point. hash and cmp and so on should call A.__class__.hash(A) to be generic enough. It's still confusing.. =) And how should I resolve this issue with my Dummy class? (it's ok for the Dummy class itself to be a Dummy, but it didn't work well to make Dummy = Dummy()) -- Stian S?iland Being able to break security doesn't make Trondheim, Norway you a hacker more than being able to hotwire http://stain.portveien.to/ cars makes you an automotive engineer. [ESR] From bmgz at dev.null Sun Dec 14 04:27:01 2003 From: bmgz at dev.null (bmgz) Date: Sun, 14 Dec 2003 11:27:01 +0200 Subject: gzip module - help! References: <3fdc2a06.0@news1.mweb.co.za> Message-ID: <3fdc2cd3.0@news1.mweb.co.za> Sorry, I forgot to mention that i am trying to create an archive. "bmgz" wrote in message news:3fdc2a06.0 at news1.mweb.co.za... > I am having problems trying to use the gzip module, I do the followig > > >>>import gzip > >>>file = gzip.GzipFile("testfile.txt") > >>>file.write() -which params does this accept?, archive name? > > I get this ERROR: > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/gzip.py", line 139, in write > self.size = self.size + len(data) > AttributeError: GzipFile instance has no attribute 'size' > > > But if I include a mode in "gzip.GzipFile("testfile.txt", 'wb')" or > something like that I don't get an error > and then I manage to do >>>file.close() but still I can't find any > compressed file? > > > > From mwh at python.net Sun Dec 7 10:54:50 2003 From: mwh at python.net (Michael Hudson) Date: Sun, 7 Dec 2003 15:54:50 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> <2lFAb.43218$aT.25634@news-server.bigpond.net.au> Message-ID: "Neil Hodgson" writes: > Ruby 2.0 will probably implement strings with encoding attributes. The > developers want to avoid changing encoding whenever possible. One posting I > saw had joining strings with different encodings as an error although I > don't know if this has been finalised. I doubt whether it will work well, so > I think the best approach for Python is to watch Ruby and if it is > successful then copy. "m17n" is the magic googling term but most of the > available information is encoded in Japanese (EUC). I fail to see what Python does so badly now that we might want to consider changing (of course, I haven't read Bengt's recent posts especially closely, but I found Martin's replies made rather more sense...). Cheers, mwh -- "Sturgeon's Law (90% of everything is crap) applies to Usenet." "Nothing guarantees that the 10% isn't crap, too." -- Gene Spafford's Axiom #2 of Usenet, and a corollary From tismer at tismer.com Tue Dec 16 06:59:24 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 16 Dec 2003 12:59:24 +0100 Subject: Preview of a Stackless Zope Application In-Reply-To: References: Message-ID: <3FDEF39C.5030606@tismer.com> Huy Do wrote: > Christian Tismer wrote in message news:... http://www.centera.de/tismer/stackless/zope_demo Please check the above URL again, I changed it a little, to fit on smaller screens. > Does this mean we can implement a Seaside(smalltalk) like application server ? > How cool is that. Oh yes (just looked into Seaside), I think it is very much like that. You can write one single program that deals with different input of the user until his data form is filled correctly, for instance. It needs some design work to make the necessary framework and to have a standard way to do this, but technically it is solved. If you have proposals, let me know. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From bhan at andrew.cmu.edu Sat Dec 27 21:19:57 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Sat, 27 Dec 2003 21:19:57 -0500 (EST) Subject: Simple way to get the full path of a running script? In-Reply-To: References: Message-ID: On Sat, 27 Dec 2003, Mark McEahern wrote: > On Sat, 2003-12-27 at 18:02, Benjamin Han wrote: > > Duh - the way I described seems to be simple enough: > > > > pathToScript=os.join(os.getcwd(),os.path.split(sys.argv[0])[0]) > > me = sys.argv[0] > print "This is the absolute path: %s" % (os.path.abspath(me),) Thank you - this is even better! From fredrik at pythonware.com Thu Dec 11 02:08:39 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 08:08:39 +0100 Subject: OT: Peter Hansen needs to use some humility (was Re: Python &Expect) References: <3FD7263E.110F9CC4@engcorp.com><3FD7906E.13832168@engcorp.com> Message-ID: Cameron Laird wrote: > Long term, the latter might be a greater benefit. I know how > much it means to me when someone helps me learn how to use > resources better. who has time to learn? wasn't the internet supposed to eliminate all that? From http Sun Dec 28 19:40:57 2003 From: http (Paul Rubin) Date: 28 Dec 2003 16:40:57 -0800 Subject: Special-purpose extension of Python -- new kinds of objects References: <6714766d.0312281442.78cd0a4b@posting.google.com> Message-ID: <7xwu8glali.fsf@ruckus.brouhaha.com> Jeff Epler writes: > In your case, you could re-cast the "decision network" in terms of class > definitions, and get pretty similar behavior if those classes have the > right behavior in metaclasses: > class my_example(DN): > class X(Chance): > cpd = gaussian(mean=25, std_dev=75) > class Y(Chance): > cpd = gaussian(mean=12, std_dev=19) > Z = X + Y When you say Z = X + Y, you've added two classes together. Can you actually do that with metaclasses? From hokiegal99 at hotmail.com Mon Dec 22 11:11:49 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 22 Dec 2003 11:11:49 -0500 Subject: Count Files in a Directory In-Reply-To: References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: <3FE717C5.1030102@hotmail.com> Jay Dorsey wrote: > On Sun, Dec 21, 2003 at 03:45:31PM -0800, hokiegal99 wrote: > >>I'm trying to count the number of files within a directory, but I >>don't really understand how to go about it. This code: >> > > > Do you want the total number of files under one directory, or > the number of files under each directory? Thanks for the tip... this bit of code seems to work: def fs_object_count(path): file_count = 0 dir_count = 0 for root, dirs, files in os.walk(path): for fname in files: file_count += len(fname) for dname in dirs: dir_count += len(dname) fs_object_count() From hokiegal99 at hotmail.com Mon Dec 29 18:36:07 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 29 Dec 2003 15:36:07 -0800 Subject: HDD Burn In with Python Message-ID: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> Hi Again, I have Macs, Windows and Linux PCs. I'd like to have a generic HDD burn in program to test new drives on all platforms. I know Python is portable enough to handle the platform differences, but would it be a good language for this type of application? The process would involve lots of reads and writes all over the drives for an extended period of time (several hours). Anybody else done something similar to this? Any suggestions? Thanks !!! From webmaster at beyond-thoughts.com Wed Dec 10 09:50:36 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Wed, 10 Dec 2003 15:50:36 +0100 Subject: Using XUL with python In-Reply-To: References: Message-ID: <3FD732BC.30409@beyond-thoughts.com> aifaik Peter Hansen is right. There's just no easy "plug & program"-library. You have to compile yourself a version of Mozilla. Basically following the instructions (search them on mozilla.org) isn't to hard and you'll get an Python-enabled Mozilla framework. However it takes a lot computing resources (I did this on a laptop PII 400/128MB and it took >24h to complete and >1GB diskspace) I agree that Mozilla should provide a readily useable XUL+(C, Python, Perl, Java, ...)-Framework. But nobody wants to do this task (it's my and your fault, too -- or would you do such a thing :-) ). cu cbf From newsgroups at jhrothjr.com Sat Dec 20 12:53:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 12:53:10 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Oren Tirosh" wrote in message news:mailman.376.1071937470.9307.python-list at python.org... > On Sat, Dec 20, 2003 at 08:44:45AM -0500, John Roth wrote: > > I'm not certain I'm making the connection. The visitor pattern > > as I use it doesn't seem to have much to do with generators. > > It's a way of disconnecting the sequencing logic from the > > processing logic, > > You mean like this? > > def generator(...): > sequencing logic, yield stuff > > for object in generator(...): > processing logic Good point. That's upside down from the way I usually think of it. > > > while a generator seems to encapsulate both in the same function. > > Can you give any specific reasons why you believe this to be the > case? Yes. You now have two sequencing constructs: the for loop and the loop inside the generator. The visitor pattern has only one: the for loop inside the .visit() method. John Roth > > Oren > From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 12 15:39:47 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 12 Dec 2003 21:39:47 +0100 Subject: porting python script from linux to windows References: Message-ID: <1m9ktv4bjfuvrir4mmelu4i0fjp2838ca9@4ax.com> hokieghal99: >What are the specific steps that one should take to make a python script >that works on a Linux x86 machine also work on a Windows x86 machine? Check for platform dependencies in the documentation of all modules that you use. >I am using os, re and string in the script. How do paths differ between >the two OSes? I am use to a unix-like path /blah/blah/blah. Would I need >to change this to x:\blah\blah\blah where x = drive letter? I'm currently developing an app on Windows and testing it for production on Linux. I use os.path.join() to construct pathnames and have encountered no portability problems. >What about creating fs objects? file works the same on both? Yes. But note the advice about binary files in the documentation of the open()/file() builtin function. >os.walk works the same? It works :-) -- Ren? Pijlman From mike at nospam.com Wed Dec 10 15:54:20 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 10 Dec 2003 12:54:20 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: <99dce321.0312100355.3e567ffa@posting.google.com> Message-ID: David M. Wilson wrote: > Microsoft, the plan to combine a traditional database and a > traditional filesystem never seems to come to fruition. AFAIK Microdoft never come out with revolutionary ideas, it makes mass-production of already proved concepts and excel in it. The idea of implementing filesystem interface on top of proved database pluses like transaction isolation, integrity, changes propagation and backup/restore mechanisms may come to something usefull due to them. > If you are interested in this sort of stuff, the only really serious Not really but thank you for the link. Mike From cjw at sympatico.ca Mon Dec 8 14:03:51 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 08 Dec 2003 14:03:51 -0500 Subject: How to graph two columns of x,y numbers? In-Reply-To: <9b849915.0312072230.5cab87b0@posting.google.com> References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: Todd, If you are using wxPython, you might consider wxPyPlot: http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html Colin W. Todd Gardner wrote: > Peter Hansen wrote in message news:<3FD3E423.B53D23DE at engcorp.com>... > >>Todd Gardner wrote: >> >>>I would like to graph two columns of x,y numbers? I would greatly >>>appreciate any pointers or suggestions. >> >>Yes, include more detail about what you want to do. Specifically, >>what platform, do you care if it's wxPython, or Tkinter, or something >>else, etc. There are about a zillion possible answers to your >>question as it stands, and "python graphing" or something on Google >>would likely get you a lot of mileage right now. Maybe after you >>do a little research there you can come back with a more detailed >>question? >> >>-Peter > > > There are LOTS of plotting choices on google. I guess I would like to > narrow them down by tapping into some expertise. > > I would like to do 2D and possibly 3D plotting with python. I am > tending toward wxpython because of it's ease of use. > > Any suggestions? Thanks in advance. Todd From bokr at oz.net Tue Dec 2 01:43:19 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Dec 2003 06:43:19 GMT Subject: newbie - integer variable with leading zero for os.makedirs References: <278a833.0312012112.55912355@posting.google.com> Message-ID: On 1 Dec 2003 21:12:57 -0800, jtoher at cyllene.uwa.edu.au (james) wrote: >I'm using python 2.3 and 2.2 on Mac OSX 10.3.1 > >My script creates directories from its input using os.makedirs > >This from http://www.python.org/doc/2.3.2/lib/os-file-dir.html: > > makedirs( path[, mode]) > Recursive directory creation function. Like mkdir(), but makes > all intermediate-level directories needed to contain the leaf > directory... > The default mode is 0777 (octal)... > >My text input specifies the mode as a string - '750', for example. I >want to convert the string input to an integer variable for use by >os.makedirs. > >makedirs works fine when I use a literal like 0750, but my problem is >setting a variable to that kind of value. int('0750') converts the >string from ascii to integer, but loses the first zero padding. It's not that it "loses" it, it's that it is ignoring it as an octal base indication, and converting with base 10: >>> int('0750') 750 >Without the leading zero os.makedirs makes a mess of the permissions >when it creates the path. > >I've tried: > >permission = int('750', 8) That was fine. You converted the string using base 8. >>> int('750', 8) 488 This 488 is a decimal printed representation of what the binary number is. If you want to see its value represented in octal again in *string* format, then you call oct with that number, and get a string back. >>> oct(488) '0750' If you want to see it in hex as a string, it's >>> hex(488) '0x1e8' But the number you get from the bare 0750 literal that worked is >>> 0750 488 The same binary number (judging by the decimal representation (488) that's being printed). >mode = oct(permission) you don't want this. If you want to bind the value to the name 'mode', you could write mode = permission or skip the 'permission' symbol, and just write mode = int('750', 8) > >but this returns an octal string '0755' and os.makedirs barfs again. >It really wants an integer and it really wants that leading zero. How It wants the integer, but you have a misconception about 'leading zero'. The leading zero you are looking at is in a printed string, not in the corresponding binary. The binary integer is probably a 32-bit integer, unless you have a 64-bit machine. You would need 11 octal digits besides the zero prefix to represent all the 'leading zeroes' in that. E.g., >>> '%012o'%488 '000000000750' Entered plain: >>> 000000000750 488 >can I assign a number with a leading zero to an integer variable? Just assign the integer you get from the conversion, e.g., >>> a = 0750 >>> b = int('750', 8) >>> a==b True So you can pass either a or b where you passed 0750 successfully before. Or use mode in place of a or b and pass that. There is an important principle behind this trivial stuff: The entities involved in programming are generally abstract, but we have to have concrete representations for them. The abstraction behind '0755' embedded without quotes in a Python source code context where it will be interpreted as a literal is the same abstraction that would be behind '488' without quotes in the same place, or '0x1e8'. These are three different character sequences representing the same thing. The leading zero you were looking at is a zero in the character sequence representation. The fact that there is no 'x' immediately following means it was an octal representation (if put in a literal source context). If put in a string literal (with actual quotes making it a source representation of a string) then you can pass that string to int(), but int() converts using base 10 unless told otherwise. And '0750' is valid as a decimal with the same value as '750' so the conversion from string to binary integer succeeds and gives the value 750. When you write a = int('0750',8) you are writing a Python source representation of an assignment statement. It's a sequence of characters, like any other source line, and it's a _representation_ of something executable. All the parts have to be converted into other representations, many things through multiple stages of different representation, until finally it's code in some context, and gets executed. Which means more looking at representations and and modifying other representations, and on and on. Keep in mind the difference between a thing and its many possible representations. IME, it helps in understanding stuff one comes across in programming (and maybe life ;-). Ceci n'est pas une pipe, it says on Magritte's painting, which depicts a pipe. (http://aux.planetmath.org/files/objects/3112/tensor-pipe.jpg) Regards, Bengt Richter From jacek.generowicz at cern.ch Fri Dec 12 05:17:16 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Dec 2003 11:17:16 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: bokr at oz.net (Bengt Richter) writes: > On Tue, 9 Dec 2003 23:50:06 -0500, "Francis Avila" wrote: > > >Stuart Bishop wrote in message ... > >>About the only thing that could be done then is: > >> > >>def memoize(callable): > >> cache = {} > >> def proxy(*args, _cache=cache): To be honest, I have trouble believing that a local variable lookup would be significantly faster than a closure lookup ... or is there some other point to this ? > >Not legal. *args must always come after default args. There's no way to do > Never say never ;-) > A function has the __get__ method, which is what getattr magic uses > to make a bound method. You can use this put cache in the "self" > position of a bound method, like > > >>> def sq(x): return x*x > ... > >>> def memoize(func): # callable is a builtin ;-) > ... def proxy(cache, *args): > ... try: return cache[args] > ... except KeyError: return cache.setdefault(args, func(*args)) > ... return proxy.__get__({}, proxy.__class__) > Looking at the code, it might be worth timing, if you have 90%+ cache hits. > I'd be curious to see what you get I get your version being almost imperceptibly slower. I used this: import timing import sys def Amemoize(func): def proxy(cache, *args): try: return cache[args] except KeyError: return cache.setdefault(args, func(*args)) return proxy.__get__({}, proxy.__class__) def Bmemoize(func): cache = {} def proxy(*args): try: return cache[args] except KeyError: return cache.setdefault(args, func(*args)) return proxy N = int(sys.argv[1]) def foo(n): if n<2: return 1 return foo(n-1) + foo(n-2) Afoo = Amemoize(foo) Bfoo = Bmemoize(foo) Acode = """ def Acall(): """ + "Afoo(10);" * N + "\n" Bcode = """ def Bcall(): """ + "Bfoo(10);" * N + "\n" exec Acode exec Bcode timing.start() Acall() timing.finish() print timing.micro() timing.start() Bcall() timing.finish() print timing.micro() From steve at ferg.org Sun Dec 28 18:30:43 2003 From: steve at ferg.org (Stephen Ferg) Date: 28 Dec 2003 15:30:43 -0800 Subject: ungetch in Python References: Message-ID: I've written a set of classes that wrap a file or a list. The heart of the matter (at least for what you're interested in doing) is the "current()" method, which allows you to specify an offset, which allows you to lookahead or backward. #------------------------------------------------------------- # # class: InputList # #------------------------------------------------------------- class InputList: """This class holds a list of strings. The list supports file-like operations. Subclasses can have the __init__() method over-ridden, in order to be loaded from files. """ def __init__(self, aList): """the aList argument should be a list of strings. """ self.items = aList self.reset() return def __len__(self): return len(self.items) def reset(self): # removed and converted to a method --- self.last_index() = len(self.items) - 1 self.index = -1 return def last_index(self): return len(self.items) - 1 def getnext(self): self.index = self.index + 1 return self.current() def get(self): return self.getnext() def current(self, lookahead_count = 0, value_to_be_returned_if_past_end=""): """return the item at the current position, unless we are past the last item, in which case return value_to_be_returned_if_past_end. """ lookahead_index = self.index + lookahead_count if lookahead_index > self.last_index(): return value_to_be_returned_if_past_end else: return self.items[lookahead_index] def eof(self,lookahead_count = 0): """look ahead lookahead_count items, and see if that position is past the end of the file. Return 1 if it is, otherwise return 0. """ lookahead_index = self.index + lookahead_count if lookahead_index > self.last_index(): return 1 else: return 0 def more(self): """The opposite of eof. A convenience feature. """ if self.eof() == 0: return 1 return 0 def getIndex(self): return self.index def current_count(self): return self.index + 1 def sortInsensitive(self): """A case-insensitive sort, in place. Uppercase A sorts before lower-case A. """ temp = [] for item in self.items: temp.append((item.upper(), item)) temp.sort() self.items = [] for item in temp: self.items.append(item[1]) del temp return None def size(self): return len(self.items) def remove(self, comment_indicator = None): """ Remove lines from the list if comment_indicator = None, remove all blank lines. Otherwise, remove all lines that have comment_indicator in column 1. """ indexes = range(len(self.items)) indexes.reverse() if comment_indicator != None: cLength = len(comment_indicator) for i in indexes: if comment_indicator == None: if self.items[i].strip() == "": del self.items[i] else: if self.items[i].strip()[:cLength] == comment_indicator: del self.items[i] def remove_trailing(self, comment_indicator = None): """ Remove lines from the list Like remove(), but works from the trailing end of the list, and works only as long as it finds a line that can be removed. if comment_indicator = None, remove blank lines. Otherwise, remove lines that have comment_indicator in column 1. """ indexes = range(len(self.items)) indexes.reverse() if comment_indicator != None: cLength = len(comment_indicator) for i in indexes: if comment_indicator == None: if self.items[i].strip() == "": del self.items[i] else: break else: if self.items[i].strip()[:cLength] == comment_indicator: del self.items[i] else: break def remove_leading(self, comment_indicator = None): """ Remove lines from the list Like remove(), but works from the front end of the list, and works only as long as it finds a line that can be removed. if comment_indicator = None, remove blank lines. Otherwise, remove lines that have comment_indicator in column 1. """ indexes = range(len(self.items)) indexes_to_remove = [] if comment_indicator != None: cLength = len(comment_indicator) for i in indexes: if comment_indicator == None: if self.items[i].strip() == "": indexes_to_remove.append(i) else: break else: if self.items[i].strip()[:cLength] == comment_indicator: indexes_to_remove.append(i) else: break if len(indexes_to_remove) > 0: indexes_to_remove.reverse() for i in indexes_to_remove: del self.items[i] def close(self): return def strip(self): # strip trailing whitespace (including newlines) from each line i = 0 while i < len(self.items): self.items[i] = string.rstrip(self.items[i]) i = i + 1 #------------------------------------------------------------- # end of class: InputList #------------------------------------------------------------- #------------------------------------------------------------- #class: InputFileOrStream #------------------------------------------------------------- class InputFileOrStream(InputList): def delete(self): if f_exists(self.myFilename): f_delete(self.myFilename) def filename(self): return self.myFilename #------------------------------------------------------------- # end of class: InputFileOrStream #------------------------------------------------------------- #------------------------------------------------------------- #class: InputFile #------------------------------------------------------------- class InputFile(InputFileOrStream): """Read a file as a list of lines. """ """This class is an abstract class for InputFile and Input Stream. _______ How to use it: code example ___________ import fpx infile = fpx.InputFile(infile_name) #or infile = fpx.InputStream(infile_name) infile.getnext() while not infile.eof(): print infile.current_count(),infile.current() infile.getnext() print "Processed", infile.total_count(), "lines in file", infile.filename() """ def __init__(self, name): """the name argument should be a text string containing the name of the file to be read in. """ # open the file and read it into a list, and close it self.myFilename = os.path.normcase(name) file = open(self.myFilename, "r") self.items = file.readlines() file.close() self.strip() self.reset() def linein(self): """A method for REXX compatibility. """ return self.getnext() def getline(self): return self.getnext() #------------------------------------------------------------- # end of class: InputFile #------------------------------------------------------------- #------------------------------------------------------------- # class: InputStream #------------------------------------------------------------- class InputStream(InputFileOrStream): """Read a file as a list of characters. """ def __init__(self, name): """The name argument should be a text string containing the name of the file to be read in. """ # open the file and read it into a list, and close it self.myFilename = os.path.normcase(name) file = open(self.myFilename, "r") self.items = file.read() file.close() self.myLineIndex = -1 self.myCharIndexInLine = -1 self.reset() return def charin(self): """Method for REXX compatibility. """ return self.getchar() def getchar(self): if self.myLineIndex == -1: self.myLineIndex = 0 self.myCharIndexInLine = 0 else: if self.current() == "\n": self.myLineIndex += 1 self.myCharIndexInLine = 0 else: self.myCharIndexInLine += 1 return self.getnext() #------------------------------------------------------------- # end of class: InputStream #------------------------------------------------------------- From SBrunning at trisystems.co.uk Mon Dec 15 12:48:28 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 15 Dec 2003 17:48:28 -0000 Subject: java.awt.Robot equivalent? Message-ID: <31575A892FF6D1118F5800600846864D01200DCC@intrepid> > From: Christopher Koppler [SMTP:klapotec at chello.at] > Autoit does exactly what I need (click on a specific coordinate in a > canvas-like window), and finally a reason to learn to use ctypes, > too... You don't really need to use ctypes to drive AutoIt - it's COM scriptable. Give me a shout if you want some examples of driving it - I'm sure I have some somewhere around here... But I gave up using it in the end, 'cos it was so fragile. If the wrong window gained focus, the script would die. Besides, there are some controls that it won't drive unless you are willing to resort to mouse clicks on absolute positions, which is also fragile. In the end, I just drove the Windows API directly. Yes, using ctypes a lot of the time. ;-) You can find my current work in progress here: http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html It's not far from being ready to go, actually. It just needs a few more tests, some introductory docs, and an installation script. It's quite useable, though - the functions themselves are well documented, and the test script gives you a good high level introduction. We use it a lot. Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From fumanchu at amor.org Sun Dec 7 19:02:13 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 7 Dec 2003 16:02:13 -0800 Subject: Case sensitive and ludicrous statements Message-ID: Douglas Alan wrote: > IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopl > eWouldWriteLike > ThisAllTheTime. The Greeks did that quite often. Some ideas take time. FuManChu From scott at alodar.com Mon Dec 1 19:09:00 2003 From: scott at alodar.com (Scott Ellsworth) Date: Mon, 01 Dec 2003 16:09:00 -0800 Subject: Rekall and associated software go 100% GPL References: <3fae9c76$0$12714$fa0fcedb@lovejoy.zen.co.uk> <3fb7eed4$0$12693$fa0fcedb@lovejoy.zen.co.uk> Message-ID: In article <3fb7eed4$0$12693$fa0fcedb at lovejoy.zen.co.uk>, "John Dean" wrote: > On 10-Nov-2003, Ben Finney > wrote: > > > On Sun, 9 Nov 2003 19:59:28 GMT, John Dean wrote: > > > You should also be aware that in order for for us to continue the > > > future development of Rekall we will have to charge for technical > > > support, customisation, training and consulting, therefore, now that > > > we have gone wholly GPL, you will have to take out a technical support > > > subscription. > > > > Sounds like a fine way to fund development and infrastructure. > > We have to make a living. Now you wouldn't begrudge that, would you. Besides > nobody is compelling you to take out a subscripion, are they. We could > always revert back to the commercial license, if you would prefer. Out of curiosity, has this change in focus made the MacOS X port more likely or less? I have emails from some months back about it happening, but slowly. Given that this is the platform of choice for the decision makers at one of my clients, this is going to be a neccesary, if not sufficient, condition for them to adopt the software. Scott scott at alodar.com Java, Cocoa, WebObjects and Database consulting (I do speak Python, but not well enough to sell services in it.) From fumanchu at amor.org Sun Dec 7 16:25:16 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 7 Dec 2003 13:25:16 -0800 Subject: Why Python won't work on .net Message-ID: It seems to be popular among the MBRGM (Management By Reading Glossy Magazines) crowd, many of whom are still allowed to make decisions. FuManChu > -----Original Message----- > From: Ville Vainio [mailto:ville.spammehardvainio at spamtut.fi] > Sent: Sunday, December 07, 2003 12:56 PM > To: python-list at python.org > Subject: Re: Why Python won't work on .net > > > allenabethea at aol.com (Allenabethea) writes: > > > > I am a new python tinkerer. I love the language. But what is its > > future but as a legacy tool? > > What, has .NET suddenly turned out to be popular while I wasn't > watching? The whole world is hardly jumping on the .NET platform, > actually mostly people seem to be ignoring it... > > Or is this a troll of some kind? > > You might also want to take a look at: > http://zope.org/Members/Brian/PythonNet/ -- Ville Vainio http://www.students.tut.fi/~vainio24 -- http://mail.python.org/mailman/listinfo/python-list From mikit at zoran.co.il Thu Dec 11 11:34:48 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 11 Dec 2003 08:34:48 -0800 Subject: Looking for ELF/PE library for Python References: Message-ID: <6250403b.0312110834.4796de7a@posting.google.com> Hello Bogdan, > Is there a Python library for working with ELF > and/or PE(Portable Executable) formats? By "working" I > mean handling file structure, dumping structure > information, extracting specific parts of the file and > even creating "by hand" new sections/relocations. I > already searched some locations for such a library, > but I couldn't find anything suitable. For just viewing information you can use the "objdump" utility which comes with GNU binutils (I think the MSVC has a "dumpbin" utility as well). HTH. Miki From mark at diversiform.com Wed Dec 10 11:20:01 2003 From: mark at diversiform.com (mark) Date: Wed, 10 Dec 2003 08:20:01 -0800 Subject: Pmw.ComboBox In-Reply-To: Message-ID: <002301c3bf39$77ca8cf0$5501a8c0@markxp> I guess I would wonder why you'd use a ComboBox that you didn't want someone to select anything from, but maybe you are disabling the widget conditionally. At any rate: Nochoice = Pmw.ComboBox() Nochoice._entryWidget['state'] = DISABLED Now, this is effectively disabling the entire widget, since it won't put anything in the entry box. I'm not certain if this is what you're looking for, but it works for me. - Mark -----Original Message----- From: python-list-bounces+mark=diversiform.com at python.org [mailto:python-list-bounces+mark=diversiform.com at python.org] On Behalf Of Gombos Katalin Sent: Wednesday, December 10, 2003 8:14 AM To: python-list at python.org Subject: Pmw.ComboBox Hi, How could I make the ComboBox state disabled? I don't want to let anybody to scroll the listbox of the ComboBox. Thank You! Katux -- http://mail.python.org/mailman/listinfo/python-list From afgncaap5 at aol.com Thu Dec 4 09:26:05 2003 From: afgncaap5 at aol.com (Afgncaap5) Date: 04 Dec 2003 14:26:05 GMT Subject: Hopelessly Lost And Desperate Newbie Message-ID: <20031204092605.01786.00000161@mb-m20.aol.com> Hello, there. I'm desperately in need of assistance, because I can't figure out how to get Python to work. Could someone help me with a program that can examine textual input in pairs of letters, keep track of how often the letters occur, and then write a random letter generator based on that input, do you? I mean,....well, let's say that this thing (in its most primitive state) would just count the occurances of a single letter. From the input, "a" occurs 12 times, "z" occurs 3 times, "q" occurs once, "e" occurs fifteen times, etc. Second level up, it would look at pairs of letters. It would know that "qu" occurs much more frequently than "qa", "re" occurs more than "ry", etc. The final level up, the one that I'm quite frankly not concerned with just yet, would look at triads of letters. "que" occurs more frequently than "qut", "qat" occurs more than "qab", etc. And then the random letter generator would use these letter frequencies to determine which letter to create next. It starts with the letter "q", checks its records, and notes that "qu" is much more frequently encountered than "qa", so it probably prints "qu" next. Then it sees that "up" occurs more than "ue", so it most likely prints "qup" instead of "que." Does this make sense, or am I rambling? Sorry for being so dense, but while I can get some of the stuff in all of the Python tutorials, there are a few things that I'm still having trouble even getting started with. From jjl at pobox.com Mon Dec 22 18:58:13 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Dec 2003 23:58:13 +0000 Subject: Naming conventions for iterator methods? Message-ID: <87fzfch0bu.fsf@pobox.com> How do people name their iterator methods / functions? eg. .iter_foo(), .foo_iter(), .iterfoo(), .fooiter(), .foos(), ...? Of course, dicts have .iterkeys(), .itervalues() and .iteritems(), but I don't like having words run together like that. My particular case: I have a class that can be iterated over in several ways, so I need to have a method other than __iter__ to return iterators. http://wwwsearch.sf.net/bits/pullparser.py The class pullparser.PullParser can iterate over HTML tokens (which includes tags, comments, declarations, etc.) or just over the tokens representing tags, skipping all other tokens. So __iter__ returns an iterator over tokens, and tag_iter() over tags. Then I wondered if I should be following a standard naming convention. There's a method .get_tag(), so I guess the should be related to that in some obvious way. John From gerrit at nl.linux.org Mon Dec 29 08:39:13 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 29 Dec 2003 14:39:13 +0100 Subject: strftime - %a is always Monday ? In-Reply-To: <282f826a.0312290503.398d72cd@posting.google.com> References: <282f826a.0312290503.398d72cd@posting.google.com> Message-ID: <20031229133913.GA3537@nl.linux.org> Richard Shea wrote: > Hi - I'm trying to use strftime to output the day of the week but I > find that I always get told it's Monday. I have tried day, month, year > etc and all come out correctly but as soon as I use %a I get 'Mon'. > I'm running Python 2.3.2 on a Windows 98 machine. Can anyone suggest > what the problem might be please ? > > This is a segment of the code which is manfests the behaviour ... > > >>> from time import localtime,strftime,time > >>> lst1 = ['2003','12','27'] > >>> strftime("%A,%d (%w %y > %m)",[int(lst1[0]),int(lst1[1]),int(lst1[2]),0,0,0,0,0,0]) > 'Monday,27 (1 03 12)' > >>> > > ... whereas the 27th was a Saturday ? time.strftime does not know about dates. Field number 6 specifies the weekday: make it a 1 and it will say Tuesday, 2->Wednesday, etc. You may want to use the new datetime module: >>> datetime.date(2003,12,7).strftime("%A") 'Sunday' yours, Gerrit. -- 131. If a man bring a charge against one's wife, but she is not surprised with another man, she must take an oath and then may return to her house. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From Samwatson at yahoo.com Tue Dec 9 23:16:04 2003 From: Samwatson at yahoo.com (Sam Watson) Date: Tue, 09 Dec 2003 23:16:04 -0500 Subject: Building a new app in python and need some architecture advice. References: <3fd51ecb$0$210$e4fe514c@news.xs4all.nl> <2v7atvkja4e7gd54sualt1d1jjprh9v0sg@4ax.com> <3fd52443$0$210$e4fe514c@news.xs4all.nl> Message-ID: <1b7dtv41tuh34oges2p061dl464otgcevr@4ax.com> >Well you have to define what "secure" is for you. >Secure can mean a lot of things. > By secure I mean hard to break into the server. I dont really care if the data coming in and out is secure. I want to maintain the server as little as possible. >What makes you think you would lose that with Pyro? >(and not with other IPC protocols) So as I try to access list, dictionary, or tuple items using the [] operator it will transparently fetch them as needed from the server? This is pretty cool if true. I assumed id have to use methods like GetNthItem SetNthItem or something like that. >on the communication stuff, and about performance: does a data >entry app have to shove 50Mbit/s over the network? > Nah, at most a few megs i would guess in a session. From peter at engcorp.com Tue Dec 9 11:43:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Dec 2003 11:43:03 -0500 Subject: regex confusion References: Message-ID: <3FD5FB97.CB8118FB@engcorp.com> "Diez B. Roggisch" wrote: > > John Hunter wrote: > > > > > In trying to sdebug why a certain regex wasn't working like I expected > > it to, I came across this strange (to me) behavior. The file I am > > trying to match definitely contains many instances of the letter 'a', > > so I would expect the regex > > > > rgxPrev = re.compile('.*?a.*?') > > This is a bogus regex - a '*' means "zero or more occurences" for the > expression to the left. '?' means "zero or one occurence" for the exp to > the left. Not true. See http://www.python.org/doc/current/lib/re-syntax.html : *?, +?, ?? The "*", "+", and "?" qualifiers are all greedy; they match as much text as possible. .... Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. .... -Peter From try_vanevery_at_mycompanyname at yahoo.com Thu Dec 25 17:12:12 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 25 Dec 2003 14:12:12 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "Tom Plunket" wrote in message news:opamuv0esr85tsu1mfpmkvlniuga5frd4c at 4ax.com... > Brandon J. Van Every wrote: > > > I am > > > > - *TENTATIVELY* - > > > > (operative word) undertaking the project of porting... > > Brandon, why not heed the advice that one holds back such an > announcement until someone actually has something interesting to > announce? Because if someone has my project goals and wants to volunteer source control right now, I'm taking them up on it. Here's the consideration on that: some people are telling me to use TLA, not CVS, so that means it's not just a hop-skip-jump to Sourceforge. >You know how many of these sorts of projects are > started, and you know how many of these projects get carried > through to completion. Yes I do. And you'll notice that I didn't start a mailing list, or really ask for any help. All I need at this point is: 1) gauge project interest 2) sanity check my goals, in the face of opposition 3) see if anyone happens to be ready and willing to work towards the same goals > > - the primary language of ProtoCiv development will be Python. > > Seems like a huge waste of time, One of the meta-goals is Python advocacy in the field of Game Design. Given my strategic view on the matter, it is not a waste of time, unless it is too much work to have any chance of ever getting done. > starting with the fact that > editing the C codebase to do what you want is likely, at this > point, far easier. Even the "simple" act of eliminating the Cygwin dependencies is proving to be a chore. C is not a good language for anything but portable assembly. > Since it's GPL'd, it's not like you couldn't just fork the > project and do it in C, sticking Python on for new bits as > appropriate. Do you have an understanding of what it takes to put on "new bits" in Python? I'm thinking not. > Show us the money. Excuse me? If you are in a snit about anyone communicating about stuff, if that's your personal taste, then that's your problem. > Let us know when there's something to see. > Until that point, you might heed the advice here: > http://www.sloperama.com/advice/lesson24.html#tal > Scroll to entry 16 if your browser doesn't go for you (Opera, for > example). I could argue all sorts of reasons why it's not "stupid" to state what I have, but I won't bother. That *would* be stupid; as I said initially, if you don't have my goals let's not waste the breath. > > - I'm a commercial developer, not a hobbyist. > > Good luck. You haven't made any money yet, right? It's been > five years? Almost six. And I'm still doing what I want to do, so that should tell you something. > > - Because of the GPL license, no commercial gain of any kind is > > believed possible with this project. > > Just because the code is GPL doesn't mean the assets need to be. But I'm not Mr. Art Guy cranking out assets. They will probably come from other people, and it will depend on their sensibilities on whether they're GPL'd or not. > Regardless, nothing is preventing you from sticking it on a CD > and charging money for it. Sure there is. First CD sold, someone else can do exactly the same thing. What's the point? Unless you're doing online subscription stuff it is difficult to have a service model for games. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From fredrik at pythonware.com Sat Dec 13 06:30:21 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Dec 2003 12:30:21 +0100 Subject: Tk -- stupid blank dialog opens up in background References: <3fdaec17.0@news1.mweb.co.za> Message-ID: "bmgz" wrote: > I am just starting with python, I found it anoying that when I use Tk, a > blank dialog always opens up behind tkMessageBox or whatever other gui > element one executes.. Is their a way of disabling this? the "blank dialog" is Tkinter's root window. to eliminate that, explicitly create a root and withdraw it before proceeding: root = Tkinter.Tk() root.withdraw() # won't need this if you're building a full-blown Tkinter application, the usual approach is to put your widgets in the root window: root = Tkinter.Tk() mybutton = Button(root, text=...) mybutton.pack() # etc From JTesser at nbbc.edu Fri Dec 19 09:28:58 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Fri, 19 Dec 2003 08:28:58 -0600 Subject: dynamic typing question Message-ID: <04875CB4331F0240A0AD66F97097865101137714@paul> I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from registration to business office. We are considering useing Java or Python. I for one don't like Java because I feel the GUI is clunky. I also think that we could produce quality programs faster in Python. The other programmer here is very concerned about dynamic typing though in Python. He feels like this would be too much of a hinderance on us and too easy for us to make a mistake and not catch it until runtime making debugging harder. OK what are your guys thoughts here? How have you all overcome the lack of static typing? Is Python a bad decision here? By the way we will be using Postgres in the back if that matters to anyone. From sombDELETE at pobox.ru Wed Dec 17 16:51:26 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Thu, 18 Dec 2003 00:51:26 +0300 Subject: [Python-Dev] Re: rexec.py unuseable References: <1071669397.3fe06095c9f3c@mcherm.com> Message-ID: "Luke Kenneth Casson Leighton" wrote in message news:mailman.258.1071687992.9307.python-list at python.org... > in my experience (windows nt services and therefore also samba-tng's > services), access control lists have been an extremely successful > means to provide security in almost every single program in the > NT operating system (i don't mean XP i don't mean windows 95) for > almost 15 to 20 years. > > it seems quite logical therefore to propose that such a successful > security model be adapted to fit a programming language, or at least > to learn from its success (and failings). Success? It's a total failure, imho. Witness millions of troyans and worms infiltrating windows ntfs filesystems, reading, writing, executing and deleting files despite acls all over. Besides you can't do certains things with pure acls. For example how do you grant to an email program ability to read/write to one work directory and attach and save _any_ files from anywhere by control of the user? With capabilities you can. It's very simple. With acls alone you can't do it at all. From f29 at gazeta.pl Wed Dec 17 16:45:39 2003 From: f29 at gazeta.pl (f29) Date: 17 Dec 2003 13:45:39 -0800 Subject: Save the pythons. Message-ID: I don't believe that noone has yet spotted that python is becoming java. Each new version is fully equipped with more garbage than before. Classes are great, but once there are 1000 of them, inheriting from each other, I cannot avoid comparing this unpleasant situation to java. Python power is in it's syntax, not addons. Let's not copy perl's experience and one java is already far too much for earth. f29 From paul at fxtech.com Tue Dec 16 11:15:39 2003 From: paul at fxtech.com (Paul Miller) Date: Tue, 16 Dec 2003 10:15:39 -0600 Subject: PyThreadState_Swap difference in 2.3.2? References: Message-ID: <6obutv86apdtrt6hgb6fvrra2rp843gia0@4ax.com> >> assert(mro != NULL); >> >> This was for a custom Python type I had created in C. It was assuming this >> mro field was initialized, which it wasn't. It must be something new, >> because this all used to work in 2.2 >This assertion appears in PyObject_GenericGetAttr(). What was the >attribute being requested? I'm guessing your extension type is doing >something funky, as otherwise PyObject_GenericGetAttr() would not be called. I am using GenericGetAttr() so my tp_getset list will work. This used to work in 2.2. >I *think* that having tp_flags as zero works OK, but as soon as you use >Py_TPFLAGS_DEFAULT, you are expected to initialize your type >differently. Sorry, but I can recall any more details. Nope, that didn't help. Since I am using new-style types, I had to have most of those flags set anyway. It seems to me that GenericGetAttr() should not assume mro to be initialized. I haven't come across any sample custom types that initialize it, and for whatever reason, it is not getting set up automatically. From sam at samuel-kleiners-computer.local Sun Dec 7 00:21:58 2003 From: sam at samuel-kleiners-computer.local (Samuel Kleiner) Date: Sat, 06 Dec 2003 23:21:58 -0600 Subject: New inited instance of class? References: Message-ID: Francis Avila wrote: > Ah! You're using classic classes. Don't do that. Ok, thanks- So can I make all my classes derive from object without doing so explicitly- IE, without having to change every single top-level class definition? -- Loren ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh eusmod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation From alan.gauld at btinternet.com Mon Dec 29 04:03:51 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Dec 2003 09:03:51 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <3fefeba6.468825104@news.blueyonder.co.uk> On Sun, 28 Dec 2003 18:15:49 -0800, engsolnom at ipns.com wrote: > I've been using constructs(?) like the below. > > def display(instance, start = None, end = None): > if instance.__class__.__name__ == 'UPCA': > do some UPCA stuff > if instance.__class__.__name__ == 'UPCE': > do some UPCE stuff > > launched by: > > lx = UPCA(sx), where sx is a string > then: > display(lx) Any reason not to use an OO style and do: lx = UPCA(sx) lx.display() That way you miss out all those horrible if instance... checks. Its much easier to maintain too since if you add a new class you only need write a display method in the class, you don;t need to extend the if/elif chain too. > What I'd like to do is display is the instance name. Is it hiding > somewhere? What is the instance's name? It is an object referenced by a variable(or maybe by several variables...). Unless you have defined a name attribute then the instance has no name. > Also, if I have a string 4 chars long, representing two bytes of hex, > how can I *validate* the string as a *legal* hex string? hexdigit = "-0123456789abcdefABCDEF" def ishexdigit(n): return 0 not in [x in hexdigit for x in n] Not fast but it should work... > Is there a 'ishexdigit'? I could parse the string, but that seems > "un-Pythonish" How else would ishexdigit work? :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jjl at pobox.com Tue Dec 23 08:14:19 2003 From: jjl at pobox.com (John J Lee) Date: Tue, 23 Dec 2003 13:14:19 +0000 (GMT) Subject: Naming conventions for iterator methods? In-Reply-To: <20031223021642.GA15171@titan.progiciels-bpi.ca> References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> Message-ID: On Mon, 22 Dec 2003, [iso-8859-1] Fran?ois Pinard wrote: > [John J. Lee] > > How do people name their iterator methods / functions? > > > eg. .iter_foo(), .foo_iter(), .iterfoo(), .fooiter(), .foos(), ...? > > I took the habit of naming such methods and functions with names > starting with `all_', so I can write: > > for name in all_names(): > do something I don't like that, because often my iterator-returning methods take arguments to restrict the iterees: shop.iter_cheeses(variety="smelly"). > or maybe: > > tokens = all_tokens() > ... > token = tokens.next() > ... I just realised some of these methods of mine don't actually return iterators, but merely objects supporting the iterator protocol. In other words, the returned objects have an .__iter__() method, but not a .next() method (usually because I've quickly implemented the method by returning a sequence, leaving the way open for a later reimplementation that, eg., returns a lazy iterator). Would that surprise people from a method named .iter_foo()? > I find this more legible than forcing the string `iter' here and there, > and leaves a bit more freedom to change the code later -- let's say, if > I ever want to substitute a solid list for the iterator. I can keep the > `all_' prefix, while I would feel uncomfortable it were some `iter' in > the names. Granted, if I want to use `.next()', I'll have to plunk one > more `iter()' in the code. That's one data point :-) I think I'll go with .foos(), for the same reason you choose .all_foos() -- it'll make people read the docs if they need to know whether it's a sequence, iterator, or object supporting the iterator protocol. John From danb_83 at yahoo.com Sat Dec 13 03:50:22 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Dec 2003 00:50:22 -0800 Subject: do this with list comp? References: Message-ID: "Michael T. Babcock" wrote in message news:... > python-list-request at python.org wrote: > > > From: John Hunter > > Date: Fri, 12 Dec 2003 10:46:58 -0600 > > > >I want to replace all empty fields in a CSV line with 'NULL'. ... > >I am wondering if there is a way to do it with list comprehensions. I > >know how I would do it with a ternary operator..... > > def replace_blank_with_null(data): > if not data: > return "NULL" > return data > > new_list = [ replace_blank_with_null(line) for line in old_list ] > > Or something more like: > > line_items = [ replace_blank_with_null(item) for item in line.split(",") ] Or: line_items = [item or 'NULL' for item in line.split(',')] From anton at vredegoor.doge.nl Wed Dec 17 07:30:36 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Dec 2003 13:30:36 +0100 Subject: Converting integer to binary representation References: Message-ID: <3fe04d14$0$127$3a628fcd@reader1.nntp.hccnet.nl> Mark Dufour wrote: >I want to loop over the binary representation of numbers, for use in some >algorithm dealing with prime numbers. Of course, there are multiple ways of >doing this, but I like the clean: 'for power, bit in >enumerate(binary(number))', possible with the above code. Currently strings are immutable sequences of characters. So it would be possible to do what you write above if integers where seen as sequences of boolean in the same way. I guess it's obvious if you're Dutch: >>> list(10) >>> [True,False,True,False] Anton From david at rebirthing.co.nz Mon Dec 8 22:35:16 2003 From: david at rebirthing.co.nz (David McNab) Date: Tue, 09 Dec 2003 16:35:16 +1300 Subject: 'import time' fails when embedding Message-ID: <3FD542F4.2040209@rebirthing.co.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I'm working on a python plugin for someone else's code written in C. On the whole, I'm successfully embedding the python interpreter, importing the python module, creating python classes and using their methods. But when I added 'import time' to my python module, I got the error: line 27, in ? ~ import sys, os, stat, traceback, thread, time ImportError: /usr/lib/python2.3/lib-dynload/time.so: undefined symbol: PyExc_IOError Is there anything I need to add to the 'link' command for my code so that the embedded Python can find everything it needs? - -- Kind regards David - -- leave this line intact so your email gets through my junk mail filter -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQE/1UL0UuEuev/PjrcRAubHAJ9TTBvR74a8LD3siUZ8/i3RruEzqgCeNUaf k63DxDgb/hLuhSog07wfRzg= =7aGW -----END PGP SIGNATURE----- From __peter__ at web.de Fri Dec 19 03:03:01 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 09:03:01 +0100 Subject: cleanup after exceptions References: Message-ID: Tim Peters wrote: > [Peter Otten] >> ... >> There seems to be some dark corner of the exception infrastructure >> that exc_clear() doesn't touch. > > It's probably just an artifact of running in interactive mode. Then you > also have to worry about sys.last_traceback (see the sys docs). >>> class T: ... def __del__(self): ... print "i'm gone" ... >>> def f(): ... t = T() ... raise Exception ... >>> import sys >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f Exception >>> sys.last_traceback = None i'm gone >>> You're right. No dark corners then... Peter From donn at u.washington.edu Wed Dec 24 12:23:23 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 24 Dec 2003 09:23:23 -0800 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: In article <%QbGb.2109$1f6.732 at newssvr25.news.prodigy.com>, "Moosebumps" wrote: > I'm fairly new to Python, and wondering if you can just list a bunch of > objects as data. For example, in C you would just do something like this: > > struct > { > int a; > float b; > } mystruct; > > mystruct x = { 3, 5.0f }; > mystruct y = { 5, 15.0f }; > > These are just "data". Obviously in python you could just write an init > function like this: > > x.a = 3; > x.b = 5; > > y.a = 5; > y.b = 15; Well, strictly speaking I think the obvious init function would be looking more like self.a = 3, etc. What you have written is legal, if not obvious. (And lose the semicolons!) > And that would work fine, but the programmer in me says that that's a pretty > inelegant way to do it. Why execute code when all you need is to put data > in the program? I think the above paragraph may account for the dismissive responses you have gotten so far. While your analysis of the Python model is structurally fairly sound as far as it goes, your instincts about what is elegant are utterly misguided! You are not the first person to ever experience this, though. > A thought that occured to me is that classes are implemented as dictionaries > (correct?). So you could have a dictionary like this: > > x = {'a': 3, 'b': 5} > y = {'a': 5, 'b': 15} > > This would be the __dict__ attribute of an object I suppose. But I don't > see anyway to assign it to a variable so you could access them like x.a and > y.a. I don't know if this would be a "nice" way to do it or not. class A: def __init__(self): self.__dict__.update({'a': 3, 'b': 5}) x = A() print x.a, x.b Would it be nice? No, it would be horrible, unless you had some very compelling reason to do this, in which case it would be fine. > Question 2: > > If "subfolder" is a folder under "basefolder", and basefolder contains > "base.py", and subfolder contains "sub.py", how do I import sub.py into > base.py? From what I can tell so far it only works if the files are in the > same directory. I need to be able to do this without modifying any > environment variables or anything. Because the scripts will be run on many > different machines and I have no way of automatically configuring them. import sys sys.path.insert(0, 'basefolder/subfolder') Donn Cave, donn at u.washington.edu From hong.jiang at acm.org Wed Dec 24 03:52:16 2003 From: hong.jiang at acm.org (Hong Jiang) Date: Wed, 24 Dec 2003 03:52:16 -0500 Subject: implementing mv Message-ID: Hi, Is there an efficient way to implement the 'mv' command? I mean not by calling external commands. Moving a file can be done by first making a hard link then unlinking the original file. But I cannot figure out a good way to move a directory. Do I have to move all the files and subdirectories recursively? Thanks. From skip at pobox.com Fri Dec 19 21:09:44 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Dec 2003 20:09:44 -0600 Subject: semi-OT: DNS issues for python.org (re-send) In-Reply-To: References: Message-ID: <16355.44904.529915.592465@montanaro.dyndns.org> Ben> I'm seeing a lot of "lame server" messages from my name server when Ben> trying to resolve mail.python.org and neither my name server Ben> (devious.adversary.org) nor those of my upstream Ben> (yarrina.connect.com.au & warrane.connect.com.au). In fact, one of Ben> my upstream's caches (yalumba.connect.com.au) is locating what Ben> appears to be invalid nameservers for python.org. The python.org domain is in transition between CNRI and the PSF. I imagine things will settle down in the next day or so. Skip From http Wed Dec 10 15:33:59 2003 From: http (Paul Rubin) Date: 10 Dec 2003 12:33:59 -0800 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> Message-ID: <7xsmjs9zuw.fsf@ruckus.brouhaha.com> aaron at reportlab.com (Aaron Watters) writes: > In order to allow transactions to wait the options are: > > 1) Use an event loop and write the application "inside out", > much like a fortran 4 program attempting to emulate recursion. > ... Maybe you could find some clever way to do it with Python generators. From mbabcock at fibrespeed.net Wed Dec 17 16:41:15 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Wed, 17 Dec 2003 16:41:15 -0500 Subject: OO issues in python In-Reply-To: References: Message-ID: <3FE0CD7B.300@fibrespeed.net> > in python, when a class, say Father, has a member that itself is an > instance of another class, say Child, an instance of Father actually > only has a reference to a Child, not the Child object itself, right? I've seen a few responses to this but I wanted to point something out ... an instance of the Father will not know about the Child at all. class Father: pass class Child(Father): pass f = Father() # f knows nothing about Child However, the rest of your message sounds like "how do I do virtual functions?" to me ... you're aware that you can replace parent functions, correct? class Father: def run(self): '''run the function; used in children''' pass def __init__(self): '''this is stupid but its just an example''' self.run() class Child(Father): def run(self): '''child version of the run function''' print "Hello" >>> c = Child() Hello -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From dmq at gain.com Mon Dec 1 21:05:51 2003 From: dmq at gain.com (David MacQuigg) Date: Mon, 01 Dec 2003 19:05:51 -0700 Subject: passing global data to a function References: <3064b51d.0312010855.66f4e2@posting.google.com> Message-ID: <0oqnsvce66u6hcttqlnbudvic6ie0ue4bt@4ax.com> On 1 Dec 2003 08:55:38 -0800, beliavsky at aol.com wrote: >How can I pass global data to function stored in a separate file? >For example, in file "funk.py" is the code > >ipow = 2 >def xpow(xx): return xx**ipow > >and in "xfunk.py" is the code > >from funk import xpow,ipow >xx = 4.0 >print xpow(xx) >ipow = 3 >print xpow(xx) > >Running Python against xfunk.py, I get the output > >16.0 >16.0, > >so the value of ipow in function xpow is not being changed. I want ipow to equal >4 in the 2nd call to xpow, so that the output would be > >16.0 >64.0 I found the scoping rules confusing also. In case anyone is writing a text, here is a simpler example: def fonc(): return p # from funk import fonc # same def, but in module funk.py # import funk p = 2; print fonc() p = 3; print fonc() ### RESULTS from uncommenting line #N, where #N = #1) As expected. #2) 'p' is not defined. #3) 'fonc' is not defined The variable 'p' trickles down ONLY to definitions within the same module. ( "Lexical scoping", as explained by Terry Reedy. ) I'm not sure why this is the right thing to do, but after a few months of working with Python, my confidence is still growing that the designers made the right choices. This is a superb language!! Perfect for a technical professional like myself who is not a programmer. Anyway, I have no complaint about this limitation. I agree with Bengt Richter, this "back door" is not a good way to pass parameters into a function. Now if only we could simplify the scoping rules by having global definitions pass down through nested classes the same as they do through nested functions ... :>) -- Dave From Scott.Daniels at Acm.Org Fri Dec 12 10:07:51 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 12 Dec 2003 07:07:51 -0800 Subject: nested function scopes In-Reply-To: <3fd83270$1@news.broadpark.no> References: <3fd83270$1@news.broadpark.no> Message-ID: <3fd8a29e$1@nntp0.pdx.net> Nils Grimsmo wrote: > i'm having some trouble nesting functions. consider the following: You understand the rules, I think. You just don't like them. The appropriate koan is "explicit is better than implicit". I'd use something like this: class Struct(object): pass ... def outer(): shared = Struct() shared.counter = 1 def inner(): print 'inner says:', shared.counter shared.counter += 1 inner() inner() print 'outer says:', shared.counter > it would be very handy to be able to do this if i have nested > functions that use a lot of variables. only passing the variables > you assign to as packed compound parameters is a bit ugly, > since what subset of all variables this is might change. Python's goal is to make code more easy to _read_, not _write_. I find it easier to read the outer function when I know what might change on me. As my example shows, you needn't thread all calls with the list of values. There is another python idea here you haven't yet caught: You speak of variables, but python only has associations of names with values. When you think in terms of names and associations, you may find 'inner's ability to see what 'outer' is talking about without being able to affect 'outer's associations reasonable. > i cannot say i like the python scope rules yet. they probably are > practical, but they seem complicated an unstructured to me. Give it time. They are simple when you twist your head just right, then they will seem completely simple. > class C: > y = 0 > def f(self): > print y Again, "explicit is better than implicit". Either: class D(object): y = "D's y" def f(self): print self.y Or: class E(object): y = "E's y" def f(self): print E.y behave as you wish. Bindings first look to the instance and then the class. Python is quite dynamic. There is, by the way, a difference between the two above. Ponder the following two subclasses: class F(D): y = "F(D)'s y" class G(E): y = "G(E)'s y" F().f() prints F(D)'s y G().f() prints E's y to work in the same was as the two above, but you'd be wrong. > In the previous example, with the functions h() and g(), g() > why should not f() take y from C? but which class should it choose in my examples? The instance's exact class? The class in which the method was defined? You could mean either, and be without a way to specify the other. Further, you could do this: y = "global" class C: def f(self): print y o = C() o.f() C.y = "classs variable" o.f() Should the second call to o.f() print something different than the first one? Anyhow, this is really too long already. I'll just include the Struct definition I actually use when coding. It uses too much magic to be clear, but it prints nicely in interactive mode. This in my "toys.py": class Struct(object): def __init__(self, **kw): self.__dict__.update(kw) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%r' % name_val for name_val in self.__dict__.items()])) Then (when I want data types): import toys class Holder(toys.Struct): pass # just to give a name And my example becomes: def outer(): shared = Holder(counter=1, name='Fred') def inner(): print 'inner says:', shared shared.counter += 1 inner() inner() print 'outer says:', shared -Scott David Daniels Scott.Daniels at Acm.Org From fredrik at pythonware.com Thu Dec 11 02:01:14 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 08:01:14 +0100 Subject: python w/expat compiled on one box doesn't work on another References: Message-ID: "Doug" wrote: > Can someone point me in the right direction as to why it doesn't find > the expat parser on the other machine. I can see the expat files in the > /usr/local/lib/python2.2/xml/parsers directory. the xml/parsers directory contains the Python parts of the expat interface, but there's also a binary module (usually called "pyexpat.so"). what happens if you import pyexpat directly? >>> import pyexpat From eric.brunel at N0SP4M.com Wed Dec 3 03:59:30 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Wed, 03 Dec 2003 09:59:30 +0100 Subject: Tkinter question: how to the red "Tk" window title bar icon? References: Message-ID: Howard Lightstone wrote: > "John Benson" wrote in > news:mailman.58.1070409537.16879.python-list at python.org: > > >>Hi, I'm using Tkinter and would like to know how to replace the red >>"Tk" logo in the left corner of the title bar of the root window with >>some other icon. >> >>Another question for curiosity's sake: >> >>I've often seen Tkinter referred to as the "standard" Python GUI. I >>assume that this is because it may be the oldest and perhaps the most >>cross-platform. Is that all that can be said for it? I've already >>heard about the Tkinter interpretive overhead, but given the amazing >>increase in CPU speeds recently, I wave my paw and just say "Bah!" >>(something I learned from Dogbert). Any other comments? >> >>Thanks in advance for any aid and comfort. >> >> >> >> > > > Try hackicon if you are on Windoze > http://sourceforge.net/projects/hackicon/ On reasonably recent versions of tcl/tk, the methods iconbitmap and iconmask on instances of Toplevel (or Tk) should work on Unices and Windows. See the corresponding commands for tk at: http://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From logan at phreaker.nospam Mon Dec 1 11:57:57 2003 From: logan at phreaker.nospam (Logan) Date: Mon, 01 Dec 2003 17:57:57 +0100 Subject: wxPython / styles and marks in TextCtrl Message-ID: I asked a similar question already in the wxPython mailing list, but did not get an answer up to now: 1.) When using a TextCtrl with styles (color etc.) in wxPython, is it then possible to get a 'list' (or anything) from the widget which tells you which styles are used in the widget (and where!; 'beginning of style', 'end of style', 'type of style' ...)? 2.) Is it possible to set something like a mark in a TextCtrl? (E.g.: Suppose you put the sentence 'Hello World!' into the TextCtrl and mark the character 'W' of the word 'World'; now, if the text in the TextCtrl changes, it should be possible to get the new position of the character 'W' from that mark.) I think, both should be possible, but I did not see it in the documentation; maybe I missed something elementary? Thanks in advance for any help! -- mailto: logan at phreaker(NoSpam).net From h.goebel at crazy-compilers.com Sat Dec 20 07:12:06 2003 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Sat, 20 Dec 2003 13:12:06 +0100 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <3fe43c97$0$19069$9b4e6d93@newsread2.arcor-online.net> John Roth wrote: > "Steve Lamb" wrote in message >> If you had run it you would have understood it. You didn't run it, >> did you? > > It doesn't matter. As you can see by my reply to Bengt, It does matter, since the _output_ of the result (which Steve posted for your convenience) contains the answer to your question. > the crux of the issue is that, in Ruby, the function call > syntax is *optional.* The crux of this 'option' is that it's ambiguos whether you wnat to _access_ or _call_ the function object. See line 12 of the output meantioned above to know why Python will never implement such an 'option'. [And BTW I probably will never use a language having such an 'option'.] > What I'm missing, however, is any *thoughtful* > discussion of the issues involved. Your [perjoritive > adverb deleted] response makes it clear that you > didn't think of the issues, you just reacted. *walking to the fuel-station, filling my many-years-unused flame-thrower for the upcoming flame-battle* > John Roth -- Regards Hartmut Goebel | Hartmut Goebel | We build the crazy compilers | | h.goebel at crazy-compilers.com | Compiler Manufacturer | From dave at pythonapocrypha.com Fri Dec 12 11:30:17 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 12 Dec 2003 09:30:17 -0700 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <01c401c3c0cd$3afe5140$891e140a@YODA> Edward wrote: > > > > It's not clear that wxWindows really actually works. > > > > Isn't that last sentence a bit overly FUD-ish? > > > Umm. Maybe you are right. > > After sleeping on this question, I think not :-) True, my choice of words > wasn't the best, but since you brought up FUD, I'm willing to discuss my > fears, uncertainties and doubts about wxWindows. > > Motivation & experience > > The typical FUD campaign is driven by ulterior motives. I have no such > motives --I am not the author of a product that competes with wxPython or > Tkinter Well, I'm not really interested in pressing the issue (I don't have ulterior motives either ;-) ), but if not FUD, it was inaccurate in the _general sense_ as many applications are built upon wxWindows/wxPython and do not have problems. I do not doubt that you've experienced problems with that framework; but I do take issue with the implication that such an experience is the norm - for example, the wxWindows site has quite a list of examples that use it, and many of which are quite widely used and certainly not toy applications (AOL Communicator, Audacity, etc.), so I'd say it _is_ clear that it "actually works". I have a hard time understanding how wxWindows could be so flaky and buggy and yet still enjoy such commercial and open source success - why aren't the people who use it drowning in support calls/emails? > In my experience, it is a _fact_ that wxPython (really wxWindows) seems to > have many more bugs than Tkinter. It is a _rare_ bug that has no > workaround, so this fact does _not_ mean that it is impossible to produce > "working" apps with wxWindows/wxPython. What is probably _does_ mean is > that it will be more expensive to create a solid wxPython app than one would > hope. In my experience, the answer to the question "Why the hell hasn't > wxPython become the standard GUI for Python yet?" is: "wxWindows is buggy." The good news is that the wxWindows and wxPython developers are pretty good about fixing bugs, so there's a good chance that all the bugs you found and reported to them have been fixed by now. ;-) It was good talking to you. Congrats on your progress with Leo - pretty neat! -Dave From bokr at oz.net Sun Dec 21 21:51:01 2003 From: bokr at oz.net (Bengt Richter) Date: 22 Dec 2003 02:51:01 GMT Subject: memory overhead using from-import? References: <20031221102848.4f901801.wtrenker@shaw.ca> Message-ID: On 21 Dec 2003 22:44:18 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >Alternatively, I guess some ambitious wizard could code up something so you could >write > > thing, another = from_extract(modulename, thingname) Oops, I meant thing, another = from_extract(modulename, thing, another) > >in place of > > from modulename import thing, another > >to get the effect you want (or maybe an exception ;-) Regards, Bengt Richter From rainerd at eldwood.com Sat Dec 20 02:09:27 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 20 Dec 2003 07:09:27 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Carl Banks wrote: > Now, do have any evidence that non-constant, default arguments (as > they are now) are USEFUL? def draw_pixel(x, y, color, surface=screen): screen[y][x] = color > (I don't agree with your "consistent" theory, anyways. The function > would be treating all arguments consistently: it's just that it'd get > a fresh copy of the default arguments each call.) A function that mutates its arguments should not be called with "fresh" arguments, implicitly or explicitly. If the purpose of the function is to modify its arguments, then doing so would throw away the effect of the function. If the purpose of the function is not to modify its arguments, then it shouldn't do so. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From eugine_kosenko at ukr.net Sun Dec 7 12:11:29 2003 From: eugine_kosenko at ukr.net (=?windows-1251?b?xeLj5e3o6SDK7vHl7eru?=) Date: Sun, 7 Dec 2003 19:11:29 +0200 Subject: Questions about datetime module Message-ID: <200312071854.14655.eugine_kosenko@ukr.net> Hi! I have several questions about the module datetime. The module has been added to Python 2.3. It seems that its interface is raw and dirty. Who is maintainer of the module? Who may answer for my questions and proposals? From wtrenker at shaw.ca Thu Dec 4 06:57:15 2003 From: wtrenker at shaw.ca (William Trenker) Date: Thu, 04 Dec 2003 11:57:15 +0000 Subject: weakrefs Message-ID: <20031204115715.52b58bdc.wtrenker@shaw.ca> I'm trying to get a better grasp on the difference between weakref.ref and weakref.proxy. I've read PEP 205 and goolged for additional description information on weakrefs, but I'm not finding much. The docs for the weakref module includes the line "XXX -- need to say more here!". Can anyone point me to tutorials or examples that illustrate where and why one would use a proxy instead of a ref? Thanks, Bill From hokiegal99 at hotmail.com Fri Dec 26 13:56:07 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 26 Dec 2003 10:56:07 -0800 Subject: Identifying File type by reading files Message-ID: <93f5c5e9.0312261056.22365aa7@posting.google.com> This is not really a Python-centric question, however, I am using Python to solve this problem (as of now) so I thought it appropiate to pose the question here. I have some functions that search for files that contain certian strings and if the files found to have these string do not already have a filename extension (such as '.doc' or '.xls') the function will append that to the files and rename them. So, if a file named 'report' was found to have the string 'Microsoft' and the string 'Word.Document.' (notice the '.' at the end of both words) and it does not already have an extension, then a rename would take place that would name the file 'report.doc' These functions work very well on most files (98% guessed correctly). However, I would like the functions to be more precise (100%). So, what should I look for in a file to determine whether or not it is a MS Word file or an Excel file or a PDF file, etc., etc.? Below is a list of some of the strings I use to ID files, but I can't help but wonder that there must be a more precise way of doing this. I know of the Unix 'file' command. It is not very useful for me as it doesn't distinguish between MS Office documents... all .xls, .docs, .ppts are MS documents to it. Are there certain sets of binary data that are unique to files that would be a better way of identifying them? For example, on the N line of a MS doc file begining at position X a binary string that is L digits in lentgh that begins with B and ends with E will *ALWAYS* be present... some one tell me that I'm not dreaming and that something like the above example exists??? A few of my string searches today: doc = string.find(file(os.path.join(root,fname), 'rb').read(), 'Word.Document.') xls = string.find(file(os.path.join(root,fname), 'rb').read(), 'Excel.Sheet.') pdf = string.find(file(os.path.join(root,fname), 'rb').read(), 'PDF-1.') jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') Any suggestions or information that better describes how to positively ID files w/o the possibiliy of mistake would be very helpful to me. As of now, some of my files, though not many (~ 2%) will be given the wrong extension, but the logic of the functions is such that they append any extension that probably applies to the file so at that point it is a simple process of elimination to determine which extension is actually the correct one. Normally, I never have more than 2 unique extensions attached to the same file. Thank you!!! From jzgoda at gazeta.usun.pl Mon Dec 22 15:07:27 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 22 Dec 2003 20:07:27 +0000 (UTC) Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: Steve Lamb pisze: >>> A function must return to have a return value. When does sys.exit() >>> return? > >> Something, that is of type NoneType. > > He didn't say what, he said when. Can anyone show a program that will > evaluate the return of sys.exit() and successfully parse it? =D sys.exit() doesn't return to caller -- but it doesn't mean it doesn't return a value. Does this value is discarded? Didn't have time (and need) to check out. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From buzzard at urubu.freeserve.co.uk Sat Dec 6 10:08:19 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 6 Dec 2003 15:08:19 -0000 Subject: Newbie question: Any way to improve this code? References: Message-ID: "Bengt Richter" wrote in message news:bqrf08$pke$0 at 216.39.172.122... > On Sat, 6 Dec 2003 00:06:16 -0000, "Duncan Smith" wrote: > [...] > > > >Or you could replace the whole thing with, > > > >try: > > f = open("firmas.txt",'r') > > texto = f.read() > > frases = texto.split('\n')[:-1] > > If you split on something, you don't have to eliminate it, > but you may split off a trailing null string, to satisfy the > logic that you should be able to join the list with the splitter and > get back your original. Splitlines does what you want: > > >>> 'abc\ndef\n'.split('\n') > ['abc', 'def', ''] > >>> 'abc\ndef\n'.splitlines() > ['abc', 'def'] > > >>> 'abc\ndef\n'.split('\n') > ['abc', 'def', ''] > >>> '\n'.join('abc\ndef\n'.split('\n')) > 'abc\ndef\n' > > But the result of splitlines gives you the same last line whether it ends with \n or not, > so you can't guarantee reconstruction: > > >>> '\n'.join('abc\ndef\n'.splitlines()) > 'abc\ndef' > > More: > >>> 'abc\ndef\n'.splitlines() > ['abc', 'def'] > >>> 'abc\ndef'.splitlines() > ['abc', 'def'] > >>> 'abc\ndef\n\n'.splitlines() > ['abc', 'def', ''] > >>> '\n'.splitlines() > [''] > >>> ''.splitlines() > [] > >>> 'a'.splitlines() > ['a'] > > >finally: > > f.close() > > > I think you forgot (oh, just realized the explanation for my amazement--you're not the other Duncan ;-) > (maybe you didn't forget) that if the open doesn't succeed in the above, > f will not be (re)bound, so f.close() will be problematical either way. > [snip] Yes, the other Duncan wouldn't have been so sloppy :-). Off to check whether I've done this in any of my 'real' code. And it was the frases = texto.split('\n')[:-1] that I was a bit unhappy about (once I'd posted). I feel a bit like a certain cartoon character, doh. Cheers Bengt. Duncan From mwh at python.net Mon Dec 1 14:04:38 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Dec 2003 19:04:38 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> <7x3cc4g56b.fsf@ruckus.brouhaha.com> Message-ID: JCM writes: > Michael Hudson wrote: > > Paul Rubin writes: > ... > >> Better to improve the compiler so that lambda makes good code. > > > Any ideas how to do that? > > http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=compiler+optimizations+lambda Very funny. Cheers, mwh -- I'm not particularly fond of singing GSTQ because she stands for some things I don't, but it's not really worth letting politics getting in the way of a good bawling. -- Dan Sheppard, ucam.chat From hans at zephyrfalcon.org Tue Dec 16 15:19:45 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 16 Dec 2003 15:19:45 -0500 Subject: range of characters? In-Reply-To: <5.2.1.1.0.20031216190836.0287b4c0@mail.comune.grosseto.it> References: <5.2.1.1.0.20031216190836.0287b4c0@mail.comune.grosseto.it> Message-ID: <3FDF68E1.6080807@zephyrfalcon.org> Bud P. Bruegger wrote: > I suppose there should be an elegant way of getting a range of > characters as in > > range('A', 'Z') > > Anyone knows how to do that? The best I thought of so far is something > like > [chr(i) for i in range(ord('A'), ord('Z')+1)], but that seems overly > verbose.. It's not built-in, but as you already demonstrated, it's easy to write your own code... >>> def chrange(char1, char2): ... return [chr(i) for i in range(ord(char1), ord(char2)+1)] ... >>> chrange('a', 'd') ['a', 'b', 'c', 'd'] >>> chrange('0', '9') ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From theller at python.net Mon Dec 29 17:15:47 2003 From: theller at python.net (Thomas Heller) Date: Mon, 29 Dec 2003 23:15:47 +0100 Subject: Building Py2Exe from source References: <153fa67.0312261752.44f3e977@posting.google.com> Message-ID: kylotan at hotmail.com (Kylotan) writes: > I need to be able to build Py2Exe from the source code as I am making > a Windows executable where I wish to preprocess the modules before > importing them. Hm, is this really a good idea? py2exe includes the .pyc (or .pyo) files, not the sources itself. Can't you preprocess them while building the exe? This way you would only have to hack python-code, not C code... > It looks like I can do this by adding lines to > Load_Module() in py2exe's start.c. However problem I have is that I > can't build Py2Exe using the instructions provided. Using the > designated command of "python setup.py install" I get this error: > > > Traceback (most recent call last): > File "setup.py", line 340, in ? > raise RuntimeError, msg > RuntimeError: PYWIN32DIR invalid. > > To build py2exe from source, you must either: > > - Download and build Mark Hammond's pywin32 source code > from http://starship.python.net/crew/mhammond, and set > the PYWIN32DIR variable to point to this directory > > - or change this setup script to not build run_svc target, > then you will not be able to build Windows NT services > with py2exe. > > > The main problem I encountered is that the 2nd option appears > misleading: removing run_svc from the list of targets does no good as > it still attempts to find some sort of "win32" directory before it > even gets that far. Or maybe I'm missing something. You *should* be able to hack the py2exe setup-script to do this, only removing run_svc from the list is certainly not enough. > Any help getting around this problem would be much appreciated. > > (Platform: Win98SE, Python 2.3.3.) Normally I would recommend the upcoming py2exe 0.5 for this, although it does not yet run on Win98, but I'm working on it. Thomas From glenfant at NOSPAM.bigfoot.com Tue Dec 16 06:07:05 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Tue, 16 Dec 2003 12:07:05 +0100 Subject: Spell checking and Python References: Message-ID: "Gilles Lenfant" a ?crit dans le message de news:brl2vb$1dj$1 at biggoron.nerim.net... > Hi pythonists, > > Any experience or pointer on using a spell checker (aspell, ispell ?) with a > Python app ? > > Many thanks by advance And many thanks to all afterwards... -- Gilles From antonmuhin at rambler.ru Wed Dec 24 11:39:01 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Wed, 24 Dec 2003 19:39:01 +0300 Subject: file opening and closing In-Reply-To: References: Message-ID: hokieghal99 wrote: > jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') > > Should this file be closed after reading? If so, how would one close it? > What's the downside to not closing it? > It would, then the file object gets destroyed (it method __del__ is called). However, as Python uses garbage collection, it can happen much later after you leave the function. There is mostly no downsides except for the cases when you try to read this file---it might not be flashed. regards, anton. From claird at lairds.com Mon Dec 15 10:11:37 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 15 Dec 2003 15:11:37 -0000 Subject: run Fortran from python References: <31e18870.0312142131.5cf4d329@posting.google.com> Message-ID: In article , Cameron Laird wrote: >In article <31e18870.0312142131.5cf4d329 at posting.google.com>, >SamX wrote: >>I know Tcl can run Fortran excutables. Can python do the same? >>Thank you > >Yes. > >Read up on such facilities as os.system and os.popen* >. . . . ... and the commands module, too. I need to change my habits to mention that one earlier. Sorry. -- Cameron Laird Business: http://www.Phaseit.net From quiteblack at yahoo.com Wed Dec 3 23:26:01 2003 From: quiteblack at yahoo.com (black) Date: Wed, 3 Dec 2003 20:26:01 -0800 (PST) Subject: customize Tkinter window button~ Message-ID: <20031204042601.31385.qmail@web21324.mail.yahoo.com> Howdy~ i am with Win2k and had built a window with Tkinter, it has 3 button on its topright corner as common window, but what i want is just one or tow of them. ie, is there any way i can configure the appearance of minimize, maximize and close button ? Regards~ --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: From francisgavila at yahoo.com Sun Dec 21 00:25:08 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 21 Dec 2003 00:25:08 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <279b566d.0312201935.38fb2156@posting.google.com> Message-ID: H.V wrote in message <279b566d.0312201935.38fb2156 at posting.google.com>... >Skip Montanaro wrote in message news:... > >Given all that Guido has said about functional programming, i'm >starting to wonder why he even made functions first class in python . He didn't make them first-class. He made everything an object, which has the consequence of making everything first-class. >I think no one even tries to understand the very concept of reducing >sequence to a single object using a rule . Sum is not a replacement of >this *concept*. >Just what is so wrong with having such a general tool available in a >programming language ? Doesn't it hurt to understand how to use it? No, but it was deemed to not be useful or idiomatic enough to warrant a builtin. The most common use-case (like, 99% most common) was simply summing up numbers, so we got a clear and conscise (and faster) builtin for that, and continue to do things idiomatically for the other use cases. I tend to agree with this. I've never found a use for reduce, even trying hard to think of where I might find a home for it in my code. All I've ever done with it is sum things. Even the Numeric people don't seem to use reduce, and it seems that they, of all people, would use it. It's simply, for whatever reason, not Pythonic. People naturally gravitate to alternate idioms to do things that reduce could do. Whether sum itself should be a builtin instead of in math is another issue altogether, but removing reduce from the builtins definately seems like a good decision to me. It may not be the right decision in some other language, but for whatever reason, Python doesn't use it much. >> John> The only explanation I can come up with for that level of >> John> absurdity is a desire to get rid of a feature, regardless of what >> John> it looks like. In other words, a jihad (holy war.) >> >If you look at some recent python-dev threads, you'll see comments >similar to "..this should get rid of most of the uses of lambdas, we >only have a few cases left .." . >I just don't understand this burning need of some to make python >conceptually poorer by eliminating the very idea of an anonymous >function. Python isn't really big on being conceptually pure, just on being clean, consistent, and easy-to-use and understand. I think the drive to get rid of usecases for lambdas is rather the opposite of what you seem to suspect: lambdas have so few uses as it is, that the Pythonic bent towards using fewer keywords/builtins/constructs has inclined people to see if those few use-cases are really unique enough to warrant the special syntax, or if it can somehow be subsumed and eliminated by other, more generally useful constructs. I will argue in the following that lambda simply isn't very useful *to* *Python.* >> No, it's simply not used very much. Python never has been a very strong >> functional language. It's always been a very strong object-oriented >> language. Use it the way it's strongest. >> >I think Guido should put his money where his mouth is and simply >eliminate functions as first class objects then ! It'd be a clear and >definitive way of saying that he doesn't like functional programming. >Object oriented purists probably wouldn't care since they probably >never use functions in that way. >It'd also be a great relief for all those who find the idea of >functions being passed around "hopelessly hard, too complex, byzantine >because i prefer 36 nested for loops with breaks, continues because >they're sooo much easier to understand, etc " . >Then python can be exactly like java at last ! You've got it backwards: functions are first-class in Python *because* everything in Python is an object. (Did you notice that functions have attributes, like objects?) It would be impossible to make them *not* first class! (Well, I guess not impossible, but it would require enormous kludgy hacking at core Python internals, and will inevitably result in bugs that would haunt Python for the rest of its days. Besides, it's inconsistent, and Python hates special-cases.) Anyway, the following is a fantastically common and powerful Python idiom that requires functions (well, really methods) to be first-class: class Dispatch(object): def do_this(self): pass def do_that(self): pass def dispatch(self, cmd): cmd = 'do_' + cmd if hasattr(self, cmd): getattr(self, cmd)() else: raise NotImplementedError Just because functions are first-class in Python doesn't mean we have to use them the way functional programmers use them. ;) >Think about it : As long as functions remain first class, some people >will program using a functional style (I surely intend to). The only >way to stop me from doing that is to remove functions from first class >status. If python ever gets very fast, people will reimplement things >like reduce in their own code or in a functional module. Anyone is free to program in a functional manner. In fact, Guido was quite amenable to the suggestion (I think by Hettinger) that there be a functional module in the standard library, similar to how we have the itertools module for generator fun. However, we will remain free to point out how there's usually a more straightforward Python idiom that does the same thing faster and more clearly. ;) We all hope Python calls get fast enough that functional programming in Python is not always slower, but, even if functional constructs were faster than standard idiom, Python would still stick to idiom, unless it needed to optimize. Of the functional functions, the only one that can occasionally beat a for-loop is map. Map is faster than anything else when the function used is a builtin. Remember that no matter how nice your lambda syntax gets, functional programming will probably always be slow in Python, simply because calling is slow in Python. Quite slow, in fact, and there's no obvious way around that. So Python generally prefers solutions that do not involve calling functions repeatedly, especially not functions as tiny as the ones you can comfortably fit into a lambda. Given this, you can see why anonymous functions don't make much sense for Python. Python would get rid of lambdas before it tried to "make them better", and no one is sure what that would entail. So just use 'def' and be happy. >> John> There is no replacement for lambda in sight, even though lambda is >> John> arguably the ***largest single*** one of the functional constructs >> John> that needs work, and has obviously needed work for a long time. >> >> Once again, you desire Python to be something it is not. If you want a >> strong functional language, program in Lisp or Haskell. > >Functions are supposedly first class, regular objects in python. Why >can't they be sometimes anonymous, just like tuples, lists and user >defined objects can ? One doesn't even need to consider other >languages to make this point. They can be anonymous, but to be small enough to be anonymous means being inefficient. Python simply does not go the way of small, throwaway functions, because there's no obvious way to use them without morphing Python into an entirely different "functional Python" language. And it will still be slower than using for-loops. >> >> John> The obvious replacement for lambda, which is some form of inline >> John> block, has not been seriously discussed, with proposed syntax and >> John> examples, anywhere I've seen it. Clearly, I'm not ominiscient, so >> John> that doesn't mean it hasn't, though. >> >> Anonymous blocks are not a replacement for lambdas, named functions are. > >Are there objects in python that must always have a name in any >context whatsoever ? It seems to me that all objects even modules can >be anonymous in at least some context. >Why are people even wondering about adding code blocks when making >real anonymous functions work will do ? What does it mean to make them "work"? If you have an anonymous function, where would you use it? map()? reduce()? But these are all slower and less-intuitive to Pythonistas than using for-loops and list comprehensions. So I would argue, there's no place to put anonymous functions to work in Python. That's why they never do any. (Work, that is.) If we make lambda some powerful construct that can have multi-line code, we'd just scratch our heads and say, "why didn't you just use a def"? If the function is long and involved enough, making it anonymous ceases to be of any importance. We'd end up just assigning the lambda to a name anyway, so what's the point? In other words, why is: def myname(): pass somehow intrinsically worse than: myname = lambda : pass supposing the latter were legal? If lambda were in every way the same as def, except that lambda is anonymous and def is not, and that lambda was legal in more places, then certainly the lambda is more general than def, and we should get rid of def, since Python does not like to have equivalent constructs. But the only thing the latter has over the former is that the latter can sometimes be used anonymously. "But," future Pythonistas will say, "we hardly ever use these anonymously! Why don't we invent a new syntax that allows us to define the name inline, like we see many other languages happily doing." And then they reinvent def, and then the upstart def-ites lobby Guido against the old-school lambda-ites, and lambda is overthrown "because def," (speaking from the future, now), "replaces the by-far-most common use case of lambda and does it more clearly, and the little niche use of lambda that's left is so rare as to not be worth it anyway. Guido Jr. the third, out." >I don't even get why some people who are against the anonymity of >lambdas seem quite ok with the anonymity of code blocks (given how >much more complex a code block can be compared to a lambda, how can >anonymity in their case be fine and not fine in the case of the much >simpler lambdas ?) . It's not the anonymity. It just so happens that in Python, anonymity makes no sense beyond very small functions placed into the call of these functional functions for which we always have an equivalent for-loop or list-comp construct that is faster and more Pythonic. There simply aren't many places in Python where a function takes a function as an argument. And those places where it does usually a for-loop is clearer and faster (as I've been saying over and over). In other cases, the function being passed is large enough that making it anonymous gains nothing--you'd just have to use a name to refer to it anyway, in order to make the code clear enough to read. Or is: map( lambda x: , range(10)) really clearer than just using def somewhere up above? It's not even clear that anything like Python syntax could support such a construct, and in anycase it is horribly unPythonic in its gnarish attempt to fit everything into one construct. So, I could turn the tables and say "what's this obsession with making things anonymous?" ;) The only utility of an anonymous function is the ability to define a function inline, within the calling construct, without polluting the namespace. I.e., a "throwaway function". Now, how often in Python do all those circumstance conjoin to make anonymous functions very useful? Not very, especially because, as we said, function calling is slow in Python. >Does anyone care about consistency in python ? For real, if you don't >want functional programming, make functions non first class and stop >claiming that they are objects just like every object. Umm...I don't understand. You can program functionally if you really want to, but I don't see why Python should feel obligated to support your habit, especially since it has its own way of doing things that is far more natural (and, um, faster, at least now) to the Pythonic frame of mind. Pythonic is a concept orthogonal to everything else, including "functional" and "OO". Python doesn't define itself by saying "I am OO, not functional." Rather, it examines itself, it peers into its own essence, and discovers, "hey, there isn't much functional in here, but there's an awful lot of OO." Python is something that simply *is*; definitions come later, and frankly will always be inaccurate and provisional. "Pythonic" is like a culture; undefinable and always evolving. It's a tautology that a language best supports those who like the way that language does things. So if you don't like the way Python does things, and you prefer it did things in a more functional way, perhaps you would be better supported by using a language that *did* do things in a more functional way? It won't make you a bad (or even a lesser) person if you don't use Python, but it might make you happier. I mean really, fighting about languages is like fighting about the relative moral worth of screwdrivers and hammers, and going from there to arguing about whether it's better to use screws or nails. -- Francis Avila From dw-google.com at botanicus.net Sun Dec 21 22:40:16 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 21 Dec 2003 19:40:16 -0800 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: <99dce321.0312211940.6bf462db@posting.google.com> "John Roth" wrote... > > I think if you can't understand why this option isn't provided for > > you, then you misunderstand some of the most fundamental Python > > concepts. import this. > I don't think I misunderstand it. As I've said several times in this > thread, I am not seriously advocating it for a number of reasons. > Please think before making a critique. That was an attempt to help unravel someone a little from the discussion, instead it has pulled me in somewhat. Look at the current subject line, look at the topic of your last post. Is there any point to this? You are engaged in free-for-all intellectual masterbation. Is there also any point to being so blunt? Please learn some manners before speaking in a public forum, you may let yourself down. David. From anton at vredegoor.doge.nl Sat Dec 20 09:09:15 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 20 Dec 2003 15:09:15 +0100 Subject: How to use a 5 or 6 bit integer in Python? References: <2u18uv8nosa821kptifdq1uei1t8koelsf@4ax.com> Message-ID: <3fe458d6$0$3319$3a628fcd@reader2.nntp.hccnet.nl> Glen Wheeler wrote: > Well, I'm a researcher for an Australian university (University of >Wollongong) and my current task is to enumerate every possible 6 digit >binary Gray code. It is possible to write a function that turns every integer into its "reflected" form so that the normal enumeration of the integers corresponds to a gray code (successors that differ only in one bit position) sequence. This can be done without enumerating them all. Here's some code from a book by Kreher and Stinson (Combinatorial ALgorithms) which I translated into Python from the pseudo-code in the book. I made some adaptations and came up with this: import sets def unrank(n,r): T,b1 = [],0 for i in range(n-1,-1,-1): b0 = r/(2**i) if b0 != b1: T.append(n-i-1) b1 = b0 r -= b0*2**i return T def rank(n,T): S = sets.Set(T) r,b = 0,0 for i in range(n-1,-1,-1): if n-i-1 in S: b = 1-b if b == 1: r += 2**i return r def reflect(n,r): S = sets.Set(unrank(n,r)) L = ["01"[i in S] for i in range(n)] return int("".join(L),2) def test(): n = 2**6 T = [None] for i in range(100): U = unrank(n,i) print i, reflect(n,i),U assert rank(n,U) == i assert len(sets.Set(T) ^ sets.Set(U)) == 1 T = U if __name__=='__main__': test() > I hope that's sated your curiosity for now :). If you'd like any >more information, or if anyone else would like to know anything about >this, then I'll be happy to correspond with them. I don't know how >on-topic it is for c.l.py. If it's interesting and provides an excuse for exercising our programming skills in our favorite language, it's on topic. It's even on topic if it's outrageously off-topic enough, so take your pick :-) I guess I must have missed something because if the problem's solution can be looked up in a book it probably is not what you are looking for. So why is it not enough to have an indexing function and why do you need to have all values literally? Anton From stephan.diehlNOSPAM at gmx.net Sun Dec 28 07:32:24 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Sun, 28 Dec 2003 13:32:24 +0100 Subject: Some optimization tale References: Message-ID: Terry Reedy wrote: [...] > > and easily messed up;-) If len(item) < len(prefix), item[i] throws > exception. For this approach to work, prefix should be set as shortest > string of m in preliminary loop. Also, you reslice m several times. Do > it once before outer loop. > >> It is just not nessesary to compare all strings in the list. > > Every string has to be compared to something at least once. You are right, of course. I have to admit that I've been too sloppy in my descriptions (and too sloppy in my thinking). > [...] >> Michael Dyck then pointed out that instead of using 'sort', 'min' and > 'max' >> should be used. While tests suggest that this is true, I have no idea why >> that should be, since finding a minimum or maximum uses some sorting > anyway > > No. max and min each do a linear scan. No sorting. But each does at > least as many character comparisons as modified f1 or f2. The speedup is > from looping and comparing in C, even though at least twice as many > compares are done. Makes sense. > >> You might have realized that the optimization so far was done one the > number >> of strings. There is still another dimension to optimize in and that is > the >> actual string comparing. >> Raymond Hettinger suggests using a binary search: > > Since this only affects the final comparison of min and max, and not the n > comparisons done to calculate each, the effect is minimal and constant, > independent of number of strings. > > Since this compares slices rather than chars in each loop, I wonder > whether > this is really faster than linear scan anyway. I would like to see timing > of f5 with min/max of f4 combined with linear scan of f3. (Basically, f3 > with sort removed and min/max added.) Since you changed two parts of f3 > to get f4, we cannot be sure that both changes are each an improvement > even though the combination of two is. > > def f5(seq): > if not seq: return '' > s1 = min(seq) > s2 = max(seq) > n = min(len(s1), len(s2)) > if not n: return '' # not required since s1[0:0] == '' > for i in xrange(n) : > if s1[i] != s2[i] : > return s1[0:i] > return s1[0:n] Your f5 function runs virtually at the same speed than Raymonds version. Even with growing string length, there is no dicernable difference. Cheers Stephan > > Terry J. Reedy From ny_r_marquez at yahoo.com Wed Dec 31 08:29:32 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 31 Dec 2003 05:29:32 -0800 Subject: Rekall Binary Message-ID: <8a27e309.0312310529.3c1f43a8@posting.google.com> So, Rekall is now GPLed. However, after a quick look at theKompany's website I see that they charge $69.95 for the download version. And looking at the rekallrevealed.org site I only see the source available for download. I am not complaining about it, but I see this as a good opportunity for someone to offer a $40.00 binary version available for download. And, then someone else might want to offer one for $20.00. And then ... Ok. This is silly. Why doesn't theKompany simply offer the binary version available for free and offer support contracts, as other apparently successful companies are doing? That would at least spead up Rekall's penetration in the market, and prevent the scenario I describe above. Sincerely wondering, -Ruben From ramen at lackingtalent.com Wed Dec 3 15:26:00 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 03 Dec 2003 20:26:00 -0000 Subject: Adding method to object References: <72krsvcpeur8hhu74s4bhlsq3bf60fu055@4ax.com> Message-ID: In article <72krsvcpeur8hhu74s4bhlsq3bf60fu055 at 4ax.com>, Gon?alo Rodrigues wrote: > If you want to leave out the f as arg (call it like an instance > method) then > >>>> import new >>>> help(new.instancemethod) > Help on class instancemethod in module __builtin__: > > class instancemethod(object) > | instancemethod(function, instance, class) > | > | Create an instance method object. > | > ... > > And > > new.instancemethod(incr, f, f.__class__) > > Should do the trick. I tried to bring this up several weeks ago but nobody replied, so I'm bringing it up again. I still see people recommending "new.instancemethod", yet "help(new)" says that the "new" module is deprecated. The seemingly identical "types.MethodType" ought to be its replacement, even though I think "new.instancemethod" is more clear. If you stringify types.MethodType, it says "". The help for instancemethod, above, says that instancemethod is in the __builtin__ module, but it is neither a builtin nor available in the __builtin__ module. This is confusing. Can we decide on a community standard for the appropriate way to create new instance methods, and resolve the documentation discrepancies? Thankya kindly, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From Yomanium at Yomanium.com Tue Dec 2 06:16:56 2003 From: Yomanium at Yomanium.com (Yomanium Yoth Taripoät II) Date: Tue, 2 Dec 2003 12:16:56 +0100 Subject: [pysnmp] Message-ID: HI, i cant connect to read my server. when i want to connect it (server.receive()) , i have an error "Address already in use". i have test with a free apps and no pb... thx in advance. F. From ville.spammehardvainio at spamtut.fi Fri Dec 19 20:39:11 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Dec 2003 03:39:11 +0200 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" writes: > a third is the ability to forget the empty parenthesis after > a function/method call that doesn't require parameters. Doesn't this suck big time? How can the interpreter tell whether you are trying to call a function or just want a reference to a callable object? > harder" syndrome. One of these days, someone is going > to start chewing up the user base, and for a while it looked > like Ruby might have been it. I dunno. It just doesn't seem likely that people who have "got" Python would switch to ruby. If the extra features of ruby were really worthwhile, they would be added to Python (which has happened before). I trust the Py development team to do the right decision at all times (apart from ternary operator, obviously ;-). -- Ville Vainio http://www.students.tut.fi/~vainio24 From 9974331 at cvm.qc.ca Tue Dec 30 11:51:58 2003 From: 9974331 at cvm.qc.ca (Askari) Date: 30 Dec 2003 08:51:58 -0800 Subject: Try except - bug? Message-ID: <104c369a.0312300851.4f23759e@posting.google.com> Hi, I have a problem with try except : example ============ try: print "bou!" raise "ha!" except: try: fileDest.close() except NameError: print "error" except: import traceback traceback.print_exc(file=sys.stdout) ============ If I run this example alone, I have no problem : result ============ bou! error ============ but I can't understand why doesn't work in my program : http://www.cvm.qc.ca/9974331/Temp/crypte.py (too long for a copy and paste) (note : it's at line 353) (note : the language of this program is in french, sorry) when I run my program, I have this error : ============ Traceback (most recent call last): File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", line 355, in crypte fileDest.close() NameError: global name 'fileDest' is not defined ============ but I know that 'fileDest' is not always defined but I put this line in a try-except!? :-( :-S Askari From davecook at nowhere.net Fri Dec 5 18:45:04 2003 From: davecook at nowhere.net (David M. Cook) Date: Fri, 05 Dec 2003 23:45:04 GMT Subject: Newbie question: Any way to improve this code? References: Message-ID: In article , Gustavo Campanelli wrote: > import string > f = open("firmas.txt",'r') # open the file > texto = f.read () > n = range (len (texto)) > frases = [0] > frase ="" > cant = 0 > for a in n: > if texto [a] != "\n": > frase = frase + (texto [a]) > else: > if cant == 0: > frases [0] = frase > else: > frases.append (1) > frases [cant] = frase > cant +=1 > frase = "" f = open("firmas.txt",'r') # open the file frases = [] for line in f.readlines(): frases.append(line[:-1]) line[:-1] is all but the last element of line. or even frases = map(str.rstrip, f.readlines()) although that may strip more of the end than you want. Dave Cook From andrel at decillion.net Wed Dec 10 04:00:47 2003 From: andrel at decillion.net (Andre Louw) Date: Wed, 10 Dec 2003 11:00:47 +0200 Subject: Test Message-ID: a Test post From steve at ferg.org Mon Dec 29 09:03:39 2003 From: steve at ferg.org (Stephen Ferg) Date: 29 Dec 2003 06:03:39 -0800 Subject: indendation question References: Message-ID: The official recommendation is to use 4 spaces, but... ... Using tabs seems much more natural to me. One level of indentation == one tab character. What could be more natural? So I always use tabs, and that's what I recommend. From sam at samuel-kleiners-computer.local Sat Dec 6 23:05:00 2003 From: sam at samuel-kleiners-computer.local (Samuel Kleiner) Date: Sat, 06 Dec 2003 22:05:00 -0600 Subject: New inited instance of class? References: Message-ID: Francis Avila wrote: > > Samuel Kleiner wrote in message ... >>Is there a builtin way of making making another instance of your own >>class? > > You mean, from the inside (from one of the instance methods of the class)? Yes. > def new(self, *args, **kargs): > return self.__class__(*args, **kargs) This works. Thanks. >>I really expected type(self)(*args, **keywords) to work this way. > > Works for me. What traceback does it give you? Not for me. I really want to call it as the function itself, and type(self)(argument1,argument2,argument3) fails with Traceback (most recent call last): File "", line 139, in ? File "", line 78, in __add__ TypeError: instance() takes at most 2 arguments (3 given) whereas self.__class__(argument1,argument2,argument3) does not >>Currently i'm doing this: >> >>[my code] > That's ugly. Yes. -- On an encouraging note, however, I found that throughout the source code, extremely conservative coding practices and good error checking everywhere means that our software does not crash when handling IPv6 addresses. --Joe Loughry, Lockheed Martin Space and Strategic Missiles, RADIANT MERCURY From aahz at pythoncraft.com Sun Dec 21 21:35:16 2003 From: aahz at pythoncraft.com (Aahz) Date: Sun, 21 Dec 2003 21:35:16 -0500 Subject: BayPIGgies Jan 8: Python Threads Message-ID: <20031222023516.GA19861@panix.com> The next BayPIGgies meeting will be Thursday, January 8, 2004, 7:30pm Aahz will be presenting a talk on Python threads. BayPIGgies meetings are held at Stanford, California. For more information, see http://www.baypiggies.net/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From kyo at netease.com Thu Dec 4 23:32:58 2003 From: kyo at netease.com (kyo) Date: 4 Dec 2003 20:32:58 -0800 Subject: why embed demo crash on freebsd4.8? Message-ID: <2f9c31f.0312042032.7e001f4a@posting.google.com> When I try to run the demo under 'Demo/embed/' , It crash, It's something wrong about my Make step? ========================================== ========== xy2.163.com embed$uname -a FreeBSD xy2.163.com 4.8-RELEASE-p5 FreeBSD 4.8- RELEASE-p5 #0: Thu Sep 25 11:42:40 CST 2003 root at xy2.163.com:/usr/home/root/src/sys/compile/DH2G AME_KERNEL i386 ========================================== =========== xy2.163.com embed$python Python 2.3.2 (#1, Dec 4 2003, 13:18:10) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import distutils.sysconfig >>> distutils.sysconfig.get_config_var('LINKFORSHARED') '-Wl,--export-dynamic' >>> ========================================== ========== xy2.163.com embed$gmake demo gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -fno-strict-aliasing -I../../Include -I../.. -c - o demo.o demo.c gcc -Wl,--export-dynamic demo.o ../../libpython2.3.a - lreadline -ltermcap -pthread -lutil -lc -lm -o demo ../../libpython2.3.a(posixmodule.o): In function `posix_tmpnam': /home/kyo/work/Python-2.3.2/./Modules/posixmodule.c (.text+0x3c8b): warning: tmpnam() possibly used unsafely; consider using mkstemp() ../../libpython2.3.a(posixmodule.o): In function `posix_tempnam': /home/kyo/work/Python-2.3.2/./Modules/posixmodule.c (.text+0x3bee): warning: tempnam() possibly used unsafely; consider using mkstemp() /usr/lib/libc_r.so: WARNING! setkey(3) not present in the system! /usr/lib/libc_r.so: warning: this program uses gets(), which is unsafe. /usr/lib/libc_r.so: warning: mktemp() possibly used unsafely; consider using mkstemp() /usr/lib/libc_r.so: WARNING! des_setkey(3) not present in the system! /usr/lib/libc_r.so: WARNING! encrypt(3) not present in the system! /usr/lib/libc_r.so: warning: this program uses f_prealloc (), which is not recommended. /usr/lib/libc_r.so: WARNING! des_cipher(3) not present in the system! xy2.163.com embed$./demo Hello, brave new world ('__builtin__', '__main__', '_codecs', '_sre', '_symtable', 'er rno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys ', 'thread', 'xxsubtype', 'zipimport') ['copy_reg', '__main__', 'cjkcodecs.aliases', 'site', '__builti n__', 'encodings', 'encodings.encodings', 'posixpath', 'enc odings.codecs', 'cjkcodecs', 'os.path', '_codecs', 'encodin gs.exceptions', 'stat', 'zipimport', 'warnings', 'encodings.ty pes', 'UserDict', 'sys', 'cjkcodecs.encodings', 'codecs', 'ty pes', 'xyzzy', 'signal', 'linecache', 'posix', 'encodings.aliase s', 'exceptions', 'encodings.iso8859_1', 'os'] /usr/home/kyo/work/Python-2.3.2/Demo/embed/demo ['./demo'] Goodbye, cruel world Segmentation fault (core dumped) ========================================== =========== xy2.163.com embed$gdb demo demo.core GNU gdb 4.18 (FreeBSD) Copyright 1998 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-unknown- freebsd"...Deprecated bfd_read called at /usr/home/root/src/gnu/usr.bin/binutils/gdb/../../../../c ontrib/gdb/gdb/dbxread.c line 2627 in elfstab_build_psymtabs Deprecated bfd_read called at /usr/home/root/src/gnu/usr.bin/binutils/gdb/../../../../c ontrib/gdb/gdb/dbxread.c line 933 in fill_symbuf Core was generated by `demo'. Program terminated with signal 11, Segmentation fault. Reading symbols from /usr/lib/libreadline.so.4...done. Reading symbols from /usr/lib/libncurses.so.5...done. Reading symbols from /usr/lib/libutil.so.3...done. Reading symbols from /usr/lib/libc.so.4...done. Reading symbols from /usr/lib/libm.so.2...done. Reading symbols from /usr/lib/libc_r.so.4...done. Reading symbols from /usr/libexec/ld-elf.so.1...done. #0 0x481fcaa8 in .cerror () from /usr/lib/libc.so.4 (gdb) bt #0 0x481fcaa8 in .cerror () from /usr/lib/libc.so.4 #1 0x4828f927 in _exit () from /usr/lib/libc_r.so.4 #2 0x481fc9a7 in exit () from /usr/lib/libc.so.4 #3 0x80a4b5c in Py_FdIsInteractive (fp=0x0, filename=0xbfbffb08 "瘥靠") at Python/pythonrun.c:1547 #4 0x8053d67 in main () #5 0x8053bf6 in _start () (gdb) ========================================== From jroznfgre at jngpugbjreQBGbet.cy Fri Dec 19 04:06:09 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Fri, 19 Dec 2003 10:06:09 +0100 Subject: pymozilla ([Python-Dev] RELEASED Python 2.3.3 (release candidate 1) - custom Py_Initialize()) References: Message-ID: On Fri, 19 Dec 2003 04:30:53 +0100, "Wiktor Sadowski" wrote: >The main problem was to have it run from CD (client requirement) without >installing anything (Mozilla/Python) I had the same problem. I solved it using Webware and SQLite. -- JZ From tjreedy at udel.edu Wed Dec 17 22:55:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Dec 2003 22:55:11 -0500 Subject: tuples and cartesian coordinates References: Message-ID: "Gerrit Holl" wrote in message news:mailman.262.1071692390.9307.python-list at python.org... > Shouldn't coordinates be mutable? Coordinates no, positions possibly yes, as long as you avoid the mutiple reference trap others have described. My philosophy on the tuple vs. list debate is that people should use what works for their particular application. TJR From shoot at the.moon Wed Dec 17 18:58:24 2003 From: shoot at the.moon (Steve Horsley) Date: Wed, 17 Dec 2003 23:58:24 +0000 Subject: tuples and cartesian coordinates In-Reply-To: References: Message-ID: Gerrit Holl wrote: > Hi, > > the FAQ says: > > >>For example, a Cartesian coordinate is appropriately represented as a >>tuple of two or three numbers. > > > I find it strange to use tuples for a coordinate. After all, a > coordinate represents a position of an object. Suppose I have a game > where the player has a position: isn't it stupid to use tuples rather > than lists or another type (maybe complex numbers?), because I want to > be able to change the position? > > Shouldn't coordinates be mutable? > > yours, > Gerrit. > Depends. Does it make logical sense for the coordinate to be mutable in the context of your app? If an object is returning an instrumentation value, as in positionNow = spaceship.getPosition() then it does make sense to be mutable. Of course the spaceship itself may well keep a mutable position internally that it changes in response to setThrusters(fullSpeedAhead) Steve From hokiegal99 at hotmail.com Sun Dec 21 18:45:31 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 21 Dec 2003 15:45:31 -0800 Subject: Count Files in a Directory Message-ID: <93f5c5e9.0312211545.363b91a6@posting.google.com> I'm trying to count the number of files within a directory, but I don't really understand how to go about it. This code: for root, dirs, files in os.walk(path): for fname in files: x = str.count(fname) print x Produces this error: TypeError: count() takes at least 1 argument (0 given) for root, dirs, files in os.walk(path): for fname in files: x = list.count(files) print x TypeError: count() takes exactly one argument (0 given) Also wondered why the inconsistency in error messages (numeric 1 vs. one)??? Using 2.3.0 Thanks!!! From klappnase at web.de Wed Dec 10 12:19:55 2003 From: klappnase at web.de (klappnase) Date: 10 Dec 2003 09:19:55 -0800 Subject: What are the errors in a simpliest Tix application? References: Message-ID: ??????? ??????? wrote in message news:... > As the Python Library manual says, the only thing I need to use Tix is to > replace Tkinter in the last program to Tk: > > import Tix > > root = Tix.Tk() > widget = Tix.Button(root) > > However, I have got the next exception tracelist: > > Traceback (most recent call last): > File "tix.py", line 4, in ? > widget = Tix.Button(root) > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1906, in __init__ > Widget.__init__(self, master, 'button', cnf, kw) > File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1835, in __init__ > self.tk.call( > _tkinter.TclError: expected integer but got "-" > Does the manual say so? I never heard about this, I always use something like: import Tkinter import Tix root = Tix.Tk() button = Tkinter.Button(root) etc... This way I never had problems. Cheers Michael From jepler at unpythonic.net Tue Dec 30 16:54:33 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Dec 2003 15:54:33 -0600 Subject: 'inverting' a dict In-Reply-To: References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: <20031230215433.GA18443@unpythonic.net> Does this listcomp give the right result? dict([(v, k) for k, vs in original.iteritems() for v in vs]) Jeff From busyman at t-online.de Fri Dec 19 08:41:35 2003 From: busyman at t-online.de (Martin Michel) Date: Fri, 19 Dec 2003 14:41:35 +0100 Subject: Save the pythons. References: Message-ID: Save the Pythons. Give 'em Rubies, Coffee and Camel :) From joconnor at cybermesa.com Tue Dec 2 12:55:53 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 02 Dec 2003 10:55:53 -0700 Subject: python's threading has no "interrupt"? In-Reply-To: <9btu91-s04.ln1@beastie.ix.netcom.com> References: <9btu91-s04.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber wrote: > There's the first point of departure: Python threads (as long as you >aren't in a C language number crunching extension) are preemptive >scheduled, on something like a 10-20 byte-code interval. Cooperative >basically means /you/ had to handle the scheduling of threads; in >Python you don't, it happens automatically. > > I stand corrected. The following code behaves exactly like I would want it to rather than how I feared it would. Is this a change? I don't seem to recall the same result when I tried it initially with Python 1.5.2.... -------- from threading import Thread def test1(): while True: print "test1" def test2(): while True: print "test2" t1 = Thread (target=test1) t2= Thread (target=test2) print "starting" t1.start() t2.start() print "started" while True: print "main" --------------- From mk at net.mail.penguinista Mon Dec 22 06:42:46 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Mon, 22 Dec 2003 12:42:46 +0100 Subject: test if a file is locked? References: Message-ID: <3fe6d8b6@news.mt.net.mk> > I can lock a file using the following snippet: > > --- > import fcntl > > f=open('flock.txt','w') > fcntl.lockf(f.fileno(),fcntl.LOCK_EX) > --- > > If some other script tries to open 'flock.txt', it'll wait until the > file is unlocked/closed. This is not true on my system (Linux-2.4.23/glibc-2.3.2), after locking the file Ican still open it with another script or program (like "cat"). The other script blocks only when I try to lock the file again. > My question is, I'd like to tell a script to quit *immediately* if it > cannot open the file, or, if it knows the file is locked. try this: fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB) it will throw an exception if the file is locked: IOError: [Errno 11] Resource temporarily unavailable -- ?????? (jabberID:damjan at bagra.net.mk) Intel: where Quality is job number 0.9998782345! From km at mrna.tn.nic.in Thu Dec 25 23:49:38 2003 From: km at mrna.tn.nic.in (km) Date: Fri, 26 Dec 2003 10:19:38 +0530 Subject: class creation Message-ID: <20031226044938.GA24099@mrna.tn.nic.in> Hi all, If i create a class "REX" and want to import it and test its implementation in a python script what should be the file name of the class file be ? kindly enlighten, thanks, KM From bkelley at wi.mit.edu Thu Dec 11 14:47:31 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 11 Dec 2003 14:47:31 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: <3FD8C13F.6BC2B2DD@engcorp.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> <3FD8C13F.6BC2B2DD@engcorp.com> Message-ID: <3fd8c97b$0$574$b45e6eb0@senator-bedfellow.mit.edu> Peter Hansen wrote: > Probably the reason the text widget doesn't already do those things is > that nobody has taken the time to make it happen *and* release the changes > back to the project. Is Robin Dunn supposed to think of and write all > these things himself, just for your benefit? That's a bit rough considering I give back quite a bit to the wxPython community. Most of the useful things that I have written I have given back to wxPython. A short resume includes PyGTK/Glade tutorial and Dr. Dobbs article, WizardTransitionPages, grid_MegaExample, etc. Some made it into the distribution, some didn't. I don't even know if this is a sane interface. When I said "why isn't there a .write(...) method for these widgets? Why can't I use a text widget like" that wasn't a specious Robin should do this for me question. It really was more like, is this a way a text widget should behave? I also wan't just talking about wxPython, non-pythonic behavior exists across the board wxPython/Tk/Qt/Gtk. Is it worth the effort to make a text widget behave like a file stream, I'm not sure. I'm certainly not going to force this down someone's throat, but when I'm happy with it I'll release it. Andrew Dalke wrote a good piece in the Dr. Dobb's 25th anniversary article about the pythonification of C toolkits that I think is pretty good reference for these types of discussions. Brian From dw-google.com at botanicus.net Wed Dec 10 06:55:11 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 10 Dec 2003 03:55:11 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: <99dce321.0312100355.3e567ffa@posting.google.com> "Mike Rovner" wrote... > It reminds me of Microsoft's promise to combine RDBMS and file system in a > new Longhorn OS. Several years ago that idea was highly popular but nothing > came out. > That approach may be very interesting to allow user to use some plug-ins for > the file system > (access, security, notification, etc.). Quite a few people have attempted work in this area, but as with Microsoft, the plan to combine a traditional database and a traditional filesystem never seems to come to fruition. If you are interested in this sort of stuff, the only really serious attempt I have seen in the recent years is the work of Hans Reiser, of reiserfs fame. Take a read through the pages at: http://www.namesys.com/ And possibly pick the thread up over on one of the database or filesystem news groups. ;) David. From andreif at mail.dntis.ro Sun Dec 21 04:52:37 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 21 Dec 2003 01:52:37 -0800 Subject: pysql lite transactions question Message-ID: <21bb8d55.0312210152.2b1957aa@posting.google.com> Hi, Could anyone shed some light on transactions using pysqlite when autocommit is off ? I am using Python 2.3 with latest pysqlite and after I do a m_connection = sqlite.connect(name, autocommit=0) and m_cursor = self.m_connection.cursor() and then looks like it starts a transaction automaticaly, because if I issue a m_cursor.execute('BEGIN TRANSACTION') it says that nested transactions are not permitted. But : if I issue an 'END TRANSACTION' and then a 'BEGIN TRANSACTION' and do the usual db operations and in the end I do a 'END TRANSACTION' I get this : Exception _sqlite.DatabaseError: 'cannot rollback - no transaction is active' in > ignored The program works as expected, i.e. seems like this exception is ignored, but I must do something wrong or not properly as this exception appear. I also tried to send a 'COMMIT' after my 'BEGIN TRANSACTION' and I get _sqlite.DatabaseError: cannot commit - no transaction is active which does strike me as odd. My reasons of trying to use transactions is that it seems to make sense in what I do, i.e. I try to populate a database and if I get an error halfway I want to cancel the whole chain of operations. Plus I noticed the speed is much greater if I put autocommit to off. Any ideas ? Thanks in Advance, Andrei From bokr at oz.net Mon Dec 1 11:29:08 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Dec 2003 16:29:08 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: On Mon, 01 Dec 2003 10:11:16 GMT, "Raymond Hettinger" wrote: >[Peter Otten] >> > extract[1] >> > extract["key"] > >[Robert Brewer] >> I'm having a hard time seeing the use cases, given that I find >> most of them more readable if done with list comprehensions >> or good ol' for loops. > >Peter's post focused on implementation instead of the context. > >For Py2.4, the list.sort() will have an optional key argument that encapsulates >the decorate/sort/undercorate pattern. For example, here is the new fastest way >to have a case insensitive sort leaving the original case intact: > >>>> words = 'The quick BROWN fox JumPed OVER the LAzy dog'.split() >>>> words.sort(key=str.lower) Please can we have a name that better expresses the functionality? E.g., 'keyfunc', or 'xform' or something that says the method is expecting a function that will be called with the sorting argument to produce the value used in sorting? "key=" doesn't do it IMO. In fact, 'key' could well be used to *select* a key from indexable objectss being sorted. E.g., key=1 could provide an efficient way to do the typical value-based sort on dictionary 2-tuple items. Regards, Bengt Richter From jeremy_kauffman at hotmail.com Wed Dec 24 08:57:26 2003 From: jeremy_kauffman at hotmail.com (Jeremy Kauffman) Date: 24 Dec 2003 05:57:26 -0800 Subject: replace line #1 with "newline\n" in text file References: <3fe955b8.0@news1.mweb.co.za> Message-ID: <97245b7.0312240557.12f64b50@posting.google.com> "bmgz" wrote in message news:<3fe955b8.0 at news1.mweb.co.za>... > Hiya, > I am trying to replace the first line of a config file.. with a new string > been googlizing and reading the python manual.. but can't find what I need.. > it's all rubbish about bits and bytes etc.. something like: lines = open('config.txt', 'r').readlines() lines[0] = 'newline\n' open('newconfig.txt', 'w').writelines(lines) From jjl at pobox.com Sun Dec 28 20:55:47 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Dec 2003 01:55:47 +0000 Subject: argument list References: Message-ID: <87zndcmlp8.fsf@pobox.com> "Phil Hornby" writes: > I am working on a solution embedding Python in an app that will looks for > specific string combination within the function names to determine if a > handler for an event exists; I have been able to extract the function names > and find all of the 'fields' of interest. What I am concerned about, > however, is that they could have the wrong argument profile, as specific > handlers will have specific function arguments - can I find out what > arguments a specific functions takes from the C-API? As I don't seem to be > able to find anything...but I could be just being blind... [...] First, maybe what you really want is just the equivalent of func(*args, **kwds)? (don't remember off the top of my head how to do that) Or maybe what you're missing is that you can just use different method naming conventions for different kinds of handler? John From jepler at unpythonic.net Tue Dec 30 17:08:10 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Dec 2003 16:08:10 -0600 Subject: Coding an extendable class In-Reply-To: References: Message-ID: <20031230220810.GB18443@unpythonic.net> Python sometimes uses "mixin" classes -- see the SocketServer module for one example in a core module. So main.Graph would be the real graph class, and graphtools.hamilton.HamiltonMixin would be one mixin: class MyGraph(main.Graph, hamilton.HamiltonMixin): pass You could use new.classobj to create a class object with a given list of mixins at runtime (untested): # In Main _graph_classes = [] def add_mixin(m): _graph_classes.append(m) global Graph Graph = new.classobj("Graph", _graph_classes, {}) add_mixin(main._Graph) # In each module that defines a new mixin class HamiltonianMixin: pass main.add_mixin(HamiltonianMixin) however, having the exact nature of main.Graph depend on what other modules have been imported is not what most Python users would expect. I prefer the solution of having the user list mixins by creating a "personalized" graph class. Jeff From python-url at phaseit.net Mon Dec 15 12:22:49 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Mon, 15 Dec 2003 17:22:49 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 15) Message-ID: QOTW (in the OS agnostic category): "There is a (very popular) Python package out there which exposes the win32 api. I'm not sure what it's called. (win32api? pythonwin? win32all?)" -- Francis Avila QOTW (in the popular vote category): "So far, python has been the easiest language to learn I've ever come across. I tried learning perl, and it was a disaster.... Too convoluted. Python is a breath of fresh air. Also, the docs and support here is excellent. :-) My thanks to all the volunteers who put in time to build python." -- Kamus of Kadizhar Zunbeltz Izaola wants to know more about preferred usage of getters and setters in python. http://groups.google.com/groups?threadm=m1oeuhqd7k.fsf at lcpxdf.wm.lc.ehu.es Aaron Watters announces xsdb, the eXtremely Simple Database, written in python and featuring an optional server mode built on stackless. http://groups.google.com/groups?threadm=mailman.25.1071054806.9307.python-list at python.org Jan Decaluwe finds help on introspection of cells, an implementation detail of nested scopes. http://groups.google.com/groups?threadm=3FD5FD4A.9060406 at jandecaluwe.com M.-A. Lemburg announces the release of eGenix mxODBC Zope Database Adapter Version 1.0.7, which is available for Zope 2.3 through 2.7 and allows you to easily connect your Zope installation to just about any database backend. http://groups.google.com/groups?selm=mailman.88.1071177569.9307.python-list at python.org Christopher Koppler finds out how to send mouse clicks to a windows gui application. http://groups.google.com/groups?threadm=d28ac2c5.0312120419.264f8213 at posting.google.com Todd Miller announces the release of numarray-0.8, an array processing package designed to efficiently manipulate large multi-dimensional arrays. http://groups.google.com/groups?selm=mailman.114.1071267670.9307.python-list at python.org Michael Stroeder releases python-ldap-2.0.0pre18, an object-oriented API to access LDAP directory servers from Python programs. http://groups.google.com/groups?selm=mailman.1071001802.31728.clpa-moderators at python.org Christian Tismer announces that Stackless 3.0 can now pickle generators... http://groups.google.com/groups?threadm=mailman.95.1071200369.9307.python-list at python.org ...and shows a way to use Stackless with Zope in a quick hack example of a long-running Python method which "prints" lines to the browser. http://groups.google.com/groups?threadm=mailman.52.1071114650.9307.python-list at python.org Itamar Shtull-Trauring announces the release of Twisted 1.1.1, an event-driven networking framework for server and client applications. http://groups.google.com/groups?selm=mailman.41.1071081238.9307.python-list at python.org David M. Wilson gets some links to better understanding and working with __metaclass__. http://groups.google.com/groups?threadm=99dce321.0312081149.2a32575d at posting.google.com Paul Rubin asks "What GUI toolkit looks the best?" Swap in OS or editor for GUI and you're properly forewarned. http://groups.google.com/groups?threadm=7xekvby0xr.fsf_-_ at ruckus.brouhaha.com Allen questions python's future, believing it to be incompatible with .net. http://groups.google.com/groups?threadm031207112217.14343.00000306%40mb-m14.aol.com Gustavo Niemeyer announces lunatic-python 0.1, a two-way bridge between Python and Lua, allowing these languages to intercommunicate. http://groups.google.com/groups?threadm=mailman.118.1071295637.9307.python-list at python.org Fredrik Lundh announces the release of WCK for Tkinter 1.0, an extension API that allows you to implement custom widgets in pure Python. http://groups.google.com/groups?selm=mailman.1071238623.31067.clpa-moderators at python.org David McNab announces pythonfs - a framework which allows mountable linux filesystems to be implemented in pure python and available to linux users. http://groups.google.com/groups?threadm=mailman.216.1070885363.16879.python-list at python.org Ruben Marquez is pleased to find demos in win32all allowing Python to operate as a nearly complete shell extension, and to interact with the shell interfaces. http://groups.google.com/groups?threadm=8a27e309.0312081137.18c2810b at posting.google.com Wilfredo Sanchez gets a tip on deleting a message with imaplib. http://groups.google.com/groups?threadm=wsanchez-7FAB67.14343408122003 at news.apple.com Manage Linux file systems with a high-level Pythonic programmatic interface. http://groups.google.com/groups?selm=mailman.216.1070885363.16879.python-list%40python.org Jim Hugunin appears to be on the verge of another miracle, following up his Jython masterpiece with a sophisticated implementation of Python for the .NET CLR. http://www.google.com/groups?selm=87n0a1uat3.fsf%40pobox.com ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From try_vanevery_at_mycompanyname at yahoo.com Wed Dec 24 16:49:20 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Wed, 24 Dec 2003 13:49:20 -0800 Subject: ProtoCiv: porting Freeciv to Python Message-ID: I am - *TENTATIVELY* - (operative word) undertaking the project of porting the GPL open source game "Freeciv" to Python. Freeciv is, in essence, an almost straight clone of Sid Meier's Civilization II, albeit with better cross-platform and multiplayer support. www.freeciv.org I'm undertaking the project independent of the current Freeciv project managers. They are not a variable as to how the project will proceed. Our goals are too disparate for us to attempt to coordinate with each other. I'll consider offers of assistance, although first I must do a lot of work on my own. Still, if my goals strongly ring a chord with your own goals, let's talk. (And conversely, if you want something totally different, let's not waste the breath. ;-) Here are my goals: - the working title of the project is "ProtoCiv," but I'm amenable to better names. "Better," in my parlance, means more marketable and more likely to get people to play / develop / notice / care about / remember the project. - the primary language of ProtoCiv development will be Python. Freeciv is a C codebase, so a lot of migration work is needed. Python will "own" the app, I will be starting at main() and digging as far down as I can easily go. Once the digging is no longer easy, i.e. once I've hit "bad dirt," an initial Python extension interface will be established. Over time, with the help of others, the C code will be whittled away to bare performance essentials. - new coding in C will be actively discouraged. - no clones of commercial games such as Civ II will be supported. One of the first things I'll do in the ProtoCiv project is remove the current Civ II support, and change the game significantly so that it is no longer almost just like Civ II. I find straight or near-straight clones of commercial products to be an offense to the game industry. - "knockoffs" are ok. I define a "knockoff" as something very similar to another game, but still a distinctly different game. For instance, Call To Power II is a knockoff of Civ II, not a clone. - the main purpose of the ProtoCiv project is to encourage rapid prototyping by 4X TBS Game Designers. This is against the desires and energies of the current Freeciv project management, and is my primary reason for going my own way with this. - an \alpha, \beta, and \release directory infrastructure will be established in all distributions so that it's easy for Game Designers to add features and get them distributed for in-the-field testing. Users will voluntarily enable features. In ProtoCiv, there will be no Gatekeepers deciding what game designs may or may not be tried. Anyone will be able to submit \alpha features, although of course they'll be turned off by default and the game developer will have to jazz people up about turning them on. \beta and \release will be more stringently controlled for purposes of making sure the code works, not for purposes of evaluating whether a given game feature is good or not. - ProtoCiv emphasizes Game Designer flexibility, not techie flexibility / libido for its own sake. Gatekeepering to keep the system architecture working properly will be more "traditional." - I am a Windows-centric developer. Currently I'm working on the subgoal of eliminating Freeciv dependencies upon crufty Cygwin and/or MinGW tools. I will be maintaining Visual Studio .NET 2003 solution files. I am amenable to cross-platform support, given that Freeciv already has a lot of cross-platform client code, but Windows development will not be Cygwin or MinGW dependent. - I may integrate .NET support later on, using Python for .NET. - This is a 4X TBS genre project. It is not a RTS, RPG, FPS, or other kind of genre project. Project management will not become confused about the basic nature of 4X TBS. Creating an engine for any game is not a goal. Creating an easily modified 4X TBS engine, starting from a Civ-style codebase, is the goal. - If project components could in fact be used independently of genre, i.e. world map generators, their modularity will be considered. - I'm a commercial developer, not a hobbyist. Project participants are free to treat the project "as a hobby," but when hobbyist and commercial development cultures collide, commercial culture will win. For instance, Commercial developers don't think all tools have to be free, nor does all software have to be open source. Commercial developers do not say "let's wait a long time before trying X." Commercial developers don't badger people about giving away tons of work as some kind of moral virtue. Commercial developers consider time to be money, and assess risk before spending their money. - FWIW I'm a proponent of MIT / BSD style "do whatever you want with it" open source licenses, not GPL. I believe if you're going to give something away, you should give it away completely. And if you don't want to do that, don't give it away. I don't want GPL licenses interfering in my business decisions, what I choose to make open source or proprietary. However, Freeciv is a GPL codebase, so if I want to use it I'm stuck with it. I will be looking for ways to put independent project components under MIT / BSD license. - Because of the GPL license, no commercial gain of any kind is believed possible with this project. My main motives are: 1) get Game Designers to advance the Art and Science of 4X TBS game design 2) prototype game features that I might try in Ocean Mars someday 3) find out what level of 4X TBS modding is or isn't possible - to accomplish these purposes, the project will be actively marketed. i.e. Get articles about it on Gamasutra, Gamedev.net, gamer websites, etc. when it's at an appropriate stage. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Taking risk where others will not. From fumanchu at amor.org Mon Dec 8 13:26:08 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 8 Dec 2003 10:26:08 -0800 Subject: from spam import eggs, spam at runtime, how? Message-ID: I worote several ugly version of this for a Cookbook recipe. You just convinced me to go update it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972 Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: Rene Pijlman > [mailto:reply.in.the.newsgroup at my.address.is.invalid] > Sent: Monday, December 08, 2003 8:33 AM > To: python-list at python.org > Subject: from spam import eggs, spam at runtime, how? > > > How do I do: > > from spam import eggs > > ... when 'spam' is only known at runtime? > > -- > Ren? Pijlman > -- > http://mail.python.org/mailman/listinfo/python-list > From paska at kios.sk Wed Dec 10 02:39:12 2003 From: paska at kios.sk (Stano Paska) Date: Wed, 10 Dec 2003 08:39:12 +0100 Subject: sorting slovak utf In-Reply-To: References: <3FD45B2C.1080107@kios.sk> Message-ID: <3FD6CDA0.5070703@kios.sk> Serge Orlov wrote: > "Stano Paska" wrote in message news:mailman.256.1070955895.16879.python-list at python.org... > >>I had an imagination, that there is some easy way >>to work with slovak, russian, english and german text in one application. > > Depends on what you mean "work". Upcase? Split words? Sort? Spell check? > Translate? Display? > Get from database or text file, show in wxTextCtrl, upper, lower, maybe sort, store into database or text file. > >>I only change locale from sk_SK.utf-8 to ru_RU.utf-8, ... and system works. >>Input and output are in utf-8. >> >>Is this a fantasy? > > If you mean sorting, yes. Python does not have handy functions to do that. > The good news is that the solution is only 10-15 lines away from you. You've > been given all information in this thread. Let me summarize it: > 1. Convert your input to unicode. > 2. Use locale named 'Slovak' (see my previous post why) On windows, 'slovak' works. I discover that 'sl' works too, but 'sk' does not (M$'s way of standardization?). > 3. Use DSU trick to sort the words, here's the (untested) D part of it: > def decorate(seq, locale_encoding): > return [(locale.strxfrm(s.encode(locale_encoding,'replace'),s) \ > for s in seq] Ok, I will try this. > > It's not as scary as strxfrm name implies. > -- Serge. > > > > Thanks for your time to explain me this. Stano. From david_sarraf at hotmail.com Fri Dec 5 22:01:18 2003 From: david_sarraf at hotmail.com (dave) Date: 5 Dec 2003 19:01:18 -0800 Subject: help with awt and jython Message-ID: Hi, how do you close a program in jython using awt. I get the following error: TypeError: windowClosing() too many arguments; expected 1 got 2 Traceback (innermost last): (no code object) at line 0 when I called System.exit(0) in an event handler from jython. Thanks in advance for your help, Dave From Raaijmakers, Vincent (IndSys, Fri Dec 19 12:38:46 2003 From: Raaijmakers, Vincent (IndSys, (Raaijmakers, Vincent (IndSys,) Date: Fri, 19 Dec 2003 11:38:46 -0600 Subject: SimpleXMLRPCServer vs handlername question Message-ID: <971323274247EB44B9A01D0A3B424C85048D0229@FTWMLVEM02.e2k.ad.ge.com> I'm struggling a bit to get a java client connected to my SimpleXMLRPServer. The issue is that the java client wants to call a specific handler on my server. so: server.handler.method() Like Pyro, I can give on the server side my handler a specific name at the time a register that handler as an instance. But, how to do that with this XMLRPC server? So for example: handler = Handler() server = SimpleXMLRPCServer(('localhost', port)) server.register_instance(handler, 'aHandlerName') #which is not possible Perhaps I have to use a different type of server. Unfortunately, I couldn't find examples in the libraries and using Google.. Please give me some advises. Thanks, Vincent From jtoher at cyllene.uwa.edu.au Tue Dec 2 00:12:57 2003 From: jtoher at cyllene.uwa.edu.au (james) Date: 1 Dec 2003 21:12:57 -0800 Subject: newbie - integer variable with leading zero for os.makedirs Message-ID: <278a833.0312012112.55912355@posting.google.com> I'm using python 2.3 and 2.2 on Mac OSX 10.3.1 My script creates directories from its input using os.makedirs This from http://www.python.org/doc/2.3.2/lib/os-file-dir.html: makedirs( path[, mode]) Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory... The default mode is 0777 (octal)... My text input specifies the mode as a string - '750', for example. I want to convert the string input to an integer variable for use by os.makedirs. makedirs works fine when I use a literal like 0750, but my problem is setting a variable to that kind of value. int('0750') converts the string from ascii to integer, but loses the first zero padding. Without the leading zero os.makedirs makes a mess of the permissions when it creates the path. I've tried: permission = int('750', 8) mode = oct(permission) but this returns an octal string '0755' and os.makedirs barfs again. It really wants an integer and it really wants that leading zero. How can I assign a number with a leading zero to an integer variable? Any thoughts much appreciated. From hwlgw at hotmail.com Sat Dec 27 12:25:48 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 09:25:48 -0800 Subject: ANN: Python Language Reference References: Message-ID: > [Troels Therkelsen] > ...To me, > it would be preferrable to be able to find the module I want in, say, 3-4 > clicks, rather than pressing several keys on the keyboard.... For me it would be preferrable to use only a few keystrokes instead of having to find the mouse! From bwglitch at hotpop.com Mon Dec 15 15:47:07 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Mon, 15 Dec 2003 15:47:07 -0500 Subject: Strip HTML tags? In-Reply-To: <7b454334.0312151121.edae739@posting.google.com> References: <7b454334.0312131911.70647953@posting.google.com> <7b454334.0312141157.8383dd5@posting.google.com> <7b454334.0312151121.edae739@posting.google.com> Message-ID: Fazer wrote: > BW Glitch wrote in message news:... > >>Fazer wrote: >>>Thanks! The recipe works out fine! The problem is that I saved the >>>class in a file and I want it to be included in my other script. How >>>can that be done? My other script is in the same directory as the >>>class and doing import doesn't work. >> >>You should import > > Thanks for the responce! I put the class and the final function in a > tags.py file. I make another script and do : "import tags" > It works, but when I try to make a new class instance, it can't seem > to find it. There are two ways to import modules, "import module" and "from module import *". The latter is seldom recommended. By doing a "import module", anything inside the module must be called like this: ### begin example import sys sys.exit(0) ### end example When you do a import tags, everything inside tags must be called tags.CLASS . HTH, -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- Blackarachnia: "We're almost through." Silverbolt: "Then ... stand back!" Blackarachnia: "Wait. We just have to--" [BLAM!] Blackarachnia: "Never mind ... What is it with guys and high explosives?" ("The Agenda" III) From jjl at pobox.com Sat Dec 27 07:20:55 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Dec 2003 12:20:55 +0000 Subject: Adding newusers to Unix system from mysql data (Better Approach) References: Message-ID: <87wu8imoyg.fsf@pobox.com> "Amy G" writes: [...] > My problem is this... It writes the data file without problem. But, the > os.system... does not necessarily work to add a new user. By 'not > necessarily' I mean that it works some of the time, but not all of the time. [...] > os.system('adduser -f /home/sean/bin/users.test') [...] You're not checking the exit status. Read the docs for os.system and os.wait, and look at the commands module. Then add code to your program to log details of any failures (the logging module in 2.3 is useful here), so you can figure out what goes wrong. John From joconnor at cybermesa.com Mon Dec 1 09:59:43 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Mon, 01 Dec 2003 07:59:43 -0700 Subject: Python for web ? In-Reply-To: References: Message-ID: black wrote: > Howdy everyone~ > > i heard Python could be used in web programming and aftering searching > many docs just found something on Python and CGI. the fact is i know > nothing about CGI and most of my projects(both of company and myself) > are established with PHP and ASP. now the questions come: > > 1. Could Python be used in web programming ? (i guess yes ?) > 2. If the answer of above is yes, then can we programms with Python in > both server and client side or either ? If by 'client side' you mean 'Python embedded in the HTML page' like PHP, I think it's possible but I tend to avoid it. First off, for any such HTML embedded scripting you have to have a server that while parse and execute the script. A lot of ISPs offer that for PHP but I'm not sure about for Python. More importantly, though, I'm not a big fan of the architecture of having HTML code interspersed with script coding. I think you'd end up with a better software design with a normal CGI-template approach From fredrik at pythonware.com Tue Dec 16 11:03:05 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Dec 2003 17:03:05 +0100 Subject: introspecting builtin functions/methods References: Message-ID: Gon?alo Rodrigues wrote: > Does anyone know if and how I can, from within Python, read the > signatures of builtin methods/functions? For methods/functions written in C, the signature is defined by a string passed to an internal C function (ParseTuple). And functions don't even have to use that function to process their arguments; they can pull values right out of the argument tuple (or they can use ParseTuple more than once, in order to support multiple calling conventions). I'd say your only hope is the doc string: >>> inspect.getdoc(list.append) 'L.append(object) -- append object to end' From aahz at pythoncraft.com Mon Dec 29 11:09:51 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Dec 2003 11:09:51 -0500 Subject: Python on Max osx and tkinter References: Message-ID: In article , Russell E. Owen wrote: > >What I did that worked on Jaguar: >- Installed MacPython 2.3 for Jaguar using the binary installer from: > >- Installed Tcl/Tk 8.4.4 using the binary installer from > >- Used Package Manager (in /Applications/MacPython) to install _tkinter >(and also readlines and some other useful stuff) Thanks! That's a clear explanation that probably ought to be on the MacPython page. (Haven't finished yet, but I'll take your word that it works.) >At that point you ought to be able to open a NEW terminal window (tcsh >caches some info, so an existing window will probably NOT work) and type >"pythonw" (not "python", that would result in a GUI you cannot bring to >the front) and you're in business: ``rehash`` ought to find ``pythonw`` -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From skip at pobox.com Sun Dec 21 14:57:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Dec 2003 13:57:54 -0600 Subject: web programming: experiences with non-zope frameworks? In-Reply-To: References: <7xu13u7gko.fsf@ruckus.brouhaha.com> Message-ID: <16357.64322.743844.54805@montanaro.dyndns.org> >> If you're doing a small project and can't afford to set aside that >> much time, then hold your nose and write in PHP or even Perl >> (HTML::Mason is an impressive package if you don't mind the cancer >> that is Perl, so it would be great if someone wrote something like it >> for Python). Brendan> That's certainly a shame to hear. I'm very concerned that any Brendan> given python framework I'd choose might not be around a few Brendan> years from now; it seems that none of them have the popularity Brendan> needed to sustain a large community to test and achieve Brendan> maturity, write books and top-quality documentation, etc. FYI, my previous framework was Mason. As I have time, I'm converting to Quixote. Skip From stain at stud.ntnu.no Tue Dec 16 23:56:23 2003 From: stain at stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 17 Dec 2003 04:56:23 +0000 (UTC) Subject: New style classes and rich comparison Message-ID: Could anyone explain to me why this does not work as intended? >>> class Oldstyle: ... pass ... >>> old = Oldstyle() >>> old == 1 False >>> old.__eq__ = lambda x: True >>> old == 1 True Nice and fine. >>> newbie = Newstyle() >>> newbie == 1 False >>> newbie.__eq__ = lambda x: True >>> newbie == 1 False Doesn't work! It seems that __eq__ is fetched directly from newbie's class, not from newbie. >>> Newstyle.__eq__ = lambda self, x: True >>> newbie == 1 True Adding a method __getattribute__ that prints the key and then calls object.__getattribute__ proves this - nothing is printed for comparison. This goes even for hash(): >>> newbie.__hash__ = lambda x: 1337 >>> hash(newbie) 1077345744 >>> Newstyle.__hash__ = lambda x: 15 >>> hash(newbie) 15 Why is this? Where is this documented? Here's my real goal, to create a Dummy class that supports anything: from dummy.py: class Dummy(object): """An object that can do anything in the world""" def __call__(self, *args, **kwargs): """Can be called with any kind of parameters, returns a new Dummy.""" return Dummy() def __getattribute__(self, key): """Any attribute created and stored on demand. All attributes are new Dummys.""" try: value = object.__getattribute__(self, key) except AttributeError: value = self() # remember it to next time! =) setattr(self, key, value) return value This dummy can be used for many things: >>> from dummy import Dummy >>> a = Dummy() >>> a.b >>> a.b == a.b 1 >>> a.b == a 0 >>> c = a.b.anything(123) >>> c.dot.something Now the trouble is that __operator__ is not resolved as I would expect. >>> a.__add__(a) >>> a + a Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand types for +: 'Dummy' and 'Dummy' Why are operators looked up in the class instead of the object? How can I modify my Dummy class to return 'anything' even directly in the class? Ie. what I probably want is something like this (simulated): >>> Dummy.asdads That way Dummy.__add__ would return a new Dummy instance, and Dummy() + Dummy() would work as expected. My first attempt was to manually define different __operator__-methods in the dummy, but this got rather boring. Can I use __metaclass__ or something? -- Stian S?iland Being able to break security doesn't make Trondheim, Norway you a hacker more than being able to hotwire http://stain.portveien.to/ cars makes you an automotive engineer. [ESR] From hwlgw at hotmail.com Sun Dec 7 04:47:02 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 7 Dec 2003 01:47:02 -0800 Subject: Help: Uploading .zip to Python CGI References: Message-ID: The problem I described in this thread is with Apache, not with Python! And the unix Apache at my work has no problems, its only the Windows Apache versions. So the Apache peeps will probably say it's a *Windows* problem 0-) I found out with the following: I can now avoid the first HTML page with the .zip upload, instead I upload the .zip to my Python CGI program with this little program: import urllib import webbrowser webserviceURI = r'http://localhost/cgi-bin/mycgiprogram.py' startpageName = 'start.xml' # instead of a HTML page with INPUT type=file just read the file fp = open(fname, 'rb') data = fp.read() fp.close() # all CGI parameters in a dict, and encoded params = urllib.urlencode({ 'yourfile': data }) # call the CGI program and read what it returns f = urllib.urlopen(webserviceURI, params) webpage = f.read() # save it locally in a file wpfp = open(startpageName, 'w') wpfp.write(webpage) wpfp.close() # show it in your browser webbrowser.open(startpageName) -- If pro is the opposite of con, what is the opposite of progress? From noemail at noemail4u.com Wed Dec 10 08:18:10 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Wed, 10 Dec 2003 13:18:10 GMT Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> Message-ID: <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> On Wed, 10 Dec 2003 11:19:21 +0100, Irmen de Jong wrote: >Sean Richards wrote: > > >> Tab completion for keywords and methods etc (you can get this in the >> standard python shell as well of course) > >You can? How? > >--Irmen Press tab after typing part of the keyword/method. This assumes you're *not* using Win32. The documentation says that IPython requires the GNU readline function, which I guess isn't available with Win32. Neither is color highlighting. --dang From fredrik at pythonware.com Fri Dec 5 04:25:52 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 Dec 2003 10:25:52 +0100 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > I disagree. You should use a tuple when you wish to not change the > contents once you have constructed the sequence, and otherwise you > should use a list. > Fredrik Lundh actually called me names a couple years back for > asserting this, but Python luminary (and rude fellow) or not, he is > dead wrong. I'm never dead wrong. Guido van Rossum, "State of the Python Union", March 2003: http://www.python.org/doc/essays/ppt/pycon2003/pycon2003.ppt ... + It's a matter of user education + Example: lists vs. tuples this is often misrepresented as "tuple are readonly lists", which is *wrong* use cases are quite different *but*... tuples also usable as readonly lists ... I expect an apology. From vincent at visualtrans.de Thu Dec 11 15:09:38 2003 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 11 Dec 2003 21:09:38 +0100 Subject: PyNew_Interpreter(): "Fatal Python error, invalid thread state for this thread" question Message-ID: Hi, Trying to grasp Py_NewInterpreter()in a simple app embedding Python, I was wondering why the following gives me an error: int main() { PyThreadState *tstate; Py_Initialize(); //The following returns //Fatal Python error, invalid thread state for this thread tstate = Py_NewInterpreter(); //etc.. Python is 2.3.3c1 on Win XP Pointers much appreciated Regards Vincent Wehren From max at alcyone.com Thu Dec 25 06:00:47 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 25 Dec 2003 03:00:47 -0800 Subject: Socket Programming References: Message-ID: <3FEAC35F.C26A14B1@alcyone.com> Kamuela Franco wrote: > Can someone give me some general information on socket programming in > Python. Very much like socket programming in C, only much easier :-). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ There are countless planets, like many island Earths ... -- Konstantin Tsiolkovsky From jacek.generowicz at cern.ch Wed Dec 10 11:45:27 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 17:45:27 +0100 Subject: Function unrolling (was Re: Speed: bytecode vz C API calls) References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > That's why I changed the Subject: to "Function unrolling"; you're going > to need to change your code to avoid function calls in inner loops. One > technique you might try is to create a generalized inner loop function: > > def innerloop(iterable, func, cache): > l = [] > for args in iterable: > try: > l.append(cache[args]) > except KeyError: > l.append(cache.setdefault(args, func(args)) > > return l OK, I see what you mean. I agree, I can do this, in some places, and toy tests suggest that getting rid of the function call could give me a factor of 3 improvement. I'll have to change the code in many places, but that's simpler than going to C. (However, we disagree on the specific formula you give above: I think that map is faster: see other post in the thread. [A quick test suggests that a map is faster than the loop by a factor of 2.]) > Yes, it's a performance hack, but I bet it's a lot clearer than C++ > code. No doubt about that :-) Cheers, From google at evpopov.com Tue Dec 16 06:36:18 2003 From: google at evpopov.com (popov) Date: 16 Dec 2003 03:36:18 -0800 Subject: Using python as client-side scripting language in IE 6 Message-ID: <7eecf173.0312160336.1160a340@posting.google.com> I try with no luck to use python in a simple html page: When opened in IE6 SP1, that does nothing (no error but no message box / nothing written in the page). I ran win32comext\axscript\client\pyscript.py and pyscript_rexec.py to register python as a scripting engine. No errors from those scripts. As I understand it and from what I have read in this forum and elsewhere, it should work, but it doesn't: what am I doing wrong ? Note: I have installed the latest win32all extensions (163) / I'm working on a W2K Server box (SP3). From kokoska.jan at globe.cz Fri Dec 5 10:03:24 2003 From: kokoska.jan at globe.cz (Jan Kokoska) Date: Fri, 05 Dec 2003 16:03:24 +0100 Subject: How to tell the difference between string and list In-Reply-To: <16336.40180.980551.605191@montanaro.dyndns.org> References: <1070635589.841.8.camel@marigold> <16336.40180.980551.605191@montanaro.dyndns.org> Message-ID: <1070636604.841.12.camel@marigold> Hello Skip, > if isinstance(a, str): > pass > elif isinstance(a, list): > pass > Tnx, worked like a charm (I would bet isinstance() uses __class__ internally, my bad). The time for me to read libref, probably ;) -Jan From fake at not-a-real-address.net Wed Dec 24 11:54:37 2003 From: fake at not-a-real-address.net (Bruce Wolk) Date: Wed, 24 Dec 2003 16:54:37 GMT Subject: Simple or Impossible in Python... dynamically dereferencing a class attribute In-Reply-To: References: Message-ID: Bill Sneddon wrote: > Given the following simple code. I was trying find a way to > dynamically de-reference a class attribute. Problem explained below. > > > class test: > def __init__(self): > self.a = 0 > self.b = 0 > self.c = 0 > > myDict = {} > myDict['one'] = test() > myDict['two'] = test() > > # I know I can do this at runtime. > myVar = 7 > myDict['one'].a = myVar > myLetter = 'b' > > ## Is there any way to choose the attribute of test based on a varible. > ## like this? > > myDict['one'].{myLetter} = 9 > > I know you can do this kind of thing with other languages Perl, C++ > > Is it possible with Python? > > If so what is the syntax in Python. > > Maybe there is a better/equivalent approach if so could you point me > to an example? > something like... setattr(myDict['one'],myletter,9) From stuart.b at commonground.com.au Tue Dec 9 20:26:45 2003 From: stuart.b at commonground.com.au (Stuart Bishop) Date: Wed, 10 Dec 2003 12:26:45 +1100 Subject: from spam import eggs, spam at runtime, how? In-Reply-To: References: <8765gpudpm.fsf@pobox.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 10/12/2003, at 6:28 AM, Rene Pijlman wrote: > from skin import template > > where skin is only known at runtime (it's passed as a parameter or > hidden > field to my mod_python application). That is scary - you need to treat anything arriving from the client as an attack. Consider what would happen if someone accessed the url: http://whatever/myapp?skin=test.testall Maintaining a blacklist is impossible, as new modules may be installed in the future. > The alternative would be: > > if skin == 'basic': > from basic import homepage > elif skin == 'modern': > from modern import homepage > > ... but this is unmaintainable and unpythonic. It is also correct IMHO, although you would be better off using a dictionary mapping string -> module, so you could just do: try: homepage = skinmod[skin] except KeyError: raise ValueError, 'No such skin: %r' % (skin,) You may want to use the import tricks elsewhere in this thread to build this dictionary though, for instance by doing an os.listdir() on your 'skins' directory. - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iD8DBQE/1nZaAfqZj7rGN0oRAlxqAJ4kf+Dm2BBkEhKJpIpokWAxhDPSLACePJlJ PKgunqahsWAYzuCHmcvXoxo= =bKfh -----END PGP SIGNATURE----- From mensanator at aol.compost Sun Dec 7 23:45:17 2003 From: mensanator at aol.compost (Mensanator) Date: 08 Dec 2003 04:45:17 GMT Subject: Base conversion method or module References: Message-ID: <20031207234517.22983.00000297@mb-m27.aol.com> >Subject: Re: Base conversion method or module >From: "Francis Avila" francisgavila at yahoo.com >Date: 12/7/2003 8:52 PM Central Standard Time >Message-id: > > >Jeff Wagner wrote in message ... >>On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" >wrotf: >> >>>Jeff Wagner wrote: >>> >>>> I found the Python cookbook recipe you were referring to. It is as >follows: >>> >>>(what's wrong with just posting an URL?) >> >>What a great idea ;) ... >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 > >Hey, I found another one which is the more general "inverse of int/long" >function I was pining for (and thus learning for the n-th time that one >should check the cookbook first before reinventing the wheel): > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/222109 These are nice, but they're very slow: For i=2**177149 - 1 224.797000051 sec for baseconvert 202.733999968 sec for dec2bin (my routine) 137.735000014 sec for radix Compare those to the .digits function that is part of GMPY 0.59399998188 sec That can make quite a difference when you're running through a couple million iterations. > >For some reason it's in the "Text" category, and uses the term "radix," >which is less common than "base". > >Hettinger's version (found in the discussion below) is better. > >Shouldn't something like this get into the builtins, so we can get rid of >hex/oct in Python3k? >-- >Francis Avila -- Mensanator Ace of Clubs From bokr at oz.net Tue Dec 23 08:21:53 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Dec 2003 13:21:53 GMT Subject: Counting how many chars equal to a given char are in the beginning of a string References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: On 23 Dec 2003 12:57:47 GMT, bokr at oz.net (Bengt Richter) wrote: >On 22 Dec 2003 12:04:21 -0800, andreif at mail.dntis.ro (Stormbringer) wrote: > >>Hi, >> >>Given a string s and a char c, is there a short & elegant way to >>determine how many consecutive occurences of c are in the beginning of >>s ? >> >>For example if s = ">>>>message1" and c = ">" then the number I am >>looking for is 4 (the string begins with 4 '>'). >> >Not tested beyond this example ;-) > > >>> def countleading(c, s): return len(s)-len(s.lstrip(c)) > ... > >>> s = ">>>>message1" > >>> countleading('>', s) > 4 > I wouldn't have posted this if the Re: replies had been in the same thread tree in my reader. Guess I need to upgrade ;-/ Regards, Bengt Richter From ptmcg at users.sourceforge.net Tue Dec 16 03:04:38 2003 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Tue, 16 Dec 2003 08:04:38 GMT Subject: ANN: parsing 1.0.0 - Python class library for defining and executing text parsers Message-ID: The parsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. The parsing module provides a library of classes that client code uses to construct the grammar directly in Python code. Here is a program to parse "Hello, World!" (or any greeting of the form ", !"): from parsing import Word, alphas greet = Word( alphas ) + "," + Word( alphas ) + "!" hello = "Hello, World!" print hello, "->", greet.parseString( hello ) The program outputs the following: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operator definitions. The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an object with named attributes. The parsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments The .zip file includes examples of a simple SQL parser, simple CORBA IDL parser, a config file parser, a chemical formula parser, and a four-function algebraic notation parser. It also includes a simple how-to document, and a UML class diagram of the library's classes. The parsing module can be found at http://sourceforge.net/projects/pyparsing/. Please let me know if you find this package helpful. Regards, -- Paul McGuire From just at xs4all.nl Tue Dec 9 16:32:35 2003 From: just at xs4all.nl (Just) Date: Tue, 09 Dec 2003 22:32:35 +0100 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> <7xy8tln207.fsf@ruckus.brouhaha.com> <3FD63B25.DC412905@engcorp.com> Message-ID: In article <3FD63B25.DC412905 at engcorp.com>, Peter Hansen wrote: > Paul Rubin wrote: > > > > Rene Pijlman writes: > > > >Why not just stick the import statement where you need it? > > > > > > Because I need a module from one of a number of different packages, at one > > > specific point in my code. > > > > I still don't understand why you don't want to use an exec statement > > for this. That's by far the most natural and understandable way to do it. > > In this case, he's getting the actual string from the web, so I wouldn't > be surprised if exec would be a real can of security worms. Also, __import__ returns a module object, so you don't have to pull it out of the globals you passed to exec. Compare: g = {} exec "import %s" % modulename in d m = g[modulename] with m = __import__(modulename) Just From aahz at pythoncraft.com Mon Dec 22 12:30:35 2003 From: aahz at pythoncraft.com (Aahz) Date: 22 Dec 2003 12:30:35 -0500 Subject: How do I test if an object is a sequence? References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: In article , John Roth wrote: >"Max M" wrote in message >news:3fe6fbb1$0$69983$edfadb0f at dread12.news.tele.dk... >> >> Is there a common idiom for testing if an object is a sequence? >> >> Both list, tuple and non-standard objects etc. I have Googled, but >> didn't find a usable answer. > >The best way I know of is to check for the existance of either __iter__ >or __getitem__. This gets you roughly the same results as either the >for statement or the iter() built-in function. Not quite. Try using ``for`` on a dict in Python 2.1 or earlier. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From __peter__ at web.de Tue Dec 9 10:03:05 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 16:03:05 +0100 Subject: parsing equations References: Message-ID: Diez B. Roggisch wrote: >> i have a question. >> Given the string '3+2*6' i need to parse it and obtain the result, so >> 15. Does a module for this operation exists? i need to do simple >> operations, but also on floating point numbers. > > Use the builtin function eval to evaluate an arbitrary python expression: > >>>> eval("3+2*6") > 15 Be aware that this is powerful: >>> eval("cleanMyHarddisk()") 'done' Just to make sure the OP is aware of the inherent danger of the unsuspecting "arbitrary python expression"... Peter From fredrik at pythonware.com Thu Dec 11 12:08:59 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 18:08:59 +0100 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com><7x65gn1jk5.fsf@ruckus.brouhaha.com> Message-ID: Cameron Laird wrote: > Guido certainly has the ability to do a low-level binding > to Tk (and I know someone did, on an experimental basis, > in the mid-'90s--was that he?) david ascher, based on brian warkentine's Rivet project. you can find traces of that project here (search for Trinket): http://py.vaults.ca/parnassus/apyllo.py/808292924.247038364.200301646 http://archive.dstc.edu.au/python/python/Contributed.html#Graphics (but don't expect the links on those pages to work) From lists at ghaering.de Tue Dec 2 09:09:23 2003 From: lists at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 02 Dec 2003 15:09:23 +0100 Subject: [ANNOUNCE] PySQLite 0.5.0 Message-ID: <3FCC9D13.4090603@ghaering.de> It was time to make another release of PySQLite, because lots of bugs were fixed and several sensitive changes were made, which need exposure in real life. Given the nature of the changes, I'd recommend you test 0.5.0 well before replacing 0.4.3. I'm in the middle of rewriting the documentation, examples and the website, so you can expect a 0.5.1 release within a few weeks. Here's the list of changes since the last release: - Removed all old docs and examples. Started writing new ones. - In sqlite.connect(), the parameter 'client_encoding' was renamed to 'encoding'. 'client_encoding' still works, but is deprecated. - Removed the usage of the warnings module for optional DB-API extensions. - Added the type constant sqlite.UNICODESTRING. - Added missing copyright statements for port/strsep.c, which was imported from FreeBSD. - John E. Barham helped with adding a binary type to PySQLite. To insert binary encoded data into a column of type BLOB, encode it using sqlite.Binary() first. - Columns with the column type 'UNICODE' are now automatically converted to unicode strings. - BIG CHANGE: Release the GIL while the SQLite engine does its work. The PyThreadState is stored in the connection object. - Plugged a memory leak that appeared in user-defined aggregates. - Added missing MANIFEST.in (fixes bug #833821). - Fixed bug #842630: .commit() is now a no-op in autocommit mode, instead of raising an exception. This behaviour is mandated by the DB-API 2.0. - Fixed bug #808952: The enhanced PgResultSet wrapper was not used for rows if you used the fetchmany() method. - Make user-defined aggregates actually work. - Detect more column type names as "numeric" ones. From vivek at cs.unipune.ernet.in Mon Dec 29 06:48:31 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Mon, 29 Dec 2003 17:18:31 +0530 Subject: xmlrpc / SimpleXMLRPCServer and multi-threading In-Reply-To: <15c2d03b.0312290247.6a0bc41d@posting.google.com>; from PPNTWIMBXFFC@spammotel.com on Mon, Dec 29, 2003 at 02:47:35AM -0800 References: <15c2d03b.0312290247.6a0bc41d@posting.google.com> Message-ID: <20031229171831.A12912@cs.unipune.ernet.in> On Mon, Dec 29, 2003 at 02:47:35AM -0800, Marco Aschwanden wrote: > I would like to develop a server based on python's xmlrpc. But I > realized that SimpleXMLRPCServer does not spawn a thread for each > request. > > How could the SimpleXMLRPCServer be turned into a multi-threaded > Server? > Is there a reason why the SimpleXMLRPCServer is not multi-threaded? > Is there a plan to make it multi-threaded? > > Thanks for any hints in advance, > Cheers, > Marco I had also faced the same problem some time ago. To use the SimpleXMLRPCServer as a multithreaded server, I just changed the SocketServer.TCPServer to SocketServer.ThreadingTCPServer in the definition of the SimpleXMLRPCServer class and it worked fine for me. But it was on Python 2.2 and I haven't tried on later versions. HTH, Vivek Kumar From duncan at NOSPAMrcp.co.uk Tue Dec 16 06:48:56 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 16 Dec 2003 11:48:56 +0000 (UTC) Subject: Cropping log files References: Message-ID: Kamus of Kadizhar wrote in news:brmp3g$b4ar$1 at news3.infoave.net: > The logging module lets me log events, but there aren't any tools for > managing the log files created in the way I need.... The > RotatingFileHandler rotates logs in the sense of logrotate, but what I > need is to keep only the last n records in one file. > Keeping a fixed number of records in one file is difficult if the records aren't a fixed length, which is why most logging systems limit the number of records that are kept by the size of the data, rather than by the number of records. If you can modify your requirements to say that you need to keep 'at least n records' then rotating file logger will do that, just make sure that the size that is kept in all files is at least n times the largest record you might log. Of course the records will then be split across multiple files. If you really need to keep n records in one file, then the best thing is probably to write your own handler for the logging module and store the log records in a fixed length format in the file. i.e. you choose a size larger than your largest log record and pad each log record to that length with nulls. Then you just write out to the file as though it were a circular buffer. You need some way of finding the first record again: one way is to always ensure you have at least one empty record in the file so when you first open the file you scan to the first empty record, then each time you write to the file you write the new record followed by a new empty record, then skip back so the empty record will be overwritten. When you reach record number n+1 in the file you simply wrap back to the start. You'll also want to write code to read a logfile starting after the last empty record. If you can't set a hard upper bound on the size of a record you will need a more complicated file structure, or if that 'n' doesn't absolutely have to be set in stone simply allow occasional long records to wrap over into the next record and handle that case in both writing and reading code. The NTEventHandler, (for those of us on Windows systems) does pretty much this last option, it uses event logs files which are a fixed length and wrap round, but individual records can span more than one block in the file, so the number of entries in a logfile is actually an upper limit. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From fw58959 at hotmail.com Fri Dec 5 10:04:46 2003 From: fw58959 at hotmail.com (CK) Date: 5 Dec 2003 07:04:46 -0800 Subject: thread vs threading -- Unexpected Results References: Message-ID: "Krzysztof Stachlewski" wrote in message news:... > "CK" wrote in message > news:c0367340.0312032212.70ab984a at posting.google.com... > > > Program A - thread example > > .... snip ... > > After the loop completes, the main thread terminates > and so your whole program. You don't wait for the threads > to finish. > Good point. I added code to check for this (a la Programming Python by Mark Lutz) but the results are really strange. All I see are Connecting messages and never a disconnecting message and so now the whole program hangs waiting for these "hung" threads to wake up. Here is the revised "thread" code #!/usr/local/bin/python import socket import time import thread threadlist = [0] * 2048 threadId = -1 def tcp_connect(dst_ip,dst_port,thisId): print "%s Connecting to %s on port %d ThreadId=%d" % (time.asctime(),dst_ip,d st_port,thisId) s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((dst_ip,dst_port)) except: pass s.close() threadlist[thisId] = 1 print "%s Disconnecting from %s on port %d" % (time.asctime(),dst_ip,dst_port) for x in range(0,2): for octet3 in range(32,36): for octet4 in range(0,256): threadId = threadId + 1 ip_addr = "10.34."+str(octet3)+"."+str(octet4) thread.start_new_thread(tcp_connect,(ip_addr,135,threadId)) while 0 in threadlist: time.sleep(2) print "Main thread exitting" and here is some sample output.... Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.0 on port 135 ThreadId=0 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.5 on port 135 ThreadId=5 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.6 on port 135 ThreadId=6 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.7 on port 135 ThreadId=7 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.8 on port 135 ThreadId=8 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.9 on port 135 ThreadId=9 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.10 on port 135 ThreadId=10 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.11 on port 135 ThreadId=11 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.12 on port 135 ThreadId=12 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.13 on port 135 ThreadId=13 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.14 on port 135 ThreadId=14 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.15 on port 135 ThreadId=15 Fri Dec 5 06:54:12 2003 Connecting to 10.34.32.16 on port 135 ThreadId=16 ... Never see a Disconnecting message, never see "Main thread exitting" > > Program B - threading example ....snip.... > The connections are closed very quickly. This time is so short > that the scheduler did not switched tasks. > Why you see a different pattern of calls I cannot tell. > Probably an artefact of the task scheduler? > I would not worry about this. All of your > operations completed within one second. > Try to put something - at least a delay - between > connect() and close() and see how it works. You are correct on this one. I added a time.sleep(2) just before the close and I got results that one would expect. I don't know what I am doing wrong in the 'thread' example but the 'threading' example works just fine. Thank you for your help Stach. ./CK From bdesth.nospam at removeme.free.fr Thu Dec 11 18:12:45 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Fri, 12 Dec 2003 00:12:45 +0100 Subject: What GUI toolkit looks the best? In-Reply-To: <7xhe0781tc.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> Message-ID: <3fd8f5bd$0$17127$626a54ce@news.free.fr> Paul Rubin wrote: > Bruno Desthuilliers writes: > >>>I guess >>>I can get the client to pay >> >>Why ? It's free (as in free beer and free speech) > > > I mean for the build tools (Visual C++ or whatever). I can't really > use the WxWindows source code without a way to compile it. You can build wxWindows with the free (as in free beer) Borland's bcc5.x compiler, or with free (as in free beer and free speech) compilers like Minwg's gcc. > I'm getting > discouraged to hear that WxWindows itself has numerous bugs though. I did not used wxWindows intensively, but I never had a crash in three years. I couldn't say the same about apps written with MS VisualBasic or like :(. Every non-trivial code does have bugs. Python has bugs, gcc has bugs, not talking about msvc. I think that some posts in this thread were a bit of a special case (FUD or bad experience, I can't tell...) wxWindows has 11 years of existence, and bindings exists for more and more languages (Javascript, Python, Perl, haskell, lua, Ruby, Eiffel, and even Java and C#...). I don't think so many developers would spend personnal time writing bindings to a 'that much buggy' toolkit !-) Bruno From martin at v.loewis.de Tue Dec 30 05:06:37 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 30 Dec 2003 11:06:37 +0100 Subject: Python and Tk: Error on Memory Access In-Reply-To: References: Message-ID: Markus Franke wrote: > I have tried several versions of python, Tk and Tkinter but > without success. > > My System: > > Red Hat 9(Severn) On Redhat 9, you should either use the packages that the system vendor provides, or you should compile Python yourself. Installing a foreignly-built Python is likely to give problems with Tk. Regards, Martin From harry_chillboy at rediffmail.com Thu Dec 18 07:43:50 2003 From: harry_chillboy at rediffmail.com (Harish) Date: 18 Dec 2003 04:43:50 -0800 Subject: How to access MFC classes in Python using SWIG ? References: <87zndsyja5.fsf@pobox.com> <3fe07ab5$0$579$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Brian Kelley wrote in message news:<3fe07ab5$0$579$b45e6eb0 at senator-bedfellow.mit.edu>... > John J. Lee wrote: > > harry_chillboy at rediffmail.com (Harish) writes: > > > > > >>I am using Python2.3 version with SWIG-1.3.19 to access C++ interface > >>provided by a DLL. > >>Some of its function returns MFC class objects like CString , CMap. I > >>tried to generate wrapper for these classes using SWIG by including > >>respective header files in .i file. > >>But it doesn't work. Swig reports hundreds parsing errors in MFC's > >>file. > > the ctypes package may do what you want > http://starship.python.net/crew/theller/ctypes/tutorial.html > > Brian Thanx Brian for your reply, ctypes is really very helpful in my case to access most of the functions. But I am stuck with some functions which return objects of MFC::CString or CMap<>. ctype talks only about c type function and simple data types. SWIG provides readymade wrappers for common STL classes but not MFC :( From roy at panix.com Fri Dec 5 14:05:40 2003 From: roy at panix.com (Roy Smith) Date: Fri, 05 Dec 2003 14:05:40 -0500 Subject: Lists and Tuples References: Message-ID: In article , "Michael T. Babcock" wrote: > PS, you can turn a tuple into a list quickly with list compressions; > > list = [ x for x in tuple ] What's wrong with the even simplier: aList = list (aTuple) From rainerd at eldwood.com Thu Dec 18 22:17:36 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 19 Dec 2003 03:17:36 GMT Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: Glen Wheeler wrote: > Hello all, > > My program uses many millions of integers, and Python is allocating > way too much memory for these. I can't have the performance hit by > using disk, so I figured I'd write a C extension to define a new type. > Problem is, my C knowledge is years old and regardless of my > attempts distutils will not recognise my installation of the MS > compiler. > I am thinking, is there any easier way to use a 5 or 6 bit integer > in python? Even a regular 8-bit would be fine. I only need to > represent either 32 or 64 distinct numbers. You're trying to solve the wrong problem. Python caches small integers, so you've only got a very small number of distinct integer objects. This is a good thing, because each Python object has a eight byte overhead. Introducing a new type wouldn't result in any memory savings. The real overhead comes from the references to those objects. Each reference is four bytes (on 32 bit computers), and there is no way to decrease this. Your best option is to use high level objects that contain many integers internally but don't store them as individual Python references. The array module is one choice, Numarray is another. If immutability isn't an issue, you could even use strings (with each character treated as an eight bit integer). -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From kristofer at hotpop.com Thu Dec 11 09:39:36 2003 From: kristofer at hotpop.com (Kristofer Wouk) Date: Thu, 11 Dec 2003 14:39:36 GMT Subject: running non-python progs from python In-Reply-To: References: Message-ID: Spiffy wrote: > "Marc Boeren" wrote in message > news:mailman.30.1071062337.9307.python-list at python.org... > >>Hi, >> >> >>>Spiffy wrote: >>> >>>>>that indicates that it's supposed to work, don't you think? >>>> >>>>IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? >> >>I can understand that you get frustrated that os.system doesn't seem to >>work, but there's no need to shout. >> > > > Shout? That's funny, I like that. If I appear to have been angry, it was > directed solely at one person, who for some unknown reason, was more > interested in harassing than helping me. > > >>I've read the thread, and noticed one odd thing. You said that if you >>execute: >> >>C:\Python22>playb Canyon.mid >> >>from the command line, it works. >>Later, you try to execute 'C:\Python22\playb.exe' with Canyon.mid as a >>parameter. >> >>Did it occur to you that playb.exe may not be located in C:\Python22\ at >>all? > > > ....playb.exe is located in C:\Python22\ > > >>The command-line you said you executed starts playb from within the > > Python22 > >>folder, but it could have found playb.exe anywhere in your Windows PATH. >> >>Can you locate playb.exe on you hard-drive using the Windows Explorer? > > What > >>is the exact location the program appears in? Try to use that in you call > > to > >>os.system. >> >>One other useful technique to track down a problem: >> >>import os >>program = r"C:\Windows\playb.exe" >>filename = r"D:\MIDI\anyfile.mid" >>commandline = "%s %s" % (program, filename) >>print commandline >>os.system(commandline) >> >>This will print the complete command-line first. You can copy/paste this > > to > >>a DOS-box and execute it (from within any directory) and see what happens. >> >>Good luck, >> >>Cheerio, Marc. >> > > > Thanks for responding and trying to help. Fredo emailed me with a solution > for the problem and now I have working code. yay! > > I'd just like to add here, I really don't think you were being "harrassed" at all. I can understand getting frustrated when you can't get anything working, but from my experience with c.l.p, I don't think I've ever seen anyone harrased by someone who actually frequents the list. Kris From arnout.standaert at n-o-s-p-a-m.cit.kuleuven.ac.be Mon Dec 22 04:09:12 2003 From: arnout.standaert at n-o-s-p-a-m.cit.kuleuven.ac.be (Wald) Date: Mon, 22 Dec 2003 09:09:12 +0000 (UTC) Subject: PNG to EPS with Python? References: Message-ID: hwlgw at hotmail.com (Will Stuyvesant) wrote: > There is a png2eps > tool for linux/unix, but I can't find something that works on > Windows. BMEPS is what you are looking for: http://www.ctan.org/tex-archive/support/bmeps/WIN32BIN/ Greetings, Wald From cjw at sympatico.ca Wed Dec 31 15:13:33 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 31 Dec 2003 15:13:33 -0500 Subject: PythonWin problems Message-ID: PythonWin has been my favourite IDE for quite a while. When one right clicks on a .py file in the Windows Explorer, among the options are Open and Edit. The former is the default and executes Python, with the selected script. The latter activates the PythonWin editor, with the selected script. Since, most frequently, I wish to edit the script, or execute it with the debugger, I tried changing the default to Edit, using the Edit File Type menu. Unfortunately, this leads to a couple of problems: 1. Any activity becomes horrendously slow, and 2. The following message appears: LoadBarState failed - LoadBarState failed (with win32 exception!) [Dbg]>>> Does anyone have a workaround suggestion? Thanks. Colin W. From mbabcock at fibrespeed.net Fri Dec 5 13:43:46 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 05 Dec 2003 13:43:46 -0500 Subject: Lists and Tuples In-Reply-To: References: Message-ID: <3FD0D1E2.50108@fibrespeed.net> I'm not sure if its a good answer or not, but I use tuples when the number of items can't / won't change and arrays/lists when they may or will change. def get_values(): #... do stuff ... return (x,y,z) (x,y,z) = get_values() PS, you can turn a tuple into a list quickly with list compressions; list = [ x for x in tuple ] -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From gumuz at looze.net Wed Dec 3 09:12:26 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 3 Dec 2003 15:12:26 +0100 Subject: Asynchronous SimpleXMLRpcServer References: <3fcdd76e$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: <3fcdef48$0$260$4d4ebb8e@news.nl.uu.net> thanx, that's all I needed to know. "Andrew Bennetts" wrote in message news:mailman.71.1070459453.16879.python-list at python.org... On Wed, Dec 03, 2003 at 01:30:40PM +0100, Guyon Mor?e wrote: > hi all, > > maybe this is a stupid question, but I'll ask it anyway. > > does the SimpleXMLRpcServer handle connection asynchronous? I don't think it does, as it just uses SocketServer. > if not, how can I make it asynchronous? This isn't exactly what you asked, but you can do asynchronous XML-RPC easily with Twisted. Here's some example code: http://twistedmatrix.com/documents/examples/xmlrpc.py The docs for the XML-RPC support are here: http://twistedmatrix.com/documents/howto/xmlrpc -Andrew. From js at cis.uni-muenchen.de Wed Dec 3 07:37:03 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 03 Dec 2003 13:37:03 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com> <3FCC6C18.7090209@Linux.ie> Message-ID: "Fredrik Lundh" writes: > you can use "sre_parse.parse(x).getwidth()" on a subexpression, to > get the shortest/longest possible match. > > >>> from sre_parse import parse > >>> parse("a?").getwidth() > (0, 1) > >>> parse("ab").getwidth() > (2, 2) > >>> parse(".+").getwidth() > (1, 65535) > > (where >=65535 should be interpreted as "any number") > > Thanks for the tip. From newsgroups at jhrothjr.com Sat Dec 20 16:14:40 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 16:14:40 -0500 Subject: dynamic typing questions References: Message-ID: "Alexander Schmolck" wrote in message news:yfsu13viaf2.fsf at black132.ex.ac.uk... > "John Roth" writes: > > > Also, pervasive testing has so many other advantages > > that I'm beginning to think that debuggers were the > > single worst invention in history. > > Pervasive testing is much easier in an interactive enviroment with a good > debugger. It's much easier if you automate your tests, you write them first and you write the code for each one as you write the test. Then you don't need the debugger. Usually. John Roth > > 'as From bignose-hates-spam at and-benfinney-does-too.id.au Sun Dec 28 23:05:41 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 29 Dec 2003 14:55:41 +1050 Subject: ishexdigit() References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: On Sun, 28 Dec 2003 18:15:49 -0800, engsolnom at ipns.com wrote: > Also, if I have a string 4 chars long, representing two bytes of hex, > how can I *validate* the string as a *legal* hex string? > > isdigit works until string = '001A', for example > isalnum works, but then allows 'foob' > > Is there a 'ishexdigit'? I could parse the string, but that seems > "un-Pythonish" More Pythonish is to use string.hexdigits and map() to write your own: >>> import string >>> def ishexdigit( char ): ... result = ( char in string.hexdigits ) ... return result ... >>> def ishexstring( str ): ... resultmap = map( ishexdigit, str ) ... result = ( False not in resultmap ) ... return result ... >>> ishexstring( '010101' ) True >>> ishexstring( 'deadb00f' ) True >>> ishexstring( 'foob' ) False -- \ "For mad scientists who keep brains in jars, here's a tip: why | `\ not add a slice of lemon to each jar, for freshness?" -- Jack | _o__) Handey | Ben Finney From stephen at dino.dnsalias.com Thu Dec 18 01:31:32 2003 From: stephen at dino.dnsalias.com (Stephen J. Bevan) Date: Thu, 18 Dec 2003 06:31:32 GMT Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: Charles Steinkuehler writes: > I could be wrong, but it looks to me like SIOD requires a C runtime > library to function. One of the big attractions of using Forth (at > least to me) is it's lack of reliance on a runtime library. Direct > interfacing to the linux kernel should be possible in an > architecture-neutral manner, and the ~10K overhead of a Forth kernel is > very minimal when compared to the ~75K overhead of SIOD (from the > website) + the hundreds of KBytes (if not MegaBytes) of overhead for the > runtime C library. After stripping out various add-ons like crypto, HTML, base64, ... etc., and statically linking it against diet-libc I get :- $ file xsiod xsiod: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped $ size xsiod text data bss dec hex filename 92169 588 6192 98949 18285 xsiod $ Which is <100K for everything -- no hidden costs of dynamic linking or external libraries. There is still more than could be done e.g. get rid of any use of stdio (which if we believe the dietlibc output costs 7+KB) and trim away functions in the SIOD standard library that would not be needed for the given application. > Using a forth-based solution to create the root ramdisk image would > drastically reduce the footprint of the initial ramdisk image, remove > reliance on a particular C runtime library (allowing folks to build > runtime root images based on uClibc, glibc, or whatever), and provide a > *VERY* powerful yet tiny runtime scripting/programming language for > extending the system. IMHO what drastically reduces the footprint is not using glibc at all. From cjw at sympatico.ca Wed Dec 24 14:40:00 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 24 Dec 2003 14:40:00 -0500 Subject: IDE for debugging In-Reply-To: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: I have been pleased, in the main, with PythonWin by Mark Hammond. If you are planning to use wxPython, you might consider Boa Constructor, which has a debug capability. Colin W. python newbie wrote: > I need the ability to debug, so I think I'm learning toward buying Komodo, > however this would only be for straight Python. When I start building a > wxPython interface to my current program, will this work? > > Does anyone currently develop in wxPython and if so, are you using a > dependable tool for debugging in this? > > Thanks > Steve > > From shalabh at gameboard.org Fri Dec 19 20:27:15 2003 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: Sat, 20 Dec 2003 01:27:15 GMT Subject: dynamic typing questions References: Message-ID: Jason Tesser wrote (relevant excerpts only): > We are considering useing Java or > Python. > The other programmer here is very concerned about > dynamic typing though in Python. He feels like this > would be too much of a hinderance on us and too easy > for us to make a mistake and not catch it until > runtime making debugging harder. > > OK what are your guys thoughts here? How have you all > overcome the lack of static typing? IMHO, the impediments introduced by static typing are not worth the benefit of catching type errors at compile time. Further, you still have to do testing to find other bugs. The increased productivity due to dynamic typing in Python allows for more testing time to catch _all_ errors (type or otherwise). Development + testing time for a Python program usually turns out to be much less than just development time for an equivalent Java program (for me, at least). An interesting read is Guido van Rossum's interview at http://artima.com/intv/strongweak.html Also note that even in Java, static typing does not achieve much in many cases (except requiring more keyboard typing), as illustrated in the following example: // myVector is a java.util.Vector, index is an int String myStr = (String) myVector.get(index); If the object in the vector is not a String, it is only at run time that the error will be caught. Admittedly, static typing allows the compiler to produce faster programs. But the question isn't if it is fast. The question is if it is fast enough. -- Shalabh From gyromagnetic at excite.com Fri Dec 19 08:42:19 2003 From: gyromagnetic at excite.com (gyro) Date: Fri, 19 Dec 2003 06:42:19 -0700 Subject: dictionary 'hash' Message-ID: <3fe3003b@news.ColoState.EDU> Hi, I have a collection of objects that I am currently trying to manage. Each object is initialized with a dictionary. The dictionaries have the same keys but may have different values. The initialization process is time consuming, so I don't want to create an object if I have already instantiated one using a dictionary with the 'same' items. I would like to collect the objects in a dictionary with the objects as values and some identifier or hash of the initializing dictionary as the keys. For instance: idicts = [{'k1':val1,'k2':val2}, {'k1':val3,'k2':val4}, {'k1':val1,'k2':val2}] for idict in idicts: dhash = somehashingfunction(idict) if not objectstoragedict.has_key(dhash): newobj = MyClass(idict) objectstoragedict[dhash] = newobj Any ideas for 'somehashingfunction'? The values in idict may be strings, integers, or instances of other classes I have created. Presently, I am considering something like def somehashingfunction(rdict): import sha dkeys = rdict.keys() dkeys.sort() rvals = [repr(rdict[key]) for key in dkeys] rstr = '_'.join(rvals) dhash = sha.new(rstr).hexdigest() return dhash I'd appreciate any suggestions or comments. Thanks. -g From bdesth.nospam at removeme.free.fr Mon Dec 15 17:25:36 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2003 23:25:36 +0100 Subject: Beginner question - How to effectively pass a large list In-Reply-To: References: Message-ID: <3fde309f$0$19285$626a54ce@news.free.fr> J.R. wrote: > Hi folks, > > The python can only support passing value in function call (right?), let's see : >>> l = range(5) >>> def modif(alist): alist[0] = 'allo' ... >>> l [0, 1, 2, 3, 4] >>> modif(l) >>> l ['allo', 1, 2, 3, 4] Er... Ok, let's try something else : >>> class Toto: ... pass ... >>> t = Toto() >>> t.name = "Toto" >>> def rename(t): t.name = "Titi" ... >>> t <__main__.Toto instance at 0x402dccec> >>> t.name 'Toto' >>> rename(t) >>> t <__main__.Toto instance at 0x402dccec> >>> t.name 'Titi' Well... You may want to read more about bindings (not 'assignements') in Python. (hint : it already *does* work like pointers in C[++] - at least for mutable objects). Bruno From afriere at yahoo.co.uk Thu Dec 18 18:29:55 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 18 Dec 2003 15:29:55 -0800 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: <38ec68a6.0312181529.729b654@posting.google.com> "J.R." wrote in message news:... > 1. There is no value passed to the default argument > The name "d" is bound to the first element of the f.func_defaults. Since the > function "f" is an > object, which will be kept alive as long as there is name (current is "f") > refered to it, the > list in the func_defaults shall be accumulated by each invoking. > ... > > I think we could eliminate such accumulation effect by changing the function > as follow: > >>> def f(d=[]): > d = d+[0] > print d > And the reason this eliminates the accumulation is that the assignment ('d = d + [0]') rebinds the name 'd' to the new list object ([] + [0]), ie. it no longer points to the first value in f.func_defaults. What surprised me was that the facially equivalent: >>> def f (d=[]) : ... d += [0] ... print d did not do so. Apparently '+=' in regards to lists acts like list.apppend, rather than as the assignment operator it looks like. From gombosk at vas.birosag.hu Wed Dec 10 11:13:41 2003 From: gombosk at vas.birosag.hu (Gombos Katalin) Date: Wed, 10 Dec 2003 17:13:41 +0100 (CET) Subject: Pmw.ComboBox In-Reply-To: <20031027023332.000038fa.ddarius@hotpop.com> Message-ID: Hi, How could I make the ComboBox state disabled? I don't want to let anybody to scroll the listbox of the ComboBox. Thank You! Katux From other at cazabon.com Tue Dec 9 01:49:24 2003 From: other at cazabon.com (Kevin) Date: Tue, 09 Dec 2003 06:49:24 GMT Subject: Python supported web hosting? References: Message-ID: www.synergyconnect.com Pretty decent support, decent pricing, Python 1.5 and 2.2 supported, and they'll install binary modules if you need them too. Kevin. "Jeff Wagner" wrote in message news:dilatvo3so7e6qjbd3kujp2nth5hkr16r5 at 4ax.com... > Does anyone know of a good web hosting company who supports Python? When I finally get my numerology > program written, I would like to put it on my web site for everyone to be able to use but my present > web host only supports Perl CGI scripts. > > Jeff From bucodi_no_spam at ahoo.fr Tue Dec 16 06:26:13 2003 From: bucodi_no_spam at ahoo.fr (Rony) Date: Tue, 16 Dec 2003 12:26:13 +0100 Subject: Cropping log files References: Message-ID: If you need a ASCII database, you could have a look at kirbybase -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi_no_spam at yahoo.fr (delete _no_spam) / | www.bucodi.com - My work \ www.ifrance/karamusique -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From exarkun at intarweb.us Wed Dec 10 12:03:30 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 10 Dec 2003 12:03:30 -0500 Subject: Email attachments and text In-Reply-To: References: Message-ID: <20031210170330.GA15860@intarweb.us> On Wed, Dec 10, 2003 at 08:25:35AM -0800, Mark Carter wrote: > Section 12.2.13 (from the email module) gives examples of how to send > attachments with emails. The problem is, it does not explain how to > send text in the body of the message. One line of code that is gives > is: > outer.preamble = 'You will not see this in a MIME-aware mail > reader.\n' > > So how do I arrange it so that the text *will* be seen? I recommend reading the documents linked from this page: http://www.mhonarc.org/~ehood/MIME/ Once you have a solid understanding of MIME (particularly the multipart type), using the email package should present no problems. Jp From dpryde+usenet at cis.strath.ac.uk Mon Dec 8 13:50:52 2003 From: dpryde+usenet at cis.strath.ac.uk (Daniel Pryde) Date: Mon, 08 Dec 2003 18:50:52 +0000 Subject: Class problem In-Reply-To: <2of9tvkkfjdj4s035flqv9igjcl6vpfjjn@4ax.com> References: <3fd4b254$1@nntphost.cis.strath.ac.uk> <3fd4bcb5$1@nntphost.cis.strath.ac.uk> <2of9tvkkfjdj4s035flqv9igjcl6vpfjjn@4ax.com> Message-ID: <3fd4c811$1@nntphost.cis.strath.ac.uk> Rene Pijlman wrote: > Daniel Pryde: > >>the code's on my home hard drive > > > Never leave home without it :-) > > >>import ImagePyramid >>pyramid = ImagePyramid(parameters) > > > Yes, that should be: > > import ImagePyramid > pyramid = ImagePyramid.ImagePyramid(parameters) > > This is explained in section 6 "Modules" of the tutorial on > http://www.python.org/doc/current/tut/node8.html > Whoops! I got into trouble last time when I posted and found out that the answer was in the tutorial. I'll need to pay attention a bit more often. :-) Thanks for the help though. Daniel From try_vanevery_at_mycompanyname at yahoo.com Sun Dec 21 07:23:28 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Sun, 21 Dec 2003 04:23:28 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: "Simon B" wrote in message news:HfUEb.59264$aT.37735 at news-server.bigpond.net.au... > > .NET is a platform, not a language. What you probably meant to say was: > "C# is of course based on Java and a number of other higher level > langauges". Completely true... Just as Java is based on Smalltalk and > C++ along with a number of other higher level langauges. I do tend to mishmash terms in a way that's annoying to a lot of "harder core" programmers than myself. > (http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html). There are far > more languages running on the JVM than languages running on .NET. "More," yes, but at a glance most of those look like academic tweaky languages. So to an industrialist, don't count. I'll save the exercise of determining which ones do count for some time when I'm more awake. > My opinion on why MS did take the .NET path is based on the premise that > they are only really interested in Operating Systems, which isn't too > bigger a stretch. They want to sell operating systems, and part of the > reason corporations don't upgrade to the lastest version until they > absolutely have to (and even then, they often don't!) is because they > have invested big money in software that will require considerable > testing and/or modification and/or risk if the underlying OS changes. > > .NET solves that problem for Microsoft. Does it? What if in so doing, only .NET has value, and OSes have no value! W2K with .NET, XP with .NET, makes no difference. Stuff still runs. But they do get to sell Visual Studio, and they can patent screw Linux. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From klapotec at chello.at Sun Dec 28 09:55:19 2003 From: klapotec at chello.at (Christopher Koppler) Date: Sun, 28 Dec 2003 14:55:19 GMT Subject: Help, multidimensional list References: Message-ID: On Sun, 28 Dec 2003 14:27:41 +0000, Crawley wrote: >Im trying to create a list of lists and for some reason its not working: > >class Tile: > _next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, >'sw':None, 'w':None, 'nw':None } > > >def blankGridCanvas( maxx, maxy ): > grid = [] > for y in xrange( 0, maxy ): > yline = [] > for x in xrange( 0, maxx ): > t = Tile() > if y != 0: > t._next[ 'n' ] = grid[ y - 1 ][ x ] > t._next[ 'n' ]._next[ 's' ] = t > > yline.append( t ) > grid.append( yline ) > > for y in xrange( 0, maxy ): > for x in xrange( 0, maxx ): > print grid[ x ][ y ], grid[ x ][ y ]._next > return grid > >now by my reconing this should be a list of lists with each element being >an instance of Tile, You only create a *class* Tile, and provide no way to create *instances* of it - so much like with static variables in other languages, you only have one 'instance' here. To be able to create separate instances, you need a constructor in your class to instantiate every instance, like so: class Tile: def __init__(self): self._next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, 'sw':None, 'w':None, 'nw':None } and some references being manipulated to point to each >other. But strangly no, its actually a list of lists where each element is >the SAME instance of Tile, so I change one, i change them ALL! > >Whats going on and how do I solve it? Any gurus around can certainly much better explain what's going on and why... -- Christopher From aleax at aleax.it Fri Dec 26 11:33:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Dec 2003 16:33:51 GMT Subject: Socket Programming References: Message-ID: Rene Pijlman wrote: > Alex Martelli: >>visit safari.oreilly.com >>Just remember to cancel the subscription within 2 weeks so you won't have >>to pay for it! > > What's wrong with paying for all that good stuff. Sorry, I generally conclude the above advice with "unless of course you find the safari service useful" but I was a bit rushed this time. I do, personally, find safari quite useful and worthwhile (and how!), but since, here, I was suggesting using it just as a way to evaluate books (the paper kind...) to decide whether you want to buy them, it might not be worth enough (if used only in that capacity) to pay for. Of course, such judgments are inherently subjective. Alex From pf_moore at yahoo.co.uk Tue Dec 2 10:44:31 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 02 Dec 2003 15:44:31 +0000 Subject: notes on compilation Python with MinGW gcc References: Message-ID: "Ames Andreas (MPA/DF)" writes: > Hi, > > bokr at oz.net (Bengt Richter) writes: > >> All I get from the above (after s/3D//g) is "An error occured[sic] >> in the logger." > > sorry, it seems I don't know enough about the magic secrets of > sourceforge urls. Just go to the python patch tracker and choose > patch with id 841454 ('Cross building python for mingw32'). python.org has a SF redirector - this works: http://www.python.org/sf/841454 Paul. -- This signature intentionally left blank From oussoren at cistron.nl Tue Dec 30 13:18:17 2003 From: oussoren at cistron.nl (Ronald Oussoren) Date: Tue, 30 Dec 2003 19:18:17 +0100 Subject: build problems on Solaris 9 In-Reply-To: <20031230152830.82136.qmail@web42004.mail.yahoo.com> References: <20031230152830.82136.qmail@web42004.mail.yahoo.com> Message-ID: <8A2FB475-3AF4-11D8-8B70-0003931CFE24@cistron.nl> On 30 dec 2003, at 16:28, Rob Boyd wrote: > Hi, > > I am having problems building Python 2.3.3 on Solaris > 9, on a SunFire SPARC. I am using gcc 3.3.2, and > apparently don't have binutils (but have ld, as, ar, > and the like). I have set LD_RUN_PATH appropriately. > > During 'make', I get many warnings such as: > "WARNING: renaming "regex" since importing it failed: > ld.so.1: ./python: fatal: libgcc_s.so.1: open failed: > No such file or directory". I can still subsequently > install Python, but it is broken. > > Despite the warning, libgcc_s.so.1 is in > /usr/local/lib. Plus, I did not get these errors when > building Python 2.3.2, and it does not fail to find > libstdc++.so.5 (which fails if LD_RUN_PATH is not > set). > Using 'CFLAGS='-R /usr/local/lib ./configure ...' to configure python should help. Ronald From belred1 at yahoo.com Mon Dec 1 22:33:47 2003 From: belred1 at yahoo.com (Bryan) Date: Mon, 01 Dec 2003 19:33:47 -0800 Subject: language learning vs. process In-Reply-To: References: Message-ID: <3FCC081B.8030101@yahoo.com> Ryan Walker wrote: > Hi, > I'm getting started with python and have almost zero programming experience. > I'm finding that there are tons of tutorials on the internet -- such as the > standard tutorial at python.org -- that tell you all about the language. > That is, what are the methods, functions, modules, syntax, punctuation, etc. > No problem there! > > Meanwhile, I'm finding that there is very little (that I can find) about how > to do basic logistical things related to using python and implementing > programs. For example: how to run a program. That's pretty basic, but I > don't see anything in the tutorials about it. With IDLE, it's easy enough: > just hit F5. But working on my server via Putty, trying to get a concrete, > meaningful result, it's hit and miss. For example, I find that sometimes a > program will run if I import it. I typed "import smtpmail" and it ran -- it > asked me to input From, To, Subj, Message. Other times, I type in "import > smtpmail" and it imports but doesn't run. My server is Unix. Typing > "python smtpmail.py" doesn't do it. That seems to be what a few websites > say to do to run a program. Doesn't work for me. It returns 'File > "", line 1' and a little carrot pointing up at the 'l' in smtpmail. > I know it's on the path since I can import it. And the permissions are 755. > > Another example of a very basic problem I can't find a solution to in any > tutorial: how to log in to an SMTP server (authentication). My web > searches have turned up only a few snippets of listserv conversations > between people who already know enough about the subject that I'm not able > to divine anything from the code they pass back and forth. A search on > Python.org doesn't turn up anything that would help newcomers. > > So basically, what I'm saying is, there is a wealth of information about how > to concatenate strings and stuff like that, but I'm finding it very > difficult to get started with basic processes and logistical things. For > example, it took me longer than I care to admit to figure out how to append > the sys.path (that's actually in the tutorial but it's somewhat > inconspicuous.) > > My ideal beginner resource would be a complete, step-by-step explanation of > how to implement a simple program -- starting with typing "python" at the > command prompt and ending with some kind of concrete result. Then, with a > complete understanding of the process of writing and implementing (emphasis > on the latter) a program, my efforts to learn the content and syntax of the > language itself will be a lot more meaningful. That is, I can learn things > like what a string is and have some confidence that I'll actually be doing > something (other than playing with a calculator) that can provide something > of value to end users in far flung places. > > Might seem weird to start with learning process and implementation, since > it's all dependent to a large extent on using the language properly, but I > do think it's possible to learn implementation first (with a bare minimum of > language learning) and then go back and learn more about the language. Just > something to think about for the excellent people who teach ingrates like me > how to program. > > If anyone has any pointers on where to get more how-to information more > oriented towards process/logistics please let me know. > Thanks! > Ryan > > > > i think there is another option you aren't thinking about. you mentioned learning with standard tutorials about basic things like concatenating strings. you also mentioned that you would like to learn by writing one large program, step by step. i think there is a third option you should consider, and IMO it's the best. it's studying small fully working recipes that concentrate on one issue at a time and gives you a good foundation to build upon. fortunately, there is a book that does just this and it's called "Python Cookbook". i think if you try to go for the one big program, you will miss out on a lot of important stuff. I think there are also free online tutorials that do much the same thing such as "Dive into Python". anyways, just my opinion. bryan From fredrik at pythonware.com Tue Dec 9 02:55:08 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 08:55:08 +0100 Subject: from spam import eggs, spam at runtime, how? References: Message-ID: "Ganesan R" wrote: > > > spam = __import__('spam.eggs') > > eggs = spam.eggs > > Is there a way to do this if I don't know about "eggs" beforehand. I have > some code which needs to import a DB module dynamically. The module could be > 'PyPgSQL.PgSQL' or 'sqlite'. Is there a sane way to do this without exec? here's one way to do it: dbapi = __import__(dbname) for p in name.split(".")[1:]: dbapi = getattr(dbapi, p) notes: - when given a package, __import__ imports all components, but returns a reference to the toplevel module). - you may still need DB-specific code to connect to the database From yan at NsOeSiPnAeMr.com Sat Dec 13 07:44:00 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 13 Dec 2003 07:44:00 -0500 Subject: "Do this, and come back when you're done" In-Reply-To: <7x8ylg5252.fsf@ruckus.brouhaha.com> References: <7x8ylg5252.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Kamus of Kadizhar writes: > >>Is there any way to rewrite each half of the function to run in the >>background, so to speak, and then have a master process that waits on >>the results? This would cut execution time in half more or less. > > > Sure, use the threading module. OK, I'll read up on that. I've written gobs of scientific type code, but this OS stuff is new to me. > Think about another aspect of what > you're doing though. You're comparing the md5's of a local and remote > copy of the same file, to see if they're the same. Are you trying to > detect malicious tampering? No, actually, both machines are under my control (and in my house). I'm slinging large (1GB MOL) files around on an unreliable, slow wireless network. I am trying to detect an incomplete copy across the network. The local machine is the video player and the remote machine is the archive server. My kids have a habit of just shutting down the video server, resulting in incomplete transfers to the archives. If it's appropriate for this newsgroup, I'd like to post the entire effort for comments (it's my first bit of pyton code.) So far, python has been the easiest language to learn I've ever come across. I tried learning perl, and it was a disaster.... Too convoluted. Python is a breath of fresh air. Also, the docs and support here is excellent. :-) My thanks to all the volunteers who put in time to build python. -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From ngps at netmemetic.com Wed Dec 3 21:00:12 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 4 Dec 2003 02:00:12 GMT Subject: Asynchronous SimpleXMLRpcServer References: <3fcdd76e$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: According to Guyon Mor?e : > does the SimpleXMLRpcServer handle connection asynchronous? > if not, how can I make it asynchronous? M2Crypto has examples of XMLRPC/HTTPS server for both SocketServer and Medusa. ZServerSSL, which is bundled with it, allows XMLRPC/HTTPS calls into Zope. See URL in .sig. HTH. -- Ng Pheng Siong http://firewall.rulemaker.net -+- All Your Rulebase Are Belong To You[tm] http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From bh at intevation.de Fri Dec 19 09:26:27 2003 From: bh at intevation.de (Bernhard Herzog) Date: Fri, 19 Dec 2003 15:26:27 +0100 Subject: Broken python-model.el References: <274A369893F5FB4099345F006439D987013876D8@bella.corp.resmed.org> Message-ID: <6q3cbghoj0.fsf@salmakis.intevation.de> Skip Montanaro writes: > Peter> So I don't even know what the "trailing builtin" problem is :-) > Peter> All I know is that I don't like the way python-mode.el > Peter> (currently) tries to find shadowed builtins. I would hardly call > Peter> highlighting the "ord" in "swimrecord" as showing a shadowed > Peter> builtin :-) I found the current mechanism highly annoying to be > > The "ord" in "swimrecord" is the "trailing builtin" problem I referred to. > > Peter> honest as it distracts rather than enhances. > > Should be fixed in CVS. Let me know if it's not. One problem I'm seeing with 4.41 is that in "self.map" map is highlighted. According to the comment the builtins (kw3) should not be highlighted when they're used as attributes but the regexp matches attributes as well. I've submitted a patch: http://sourceforge.net/tracker/index.php?func=detail&aid=862952&group_id=86916&atid=581351 Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From john at landahl.org Fri Dec 19 22:40:55 2003 From: john at landahl.org (John Landahl) Date: 19 Dec 2003 19:40:55 -0800 Subject: OO issues in python References: Message-ID: Ali El Dada wrote in message news:... > so do you advise me to take the second solution, creating a class called > Global that any other class can access?? as in: (not tested) > > class Global: > user_home = os.environ['HOME'] > my_app_data = 'C:\\Program Files\\MyApp' > > class AnyClass: > self.user_home = Global.user_home Take a look at PEAK, the Python Enterprise Application Kit (http://peak.telecommunity.com/). It has advanced configuration and binding capabilities that make this sort of thing incredibly simple (and which provide far more power and flexibility), without needing to resort to singletons like your Global class. Using PEAK your AnyClass might look like this: from peak.api import binding, PropertyName class AnyClass(binding.Component): user_home = binding.Obtain(PropertyName('environ.HOME')) app_data = binding.Obtain(PropertyName('myapp.data')) binding.Obtain allows you to locate and "bind to" an object that's been created elsewhere in the program. Objects are located through "configuration keys" -- in this case dotted "property names" are used, though there are other choices which provide even more flexibility. Properties provide a simple way to organize data hierarchically (e.g. 'myapp.foo.bar.whatever') and which have a direct tie-in to external .ini config files. "environ.*" provides a simple way to lookup environment variables, and "myapp.data" could be specified in a config file like so: [myapp] data = 'C:\\Program Files\\MyApp' There's a great introductory tutorial on the PEAK DevCenter wiki: http://peak.telecommunity.com/DevCenter/IntroToPeak It walks you through creating simple applications with these features, and moves on to more advanced PEAK features that you might also find useful. From hokiegal99 at hotmail.com Tue Dec 30 11:11:35 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 30 Dec 2003 11:11:35 -0500 Subject: HDD Burn In with Python In-Reply-To: References: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> <84fc4588.0312300019.41a81615@posting.google.com> <3ff15d8a$0$318$e4fe514c@news.xs4all.nl> Message-ID: Terry Reedy wrote: > You could also get the assembly coded SpinRite5 (<$100) which will > systematically read and test every block, including boot sectors, on the > disk (moving each block of data temporarily to another place while write > testing). It also fixes bad formatting and has twice saved a disk for me > that ScanDisk could not. > > Terry J. Reedy I've used SpinRite before. An excellent piece of software, but it has a few short falls: Only works on x86. Only works on fat or fat32 filesyatems. Very, Very slow because of its throughness. Has trouble with bigish (> 60GB) HDDs. If you use Windows 98 with a fat32 filesystem on a smallish IDE based HDD... it's a great program, otherwise it's not very useful. From donald.welch.nospam at hp.com Tue Dec 30 12:55:57 2003 From: donald.welch.nospam at hp.com (djw) Date: Tue, 30 Dec 2003 09:55:57 -0800 Subject: inline References: Message-ID: <3ff1bccb@usenet01.boi.hp.com> km wrote: > Hi all, > > Does python support inline assembly ? (like C ) how can one do that in > Python ? any link to third party module ? > > kindly enlighten > thanks, > KM Not assembly, but you can embed C into Python with Weave [http://www.scipy.org/site_content/weave] (part of SciPy). -Don From bokr at oz.net Sun Dec 21 15:47:35 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Dec 2003 20:47:35 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: <696dnfQukvxHaXii4p2dnA@comcast.com> Message-ID: On Sun, 21 Dec 2003 14:30:36 -0500, "Terry Reedy" wrote: > >"John Roth" wrote in >message news:vub584opb8sd0f at news.supernews.com... >> Well, the basic idea was simply to make the () >optional for functions >> with no parameters. > >In mathematics (except in lambda calculus), there >is generally no such thing since functions >generally have no side effects and hence no-param >function = constant, and name with no parens is >same as normal name ref to constant, whether >number, function, or other mathematical object. >On the other hand, one-param functions *are* ofter >written without parens for simple args. Hence I >suspect that above would lead to the suggestion >that parens also be optional for single-arg funcs. > >The overloading of no-op juxtaposition to mean >either * or () (alternatively, the interpretation >of function * number as function(number)) is >rather cute. > >>> class MulFun(object): ... def __init__(self, f): self.f = f ... def __mul__(self, other): return self.f(other) ... >>> r = MulFun(repr) >>> r * 123 '123' >>> r * 'Happy Holidays' "'Happy Holidays'" Regards, Bengt Richter From lkcl at lkcl.net Tue Dec 16 11:16:03 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 16:16:03 +0000 Subject: rexec.py unuseable In-Reply-To: <1071587601.3fdf2111afc59@mcherm.com> References: <1071587601.3fdf2111afc59@mcherm.com> Message-ID: <20031216161603.GG17021@lkcl.net> On Tue, Dec 16, 2003 at 07:13:21AM -0800, Michael Chermside wrote: > I (Michael) wrote: > [Speaking of how to provide restricted execution in Python] > > Actually, I rather prefer the approach that has been mentioned before > > of trying to use capabilities. > > See, for instance, the threads on > > Capabilities found here: > > http://mail.python.org/pipermail/python-dev/2003-March/thread.html#33854 ta. > Luke replied: > > capabilities, acls, schmapabilities, same thiiing :) > > No... they're not. Read the thread I mentioned above, or read this, > and some of the other documentation for the language E: > > http://www.erights.org/elib/capability/ode/ode-capabilities.html no offense intended: i'll read that later, i'm running out of time. without going into too many definitions, consider what i am advocating to be _like_ an access control list but instead to be a capabilities control list, instead. a "capabilities list", where it's a list ordered on a per-caller-function-name basis [with a special wildcard function name called "absolutely everything"] > > Later Luke writes: > > btw yes you're right, it's better off called "capabilities" > > but the name CCLs - capability control lists - is a bit of > > a mouthful :) > > Again, I mean something different, NOT CCLs, but capabilities. anyone have a one-para summary of the difference between capabilities and access control lists? even if it's "access control lists are lists of capabilities" which i don't know if that's true. access control lists are typically made on a per-user basis, but what i am recommending in _this_ case is that a "user" be considered to be a *function*. so maybe i _do_ mean access control list and should stick to my guns, here :) so. is the difference between capabilities and access control lists simply that capabilities lists restrict caller-function rights and access control lists restrict user rights? > Hmm... how about a quick summary from me (but I'm not an expert). > > Suppose that had some code which had an object representing a > directory, with a method "open(filename, mode='r')" that opened > files in the directory. Given this object, you could imagine > constructing new objects with more limited capabilities. For > instance, you might create a readOnlyDirectory object which had > a method "open(filename)" that didn't allow specifying the mode > as anything but 'r'. Or you might open a file and then pass a > file object with "read()", "write()", "seek()", and other such > methods, which would only access that file. [i'll have to read this in more depth later, i'm out of time, sorry] > So _IF_ the only way to access files were through this object (and > that's a BIG if), then you could imagine a world where HAVING and > object was equivalent to being able to do something. If a bit of > code had access to a read-only-file object then it could read that > file, but couldn't write to it, or do anything else with the file > system unless it ALSO had access to some OTHER objects. That's > capabilities... and it would work for most kinds of restricted > resources, not just the file system. The key idea is that HAVING > a pointer to the object is equivalent to having the permission to > USE that object, and whatever it provides access to. [again, i'll have to read this in more depth later, i'm out of time, sorry] > There are several ways to "escape" out of this system. One way is > to access some global ability... for instance, you might use the > "open()" function from __builtins__. i would expect __builtins__.open() to have _its_ own mmm... capabilities list, and _if_ that list contained a permission for the restricted function to "execute" it, then _yes_ it would be allowed, but otherwise no, definitely not. therefore, the author of the [new] rexec.py module should simply be a matter of creating the right ACLs, and applying them. in the case of __builtins__ it could be a matter of just applying a capabilities list of one item: [("all functions and modules", DENY, "write, apply-to-sub-objects")] and that would be _it_! all functions in __builtins__ would be dealt with, and restricted! of course, i don't believe it will be _quite_ that simple, but it might. > For capabilities to work in > Python access to "dangerous" globals would need to be restricted. simple: apply a capabilities list that denies dangerous actions, on all such "dangerous" globals. OH! one important "permission" is "change acl" of course, which must be "DENIED"! > Another way is to just create an object out of nowhere, or forge > a pointer to an object. Fortunately, in Python these are already > impossible... pure Python code cannot forge references or create > objects without access to the type or class. (C extensions can > do anything and are unsafe.) that is why i mentioned about "create object" permissions [capabilities]. if there is a permission/capability whereby the capabilities list of a parent object is "inherited" when a create object action is carried out, the problem you describe is alleviated. _at_ object create time (and object create itself could be a separate permission / capability, granted on a per-function and per-module basis like everything else), the capabilities are examined. what happens is that _if_ the "inherit capabilities" flag is set, then the newly created object receives a COPY of the parent object's capabilities list. ta-da, problem solved. this is a _normal_ bog-standard approach that is used in the windows nt security model, and has been for over twenty years, now, and if you count the VAX/VMS history as well, a lot longer than twenty years. > Another way is to access the more powerful object that "empowers" > a less powerful one... perhaps using the (supposed to be private) > _directory field in the readOnlyfile object. So capabilities in > Python are impossible without some sort of private data for > objects (this is not a particularly onerous requirement). Yet > *another* approach would be to use introspection... for instance, > in Python today, given any file object, the class itself ("file") > can be obtained via introspection, and then used to create other > file objects. Using capabilities in Python would require that > "restricted" objects have some more limited form of introspection... > perhaps one could only obtain a "fake" class object which had > a __equals__ method that simulated being the real class, but > which had no __init__ so it couldn't be used to create new > instances. i don't quite follow, even after reading the capabilities thread, what introspection is. but let me try to clarify so you can correct me if necessary: introspection is the ability to go via the __XXXXX__ functions etc. including the __class__ stuff, yes? well, if i follow you correctly, you simply put a capabilities list on all those things, or you put one on the entire object. or better yet, you put an "inherited" one on the class, such that _any_ object created will receive restricted capabilities. etc. > At any rate, you get the idea. Capabilities are possible in Python > only if some sort of "restricted mode" is created, which restricts > access to some built-in abilities and which creates "restricted" > objects with some private data and limited introspection. > But IF > you had these things (and they're NOT trivial), then capabilities > may be a conceptually more elegant approach than ACLs, lleading to > more elegant programs. i believe that if you understand what i am suggesting, and i hope that filling in some examples above, i believe that what i am suggesting covers your concerns. the capabilities lists that i am recommending can be applied on a per-function and per-object basis and can be inherited. in this way, useful restrictions can be made to achieve the expected results. ... i didn't say, however, that it wouldn't require quite a lot of thought about _which_ functions to apply restricted capabilities lists to! starting, of course, with the "nothing goes" one, and repeatedly attempting to run code. l. From image9n at hotmail.com Tue Dec 9 14:29:04 2003 From: image9n at hotmail.com (Agency) Date: 9 Dec 2003 11:29:04 -0800 Subject: Nub needs help withTkinter References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> <1cca69c7.0312081017.27140c39@posting.google.com> Message-ID: <1cca69c7.0312091129.72af0e05@posting.google.com> O.K. So, I'm stuck again. I tried putting the code into a class, might not be smart given what I know, but I did it. I'm thinking that the beat, time, and bpm would each have their own class and display/label. I know that the pack() determines if something shows up. So, I'm guessing that somewhere along the line pack() is not be referenced right. My problem is that I have a window, with no label showing up. I also just noticed that there is no linkage between the beatContainer/frame and the beatNum/label. Here is the newbie code: from Tkinter import * class beatX: def _init_(self, parent): self.beatContainer = Frame(parent) self.beatContainer.pack() self.beatNum = Label(self, text = "Beat Counter : ") self.beatNum.config(text = "Beat Counter : %d" %beats) self.beatNum.pack() self.beatNum.bind("", self.beatCounter) self.beatNum.bind("", self.beatReset) def beatCounter(event): print "increment counter" beats = beats + 1 def beatReset(event): print "reset counter" beats = 0 root = Tk() root.mainloop() From tnienstedt at telesyn.com Thu Dec 4 11:24:17 2003 From: tnienstedt at telesyn.com (Ted Nienstedt) Date: Thu, 4 Dec 2003 11:24:17 -0500 Subject: stddev bug in util.py In-Reply-To: <3FCF5D0E.50500@ghaering.de> Message-ID: <001f01c3ba83$10983b00$421210ac@telesyn.corp> The code was obtained from http://aima.cs.berkeley.edu/python/utils.html Perhaps I should have made that clear -----Original Message----- From: Gerhard H?ring [mailto:gh at ghaering.de] Sent: Thursday, December 04, 2003 11:13 AM To: python-list at python.org Cc: Ted Nienstedt Subject: Re: stddev bug in util.py Ted Nienstedt wrote: > Gentlemen, et al: > > The stddev function in the current, as of 11/03, utils.py module has a > bug. Corrected code excerpt below, in red; comments in blue. [...] Thanks for informing the whole Python community of this bugfix in your software, Ted. -- Gerhard From skip at pobox.com Mon Dec 22 17:12:45 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Dec 2003 16:12:45 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <20031222213900.GC24252@unpythonic.net> References: <21bb8d55.0312221204.51d86182@posting.google.com> <16359.24377.5101.789601@montanaro.dyndns.org> <20031222213900.GC24252@unpythonic.net> Message-ID: <16359.27741.785330.856198@montanaro.dyndns.org> >>>>> "Jeff" == Jeff Epler writes: Jeff> On Mon, Dec 22, 2003 at 03:16:41PM -0600, Skip Montanaro wrote: >> How about: >> >> def howmanyatstart(s, pfx): >> return (len(s) - len(s.lstrip(pfx)))/len(pfx) >> >> ? Jeff> strip() doesn't work that way: >>>> "bbbbbbbxxx".strip("bob") Jeff> 'xxx' Skip> Then it looks like a bug in one or the other to me. I retract my statement. It's a bug in my code. help("".lstrip) shows why: lstrip(...) S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping Note the second sentence. Sorry for the flub. Skip From phil.hornby at accutest.co.uk Tue Dec 30 05:24:05 2003 From: phil.hornby at accutest.co.uk (Phil Hornby) Date: Tue, 30 Dec 2003 10:24:05 -0000 Subject: argument list In-Reply-To: <87llovi3t4.fsf@pobox.com> Message-ID: Looks like I will be calling inspect from my app - as using except TypeError: rather than using inspect won't do what I want as it is done @ runtime and I need to make the decision when initialising not when I try to call it - i.e. when I am deciding which handlers to assign to which events; this way I can hopefully minimise the number of reasons for the system stalling - because in reality if an exception is thrown from within a handler then the system needs to stop(optionally). Thanks for the suggestions peeps... Phil From mwh at python.net Mon Dec 1 13:39:08 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Dec 2003 18:39:08 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> <7x3cc4g56b.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > "Raymond Hettinger" writes: > > Not only is the lambda unattractive, it is slow. This situation is > > not unique to sort(), it comes up with other functionals like map() > > and filter(). A new itertool called groupby() also faces the same > > situation. > > > > So, the idea was born to add a fast extract function maker to the operator > > module: > > Better to improve the compiler so that lambda makes good code. Any ideas how to do that? Cheers, mwh -- > With Python you can start a thread, but you can't stop it. Sorry. > You'll have to wait until reaches the end of execution. So, just the same as c.l.py, then? -- Cliff Wells & Steve Holden, comp.lang.python From mirko-lists at zeibig.net Mon Dec 8 07:16:26 2003 From: mirko-lists at zeibig.net (Mirko Zeibig) Date: 8 Dec 2003 12:16:26 GMT Subject: __slots__ References: <9d5f9ae4.0311070836.7503de86@posting.google.com> <9d5f9ae4.0311100749.362e8cdf@posting.google.com> <653b7547.0311112052.4a7f9b3d@posting.google.com> Message-ID: On Wed, 12 Nov 2003 at 04:52 GMT, Patrick Maupin wrote: > Brad Clements wrote: > >> But nonetheless I slotted myself into a corner anyway. Now I have to undo >> all those nasty slots statements. >> >> My advice.. forget __slots__! > > One might also find, while taking this path, that the > use of __slots__ by itself makes SOME applications run > fast enough without going all the way to Pyrex. At this > point, one might reasonably conclude (despite the > oft-repeated claim that __slots__ are an un-Pythonic > "premature optimization") that the ability to avoid writing > a C extension by merely adding a single line of (basically > non-executable) code to a class or two is unalloyed goodness. Just as an info: I ran some tests using slots vs. "normal classes" vs. tuples, here are the definitions for the classes: class NoSlots(object): def __init__(self, *args): self.id, self.weight = args class Slots(object): __slots__ = ('id', 'weight') def __init__(self, *args): self.id, self.weight = args def createtuple(id, weight): return (id, weight) def create(func, count): w = timer.create("creating %s" % func) l = [ func(str(id), id*2) for id in xrange(count) ] w.stop() showMemUsage(func) return l def usetupledirectly(func, count): w = timer.create("creating %s" % func) l = [ (str(id), id*2) for id in xrange(count) ] w.stop() showMemUsage(func) return l created lot's of these and hold them in a list. I measured memory-usage very roughly using /proc/self/status (VmRSS): [mize at lxmize python]$ for i in 1000 10000 100000 ; do ./memusage_speed_tuple_vs_simple_classes.py $i; done ******************************************************************************** Creating 1000 objects MemUsage : 2780 kB MemUsage : 80 kB MemUsage : 88 kB MemUsage : 88 kB Runtime UsrTim SysTim Calls NestC PendC TimerName 0.216 0.130 0.000 1 0 0 total 0.039 0.040 0.000 1 0 0 creating 0.035 0.040 0.000 1 0 0 creating 0.019 0.020 0.000 1 0 0 creating 0.011 0.010 0.000 1 0 0 creating 0.007 0.010 0.000 1 0 0 deleting stuff, disablegc=0 ******************************************************************************** Creating 10000 objects MemUsage : 4752 kB MemUsage : 800 kB MemUsage : 860 kB MemUsage : 864 kB Runtime UsrTim SysTim Calls NestC PendC TimerName 1.351 1.230 0.020 1 0 0 total 0.438 0.440 0.000 1 0 0 creating 0.365 0.370 0.000 1 0 0 creating 0.186 0.180 0.000 1 0 0 creating 0.148 0.130 0.020 1 0 0 creating 0.100 0.100 0.000 1 0 0 deleting stuff, disablegc=0 ******************************************************************************** Creating 100000 objects MemUsage : 25160 kB MemUsage : 8528 kB MemUsage : 9308 kB MemUsage : 9308 kB Runtime UsrTim SysTim Calls NestC PendC TimerName 16.979 16.230 0.610 1 0 0 total 5.448 5.230 0.200 1 0 0 creating 4.792 4.640 0.140 1 0 0 creating 3.111 2.970 0.140 1 0 0 creating 2.805 2.670 0.130 1 0 0 creating 0.716 0.710 0.000 1 0 0 deleting stuff, disablegc=0 [mize at lxmize python]$ So while there is a big memory saving in using __slots__, the time savings I observed are relatively small. Test system is a Pentium Celeron 500MHz with 256 MB running the Python 2.2 on Linux. Of course never trust measurements you didn't manipulate yourself ;-). Regards Mirko From andreif at mail.dntis.ro Wed Dec 24 04:48:46 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 24 Dec 2003 01:48:46 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> Message-ID: <21bb8d55.0312240148.5d1bbaa3@posting.google.com> Jp Calderone wrote in message news:... > On Tue, Dec 23, 2003 at 12:54:39PM -0800, Stormbringer wrote: > > Jp Calderone wrote in message news: 189772.684.python-list at python.org>... > > > On Tue, Dec 23, 2003 at 04:35:50AM -0800, Stormbringer wrote: > > > > Hi, > > > > > > > > I want to implement a fulltext search for messages in a forum. More > > > > exactly for each message I store pairs (wordId, msgId) for each > > > > identified word and when I search something I want to be able to > > > > retrieve very quickly all msgId for a given wordId. > > > > > > > > > > A pure Python fulltext indexer - http://divmod.org/Lupy/index.html > > > > Thanks ! This is exactly what I needed, and the size of the indexes is > > around 30%, much much less than what I could have achieved with my > > code. Not to mention the fact that I get phrase search and some other > > goodies :) > > > > The only thing that bothers me a little is the speed for building the > > index, I tried with around 5000 messages and I am not quite thrilled, > > it's not extremly slow but it has to be faster for what I need. > > Perhaps I'll use the C++ version with some Python bindings. > > > > Yea, I hear that. Work is being done on speeding it up (pretty much the > only development on it now is optimization). I don't know how it will end > up, but things look promising so far. On the other hand, if you don't want > to wait for that to be finished... Well - that depends. If there will be a faster version of lupy when I'll really need it in 1-2 months then I will use that. Else if I can find a faster equivalent I will use that. Just beeing practical. Andrei From none at none.net Mon Dec 22 14:53:59 2003 From: none at none.net (Iwan van der Kleyn) Date: Mon, 22 Dec 2003 20:53:59 +0100 Subject: manpage of python 2.3? In-Reply-To: References: <3fe63429$0$242$e4fe514c@news.xs4all.nl> <3FE728A7.7030608@none.net> Message-ID: <3FE74BD7.60303@none.net> km wrote: >>Of course, you could use links/lynx to view Python's excellent html >>documentation from the console. > may be excellent but not as comfortable as of Perl documentation on the system. well thats a poor feature of Python. It depends a bit on taste and custom, I guess. On Debian it's a matter of: ~# apt-get -t unstable install python2.3-doc (install documentation) ~# links /usr/share/doc/python2.3-doc/html/index.html (et voila) For me pydoc is an indispensible tool searching through the Python documentation, added with the Python Docs as generated by epydoc (epydoc.sourceforge.net). On Windows you have the docs in the searchable HTMLHelp format. On other platforms you could run an indexing tool on the docs (i.e. htdig). -- That brings up a thought: I would have expected pydoc to come with a search facility for the Python docs. Has this ever been attempted? Regards, Iwan From sam at h41n2fls31o839.telia.com Mon Dec 22 11:03:03 2003 From: sam at h41n2fls31o839.telia.com (Samuel Kleiner) Date: Mon, 22 Dec 2003 10:03:03 -0600 Subject: Operator overloading and __getattr__ Message-ID: I'm trying to create methods on method access- but __getattr__ fails with operator overloading(below) Any suggestions? EG: class NewM(dict): def __getattr__(self,name): def fi(m): if type(name) in self: self[type(name)]=self[type(name)].__dict__[name](m) else: self[type(name)]=m return fi p=int(2) s=NewM() print p.__add__(2) print s.__add__(2) print p+2 print s+2 Causes TypeError on the last line -- "I know, there is no Nobel Prize in preternatural biology. That's because Alfred Nobel's wife was seduced by a vampire." --Andrew Plotkin From dw-google.com at botanicus.net Sat Dec 20 12:43:43 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 20 Dec 2003 09:43:43 -0800 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: <99dce321.0312200943.576c9606@posting.google.com> Ville Vainio wrote... > I don't know if you have seen this before, but here goes: > > http://text.userlinux.com/white_paper.html > > There is a jab at Python, though, mentioning that Ruby is more > "refined". I read a lot of that last night, and I find it intriguing. It strikes me as being misdirected on a number of fronts, but that's Linux talk so I'll skip it here. I find his rationale for using Python to be poor. It is lumped between two bullets for 'Mail Transfer Agent' and 'Java-like environment'. His reasoning for using Python is terse - essentially because he couldn't use Ruby. Maybe he was typing this up in a rush, but regardless. The reasons he has given for making Python the primary 'interpretive'(wtf?) language are unclear. I could think of a hundred reasons for it, but that's not my job, it's his. I wouldn't call what he said a jibe, given that he shows no understanding of what Python is about. If he isn't or hasn't been an enlightened one, then how can he insult us? :) David. From johnk at aurema.commercial Mon Dec 1 22:31:03 2003 From: johnk at aurema.commercial (John Ky) Date: Tue, 2 Dec 2003 14:31:03 +1100 Subject: Conflicting gethostname function definition on Solaris 9 References: <1069977306.415163@cousin.sw.oz.au> Message-ID: <1070335876.873683@cousin.sw.oz.au> To work around this, I had to do two things: 1. not defined "SOLARIS" 2. put "python.h" first in the header file. "John Ky" wrote in message news:1069977306.415163 at cousin.sw.oz.au... > Hello: > > Building Python works fine. Now I am trying to build my own python > module on Solaris 9, but I'm getting the following conflict: > > In file included from > /wrk/src/test/tools/local/include/python2.2/Python.h:62, > from elxml.cpp:20: > /wrk/src/test/tools/local/include/python2.2/pyport.h:333: declaration > of C function `int gethostname(char*, int)' conflicts with > /usr/include/unistd.h:274: previous declaration `int gethostname(char*, long > unsigned int)' here > > Did I do something wrong? > > Thanks > > -John From spiffy at worldnet.att.net Tue Dec 9 19:27:06 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Wed, 10 Dec 2003 00:27:06 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> <2fsBb.423999$0v4.20388116@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Diez B. Roggisch" wrote in message news:br5k2i$a6s$02$1 at news.t-online.com... > >> > filename = "C:\Python22\Canyon.mid" > >> > os.system("C:\Python22\playb.exe%s"%filename) > >> > ...this causes a dos box to appear which promptly hangs and does > > nothing, > >> > at which time Python stops responding. Vartiations on this will cause > > the > >> > dos box to appear with the message "Bad command or file name". > >> > > >> > >> Looks like there is a space missing - > >> > >> os.system("C:\Python22\playb.exe %s"%filename) > >> ^ > >> > >> Diez > >> > > There is no space missing. That is the name of the file on my comp. > > Ok, most probably you'll start to yell at me now, but _there is a space > missing_: > > >>> filename = "C:\Python22\Canyon.mid" > >>> print "C:\Python22\playb.exe%s"%filename > C:\Python22\playb.exeC:\Python22\Canyon.mid > > I have no WinBox here - but I bet even windows likes its commandline > arguments somehow separated from each other. Try executing the line above, > and I bet command.com complains about "Bad command or file name". > > Diez > > ...why would i yell at you? you are trying to help and i appreciate that. Unfortunately, I have tried various spacings both in the filename and the os.system call and what happens most often is that a dos box appears and hangs and python stops responding. From __peter__ at web.de Mon Dec 29 08:54:25 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Dec 2003 14:54:25 +0100 Subject: strftime - %a is always Monday ? References: <282f826a.0312290503.398d72cd@posting.google.com> Message-ID: Richard Shea wrote: > Hi - I'm trying to use strftime to output the day of the week but I > find that I always get told it's Monday. I have tried day, month, year > etc and all come out correctly but as soon as I use %a I get 'Mon'. > I'm running Python 2.3.2 on a Windows 98 machine. Can anyone suggest > what the problem might be please ? > > This is a segment of the code which is manfests the behaviour ... > >>>> from time import localtime,strftime,time >>>> lst1 = ['2003','12','27'] >>>> strftime("%A,%d (%w %y > %m)",[int(lst1[0]),int(lst1[1]),int(lst1[2]),0,0,0,0,0,0]) > 'Monday,27 (1 03 12)' >>>> > > ... whereas the 27th was a Saturday ? Garbage in garbage out. Only the 7th element of the tuple is used to generate the string: >>> for wd in range(7): ... print time.strftime("%a", (0,0,0,0,0,0,wd,0,0)) ... Mon Tue Wed Thu Fri Sat Sun The cleanest solution uses the new datetime module instead: >>> import datetime >>> datetime.date(2003, 12, 27).strftime("%a") 'Sat' >>> Peter From paulp at ucla.edu Tue Dec 9 16:53:24 2003 From: paulp at ucla.edu (Paul Phillabaum) Date: Tue, 9 Dec 2003 13:53:24 -0800 Subject: closing file opened by csv reader Message-ID: I'd like to close the file the "reader" opens, but I can't figure out how to reference it. example: reader2=csv.reader(file('blah.csv')) if reader2 was a normal file, I would do "reader2.close()" but that doesn't work. I won't show any of the more wacky attempts I made based on my limited experience as they'd just reveal my total ignorance of this part of python. I did look through the dictionary for the reader object but couldn't find what I needed. Thanks! Paul From andymac at bullseye.apana.org.au Tue Dec 30 00:00:36 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 30 Dec 2003 16:00:36 +1100 (EST) Subject: [Mailman-Developers] python is slow In-Reply-To: References: <3FE20578.7060402@gmx.at> <1072458360.4458.13.camel@anthem> Message-ID: <20031230155404.W58893@bullseye.apana.org.au> On Mon, 29 Dec 2003, Michael Hudson wrote: > "John Roth" writes: {...} > > and then it's improved from there. 2.3, for example, is quite a bit > > faster than 2.2. > > I know -- I'm partially responsible for that :-) (although only if you > don't run python -O). And much appreciated too! In conjunction with the changeover to using PyMalloc by default, courtesy of the TimBot, the apparent gain is decidely noticeable. Pity that the startup phase took a hit, which impacts some usage (eg CGI scripting) negatively in spite of the gains once the interpreter is running :-( -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From gherron at islandtraining.com Mon Dec 1 18:44:52 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 1 Dec 2003 15:44:52 -0800 Subject: Looking for a Python accessible OS framework. Message-ID: <200312011544.52502.gherron@islandtraining.com> Hi, I'm going to be teaching an Operating Systems course in a Computer Science department of a nearby college. I'm currently searching around for interesting programming projects for the students. It is my hope (and of course the reason I'm posting to this list) that I can have the students program in Python and access some framework that allows the exploration of various OS topics. So even though this is more of an operation system question than a Python question, I though I'd start here and see if anyone knows of an OS teaching framework that could be accessed from Python. I do SWIG competently well, so I'd be able to create the interface. In my search of the web, I did find one possibility, called RCOS, at http://cq-pan.cqu.edu.au/david-jones/Projects/rcos/index.html, but it seems to have gone inactive about six years ago while converting from from C++ to Java. Thanks for any pointers, Gary Herron From anton at vredegoor.doge.nl Wed Dec 17 11:39:52 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Dec 2003 17:39:52 +0100 Subject: Converting integer to binary representation References: <3fe04d14$0$127$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <3fe0879e$0$3323$3a628fcd@reader2.nntp.hccnet.nl> anton at vredegoor.doge.nl (Anton Vredegoor) wrote: > >>> list(10) > >>> [True,False,True,False] Sorry, I was dead wrong here, or maybe not, it all depends on the future. The code below here would make the positions of the booleans correspond to the powers of two: >>> list(10) >>> [False,True,False,True] But the other interpretation has some merit too since it corresponds to the way we use strings to denote numbers. There is a choice between left-to-right and right-to-left here, analogous to the "most significant bit" issue. Because these interpretations are more or less equally valid, there is no obvious way of doing it. Making an explicit choice here would be good since that would remove the ambiguity. Guido could use his time machine to make one of these alternatives the obvious way to do it. Anton From dave at pythonapocrypha.com Mon Dec 29 15:26:30 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 29 Dec 2003 13:26:30 -0700 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: <03df01c3ce4a$0b68b8a0$6401fea9@YODA> Thomas wrote: > On Sun, 28 Dec 2003 14:28:42 +0100, Pjer Holton wrote: > > > > If I were to build a Windows application that is a true standard Windows > > application in every conceivable way and that adheres to the MS Windows > > standards as much as possible (installation, GUI, printing, registry, RTF > > etc.), and if portability to other platforms is only a minor concern, ... > > would Python be a good choice? > > > > In your situation (i.e. trying to build a Windows application which > is "standard in every conceivable way"), I would not use Python. Why? -Dave From http Sat Dec 6 07:03:40 2003 From: http (Paul Rubin) Date: 06 Dec 2003 04:03:40 -0800 Subject: newbie list question References: Message-ID: <7xsmjyi25f.fsf@ruckus.brouhaha.com> Kamus of Kadizhar writes: > I want to remove those elements that are in the sub-lists of fav that > also appear in the corresponding sub-list of oldfav: > > I can hack this up using C-style indexes, but I have to imagine there > is some neat python way that eliminates indexes altogether. Does this work? difffav = [[f for f in new if f not in old] for new,old in zip(fav,oldfav)] From francisgavila at yahoo.com Sun Dec 7 12:59:51 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 7 Dec 2003 12:59:51 -0500 Subject: New inited instance of class? References: Message-ID: Aahz wrote in message ... >In article , >Francis Avila wrote: >> >>If you're curious, look in the Python Language Reference at the old >>and new style classes to see the differences. There's absolutely no >>advantage to old style classes, so stop usin' 'em. > > In addition to the factors Fredrik mentioned, I responded to those concerns separately. >there's >also the issue that new-style classes are more of a moving target WRT >syntax and semantics; for complex uses, it can be tricky (or impossible) >to get the same code working the same way on both 2.2 and 2.3. True, but if you are coding for both 2.2 and 2.3, you have to avoid a great deal more than new-style classes (but, what changed besides the mro?). If we're worried about compatability with pre-2.2, shouldn't we not be using __class__ either? Barring trying to get code running on 2.2, it seems we should be coding for new-style classes where possible, and it's possible almost everywhere. Classic classes are on their way out, and eight more keystrokes now means fewer headaches later. >More than that, you *can't* use new-style classes for exceptions. Exceptions should be derived from Exception or a subclass thereof, so whether they're new- or old-style is not an issue. When Python supports new-style class exceptions, Exception will be changed to reflect that. >So >please stop telling people to avoid classic classes. Someone better tell Alex Martelli, too, because IIRC he is far more gung-ho on using new-style classes absolutely everywhere than I am. I believe he said the only time he uses them is when he forgets to type (object), which is about where I'm at. -- Francis Avila From wtrenker at shaw.ca Sun Dec 21 10:39:43 2003 From: wtrenker at shaw.ca (William Trenker) Date: Sun, 21 Dec 2003 15:39:43 +0000 Subject: Using weakref with execfile? Message-ID: <20031221153943.3a6e4a20.wtrenker@shaw.ca> I'm trying to use a weak reference with execfile, if that even makes sense. The following snippet produces an execption: Python 2.3.2 (#1, Oct 27 2003, 10:19:56) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> d=weakref.WeakKeyDictionary() >>> execfile('x.py',d) Traceback (most recent call last): File "", line 1, in ? TypeError: execfile() argument 2 must be dict, not instance I've read the weakref docs. I thought maybe the weakref.ref or weakref.proxy functions might be needed but they also return their own types which are, of course, not "dict" and so make execfile unhappy. Am I doing something wrong with weakref, or is it even possible to use a weak reference dict with execfile? Thank you, Bill From hwlgw at hotmail.com Sat Dec 27 06:27:54 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 03:27:54 -0800 Subject: Project dream References: Message-ID: > [Brandon J. Van Every] > Will, are you aware that I'm beginning exactly this project? Well, not the > twisted bit, I don't even know what that is or why one would want it. > Please see my post "ProtoCiv: porting Freeciv to Python." I'd be interested > in your feedback even if my project goals don't match yours. I have that posting saved somewhered, rather too expensive to read online (telephone). Will do. > > ... > There's Umbra. http://kuoi.asui.uidaho.edu/~kamikaze/Umbra/ Graphics and > gameplay aren't great, but it is something to start with. Thanks for the link, going to look at it. > If you go to http://www.thangorodrim.net/ and search with the keyword > "Python," you will find some roguelikes that claim to have various amounts > of Python support in them. I haven't chased any of these down myself > though. At some point I gave up on the "do a RPG" project excuse, opting > instead for 4X TBS because it's more directly applicable to my Ocean Mars > project. I don't know what TBS is. Can you show something of the Ocean Mars project, link, screenshots? From jan at jandecaluwe.com Wed Dec 10 04:41:52 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Wed, 10 Dec 2003 10:41:52 +0100 Subject: cell object dereferencing In-Reply-To: <3FD5FD4A.9060406@jandecaluwe.com> References: <3FD5FD4A.9060406@jandecaluwe.com> Message-ID: <3FD6EA60.2000905@jandecaluwe.com> Jan Decaluwe wrote: > Is there a way to dereference a cell object (that is, get > the object that it references to) in Python? I got the following response from Samuele Pedroni. I'll repost this first, and then start thinking about it :-) -- [I was reading the news group through google, feel free to repost this] well you can write a C extension or use this hack (it's a huge hack but it is safe and does the trick): def proto_acc(v=None): def acc(): return v return acc acc0 = proto_acc() import new make_acc = lambda cell: (new.function (acc0.func_code,acc0.func_globals,'#cell_acc',acc0.func_defaults,(cell,))) def cell_deref(cell): return make_acc(cell)() # usage def g(x,y): def f(): return x,y return f f=g(1,2) f_cells_by_name = dict(zip(f.func_code.co_freevars,f.func_closure)) print cell_deref(f_cells_by_name['x']) print cell_deref(f_cells_by_name['y']) regards. -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From skip at pobox.com Mon Dec 22 15:07:44 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Dec 2003 14:07:44 -0600 Subject: any one used googles api? In-Reply-To: References: Message-ID: <16359.20240.266135.569338@montanaro.dyndns.org> Bill> This works well. It is a cool package. Bill> Like a lot of modules in Python. It reduces the problem to a Bill> trivial level. Great way to be productive quickly but does not Bill> convey much understanding of problem. Sure it does. Study the source. ;-) There are probably many less productive ways to spend your time than studying Mark Pilgrim's code as well. Skip From shuvit at 127.0.0.1 Mon Dec 1 23:04:50 2003 From: shuvit at 127.0.0.1 (David MacQuigg) Date: Mon, 01 Dec 2003 21:04:50 -0700 Subject: language learning vs. process References: Message-ID: <0h3osv4ck1e2ciev3np84pl87qr8ti0648@4ax.com> On Mon, 1 Dec 2003 21:09:31 -0500, "Ryan Walker" wrote: [...] >If anyone has any pointers on where to get more how-to information more >oriented towards process/logistics please let me know. Chapter 1 of "Learning Python" by Mark Lutz is excellent. Starting on page 10 with "How to run Python Programs", the rest of the chaper is all about running from the command line, setting environment variables, startup scripts, etc. The only thing missing in the way of "operational details" is IDLE. You should definitely work through the tutorial on that tool. -- Dave >Hi, >I'm getting started with python and have almost zero programming experience. >I'm finding that there are tons of tutorials on the internet -- such as the >standard tutorial at python.org -- that tell you all about the language. >That is, what are the methods, functions, modules, syntax, punctuation, etc. >No problem there! > >Meanwhile, I'm finding that there is very little (that I can find) about how >to do basic logistical things related to using python and implementing >programs. For example: how to run a program. That's pretty basic, but I >don't see anything in the tutorials about it. With IDLE, it's easy enough: >just hit F5. But working on my server via Putty, trying to get a concrete, >meaningful result, it's hit and miss. For example, I find that sometimes a >program will run if I import it. I typed "import smtpmail" and it ran -- it >asked me to input From, To, Subj, Message. Other times, I type in "import >smtpmail" and it imports but doesn't run. My server is Unix. Typing >"python smtpmail.py" doesn't do it. That seems to be what a few websites >say to do to run a program. Doesn't work for me. It returns 'File >"", line 1' and a little carrot pointing up at the 'l' in smtpmail. >I know it's on the path since I can import it. And the permissions are 755. > >Another example of a very basic problem I can't find a solution to in any >tutorial: how to log in to an SMTP server (authentication). My web >searches have turned up only a few snippets of listserv conversations >between people who already know enough about the subject that I'm not able >to divine anything from the code they pass back and forth. A search on >Python.org doesn't turn up anything that would help newcomers. > >So basically, what I'm saying is, there is a wealth of information about how >to concatenate strings and stuff like that, but I'm finding it very >difficult to get started with basic processes and logistical things. For >example, it took me longer than I care to admit to figure out how to append >the sys.path (that's actually in the tutorial but it's somewhat >inconspicuous.) > >My ideal beginner resource would be a complete, step-by-step explanation of >how to implement a simple program -- starting with typing "python" at the >command prompt and ending with some kind of concrete result. Then, with a >complete understanding of the process of writing and implementing (emphasis >on the latter) a program, my efforts to learn the content and syntax of the >language itself will be a lot more meaningful. That is, I can learn things >like what a string is and have some confidence that I'll actually be doing >something (other than playing with a calculator) that can provide something >of value to end users in far flung places. > >Might seem weird to start with learning process and implementation, since >it's all dependent to a large extent on using the language properly, but I >do think it's possible to learn implementation first (with a bare minimum of >language learning) and then go back and learn more about the language. Just >something to think about for the excellent people who teach ingrates like me >how to program. > >If anyone has any pointers on where to get more how-to information more >oriented towards process/logistics please let me know. >Thanks! >Ryan > > > From dw-google.com at botanicus.net Sun Dec 14 01:12:36 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 13 Dec 2003 22:12:36 -0800 Subject: Shell quoting as part of the standard library? References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: <99dce321.0312132212.6cb379ff@posting.google.com> Peter Otten <__peter__ at web.de> wrote... > >>> from commands import mkarg > >>> mkarg("one silver $") > " 'one silver $'" > >>> mkarg("one's own $") > ' "one\'s own \\$"' I don't get it. I just don't get it. I'm really starting to doubt I have any initiative whatsoever. :) Ok, yet another mystery "why hasn't python got that" solved. Thanks! David. From vze4rx4y at verizon.net Fri Dec 5 07:06:38 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 05 Dec 2003 12:06:38 GMT Subject: Yet another newbie question - standard or built-in methods References: Message-ID: [Kamus of Kadizhar] > OK, I've been playing with the snippets of code posted earlier. > > Among them are things like > > allmovies[movie] = allmovies.get(movie, 0) + 1 > > From reading the docs, I've gathered that the '.get(xxx,yyy)' part is a > method that operates on the dictonary allmovies. (Sorry if I have the > terminology wrong). > > But nowhere can I find a list of 'standard' or 'built-in' methods, or > methods that can be used with various variable classes. What exactly > does 'get' do? This seems to be so basic to python that it's not > explained anywhere, but that's no help to me.... Is there a list with > explanations somewhere? I've been through the tutorials and guides, and > all just start using these with no explanation of what they do and how > they work. > > Maybe I've missed it somewhere; just point me to the right FM, so I can > RTFM. http://www.python.org/doc/current/lib/typesmapping.html Raymond Hettinger From nospam at freeworld.fr Mon Dec 29 16:54:28 2003 From: nospam at freeworld.fr (Lucas Branca) Date: Mon, 29 Dec 2003 21:54:28 GMT Subject: mod_python has empty POST Message-ID: python 2.1.3 Debian woody Apache 1.3.26 mod python 2.7.8 ## ---- formtest.html ---- ##
    ## ---- formtest.py ------ ## import mod_python def main(req): form = mod_python.util.FieldStorage(req).list vars = '' for field in form: if isinstance(field, mod_python.util.Field): vars = "%s [%s] = %s" % (vars, field.name, field.value) return(vars) ## ---- results ---- ## if method is "POST" variable form is an empty list !!! <---- WRONG if method is "GET" it's all right and I receive a string containing : "[action] = go [hide] = A" why I cannot access POST variables????? ... I'm bouncing like a ball .... help! Lucas From http Sat Dec 20 02:33:55 2003 From: http (Paul Rubin) Date: 19 Dec 2003 23:33:55 -0800 Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> <7xekv0b0cf.fsf@ruckus.brouhaha.com> Message-ID: <7xad5o7xjw.fsf@ruckus.brouhaha.com> Carl Banks writes: > But I hope the reason you want this is because it's less surprising, > more intuitive, more useful, or whatnot, and not just because Common > Lisp did it that way. Because people who can't see the side of any > computer programming argument except in the context of Common Lisp are > just pathetic. It avoids the need for ridiculous kludges to check whether there is a real arg there or not, etc. I'd prefer that Python had used the CL method in the first place since I find the Python method bizarre and counterintuitive. However, changing it now would introduce incompatibility that's harder to justify. So we probably have to live with it. From mcfletch at rogers.com Mon Dec 29 14:33:50 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 29 Dec 2003 14:33:50 -0500 Subject: Installing PyOpenGL - can't find libnumarray module In-Reply-To: References: Message-ID: <3FF0819E.2010303@rogers.com> Steven Gutstein wrote: >This is probably a fairly newbie type problem, but I'm trying to use >PyOpenGL, and don't seem to have installed it correctly. > > ... >ImportError: No module named libnumarray > > ... >The main problem seems to be the lack of a libnumarray module. However, > >I have already installed numarray, and have verified that it's in my >sys.path: > > Well, if you format this somewhat differently, yes, it's the problem. PyOpenGL currently requires NumPy (as distinct from NumArray). I haven't had the time to track down what's broken in the PyOpenGL/NumArray interface (I gather NumArray is supposed to be compatible with NumPy at some level, as it gets to the point of crashing when people attempt to use this setup, but I don't know whether that's supposed to be a binary compatibility or not). Basically, to fix the problem, uninstall NumArray and install NumPy 23.0. HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From tzot at sil-tec.gr Tue Dec 30 07:30:50 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Dec 2003 14:30:50 +0200 Subject: Some optimization tale References: <0gf0vv4o95ql695fkgemodebdlgvvsh7u7@4ax.com> Message-ID: <3fr2vvo7ubmgkuo7u5s7cf90fh8ge34l12@4ax.com> On Mon, 29 Dec 2003 17:08:39 +0100, rumours say that Stephan Diehl might have written: >> You might also want to read: >> >> http://www.python.org/sf/681780 > >Terry's solution is much faster (at least on my test set) and, as an >additional benefit, is the easiest to understand. Yep, I believe clarity is essential in the library (and that is why my patch was obviously not accepted :) Actually IIRC (it's been a long since) that code never compares more than once prefixes that have been found equal and does not create slices (used buffer() and then switched to startswith() for future compatibility), that is why it's a little complicated. The main loop runs math.ceil(math.log(N,2)) times, where N is min([len(x) for x in argument_list]). Anyway, perhaps Terry or you should update the SF patch so that os.path.commonprefix becomes faster... the point is to benefit the whole Python community, right? :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From fredrik at pythonware.com Sat Dec 13 06:43:49 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Dec 2003 12:43:49 +0100 Subject: Building problem References: Message-ID: Lucas Raab wrote: > I've downloaded a set of modules and when using the MS-DOS prompt: python > setup.py build (or install) the following message appears: > > error: Python was built with version 6 of Visual Studio, and extensions need > to be built with the same version of the compiler, but it isn't installed. > > Has anyone else seen this problem? If you have, any feedback would be much > appreciated. the message means exactly what it says. if you have version 6 of visual studio on your machine, try firing up the studio once before running the setup.py script again. if you don't have version 6, you either need to upgrade, find binary versions of the modules, or get a python built with a compiler you have. From remco at localhost Tue Dec 23 04:15:24 2003 From: remco at localhost (remco) Date: Tue, 23 Dec 2003 10:15:24 +0100 Subject: Flat file database References: Message-ID: <3fe807c7$0$230$e4fe514c@news.xs4all.nl> "Art Decco" wrote: > >Is there any Python module designed to simplify the use of a plain text file >as a flat file database? > >I realize that's a bit vague, but I'm just wondering about the best approach >for creating a little database-backed CGI app using Python on a server with >no real database available. The server belongs to the ISP, and I don't get >to install "real" software, but they do have a cgi-bin directory for me, and >they do have a relatively recent Python, so I've got Python cgi apps working >via "#!/usr/local/bin/python". I can get the apps to write and read plain >text files right in the cgi-bin directory, too, so I can use that as a >simple, flat file database. > >Now, the question is, do I write all the database >access/update/sort/search/etc. features myself, or is there some Python >module that has implemented some useful functions that I should build on. >I'm pretty new to Python (though not to programming), so if there's a >standard way most skilled Pythonistas would approach something like this, >I'd like to know what it is. And if there's something that goes beyond flat >file and has some relational support as well, all the better. > >Thanks for any suggestions. > You could see if the Berkley db is available (bsddb module). The Berkley DB is normally builtin. It behaves like a dictionary, and is therefore simple and straightforward. Cheers, Remco Boerma From http Thu Dec 18 09:38:04 2003 From: http (Paul Rubin) Date: 18 Dec 2003 06:38:04 -0800 Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: <7xekv2qjhv.fsf@ruckus.brouhaha.com> Carl Banks writes: > It seems that most people who haven't thought about time of evaluation > tend to expect it to be evaluated when the function is called; I know > I would expect this. (I think I even made the mistake.) The principle of least astonishment then suggests that Python made a suboptical choice. From e97_far at e.kth.se Tue Dec 9 19:52:24 2003 From: e97_far at e.kth.se (Fredrik Arnerup) Date: Wed, 10 Dec 2003 01:52:24 +0100 Subject: Pygtk, libglade References: Message-ID: <87llplpk8n.fsf@e.kth.se> Vams writes: > > Problem: > ---------- gtk.main() ------------- > The GUI won't show up w/o calling this function. And if I do call > this function, the control of my program will stay in the mainloop > until it exists (GUI closes). This stops the daemon from doing what > it normally does. > > So, what do I need to do? Should I have the gtk.main() in its own > thread or something? Or can I somehow extend the gtk.main() so that > it does my program's tasks while keeping an eye on the GUI? I don't know if running mainloop in separate thread is a good idea. I suggest running your main program in a separate thread. (See the faq on threading: http://www.async.com.br/faq/pygtk/index.py?req=index) An alternative is to use gtk.timeout_add() to call the main program at regular intervals. -- Fredrik Arnerup From tjreedy at udel.edu Sun Dec 28 17:50:07 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Dec 2003 17:50:07 -0500 Subject: Help, multidimensional list References: Message-ID: "Christopher Koppler" wrote in message news:jbrtuvg9fh5e0hdj0d6vseo7287r94sa7d at 4ax.com... > On Sun, 28 Dec 2003 14:27:41 +0000, Crawley > wrote: > > >Im trying to create a list of lists and for some reason its not working: > > > >class Tile: > > _next = { 'n':None, 'ne':None, 'e':None, 'se':None, 's':None, > >'sw':None, 'w':None, 'nw':None } > > > > > >def blankGridCanvas( maxx, maxy ): > > grid = [] > > for y in xrange( 0, maxy ): > > yline = [] > > for x in xrange( 0, maxx ): > > t = Tile() > > if y != 0: > > t._next[ 'n' ] = grid[ y - 1 ][ x ] > > t._next[ 'n' ]._next[ 's' ] = t > > > > yline.append( t ) > > grid.append( yline ) > > > > for y in xrange( 0, maxy ): > > for x in xrange( 0, maxx ): > > print grid[ x ][ y ], grid[ x ][ y ]._next > > return grid > > > >now by my reconing this should be a list of lists with each element being > >an instance of Tile, > > You only create a *class* Tile, and provide no way to create > *instances* of it No, the line 't=Tile()' does create a separate Tile for each grid position. However, there is only one class attribute shared by all instances. > - so much like with static variables in other > languages, you only have one 'instance' here. To be able to create > separate instances, you need a constructor in your class to > instantiate every instance, like so: > > class Tile: > def __init__(self): > self._next = { 'n':None, 'ne':None, 'e':None, 'se':None, > 's':None, 'sw':None, 'w':None, 'nw':None } You do not need __init__ for separate instances, but do need it to give each instance its own map. > and some references being manipulated to point to each > >other. But strangly no, its actually a list of lists where each element is > >the SAME instance of Tile, so I change one, i change them ALL! As stated above, you do have separate instances but only one map attached to the class instead of a separate map for each instance. Koppler's __init__ will fix this. Terry J. Reedy From bkc at Murkworks.com Thu Dec 18 11:52:14 2003 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 18 Dec 2003 11:52:14 -0500 Subject: RELEASED Python 2.3.3 (release candidate 1) - custom Py_Initialize() References: <02ae01c3c53b$778bf870$0201010a@kret> Message-ID: _ "Wiktor Sadowski" wrote in message news:02ae01c3c53b$778bf870$0201010a at kret... > For one of our clients we created pymozilla.exe to run packed > websites(zipped html,xml,css,images and python "cgi" files) > It's pretty cool. :-) > I'd like to find out more about pymozilla.. It sounds very interesting From bdesth.tagada at tsoin-tsoin.free.fr Wed Dec 17 18:41:05 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Thu, 18 Dec 2003 00:41:05 +0100 Subject: Zen of ... In-Reply-To: References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: <3fe0e547$0$24039$626a54ce@news.free.fr> Gerrit Holl wrote: > Tim Churches wrote about the Zen of Python: > >>It is entirely possible to do programming in Perl, but the results bear >>little resemblance to these desiderata. > > > Ok. > > So the Zen of Python shouldn't *be called* the Zen of Programming. "the name of this song is called..." > But shouldn't it *be* the Zen of Programming? ;) > > Can the Zen be used as a programming-guide, rather than a > language-design guide? Well... Each time I program with , I *do* have to stay really, really zen !-) Zen is best used as a way of life... Bruno From has.temp at virgin.net Thu Dec 4 13:48:19 2003 From: has.temp at virgin.net (has) Date: 4 Dec 2003 10:48:19 -0800 Subject: Separation of content and code for web (was Re: Python for web?) References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> <73c38014.0312030233.1c051da5@posting.google.com> Message-ID: <73c38014.0312041048.786b8553@posting.google.com> Richie Hindle: > Different Hamish - apparently you Hamish types like to lie in wait and > then reply in groups as well. 8-) Gakk! Guess who slept through the "Namespaces 101" class? ;p Jay O'Connor > Frell..I have a class I developed that I use regularly called > "HTMLTemplate". I should probably change the name... Heh... Google already returns 5,780 matches for the name - doubt one more'll make a difference. :) has From bokr at oz.net Sun Dec 21 16:51:33 2003 From: bokr at oz.net (Bengt Richter) Date: 21 Dec 2003 21:51:33 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: On Sun, 21 Dec 2003 10:23:29 +0100, Peter Otten <__peter__ at web.de> wrote: >Jarek Zgoda wrote: > >> Anyway, isn't that function always returns value, even without explicit >> "return" statement? > >>>> import dis >>>> def f(): >... return 123 >... >>>> dis.dis(f) > 2 0 LOAD_CONST 1 (123) > 3 RETURN_VALUE > 4 LOAD_CONST 0 (None) > 7 RETURN_VALUE >>>> def g(): >... raise Exception >... >>>> dis.dis(g) > 2 0 LOAD_GLOBAL 0 (Exception) > 3 RAISE_VARARGS 1 > 6 LOAD_CONST 0 (None) > 9 RETURN_VALUE >>>> def h(): pass >... >>>> dis.dis(h) > 1 0 LOAD_CONST 0 (None) > 3 RETURN_VALUE >>>> > >So Python always appends a > >return None > >statement at the end of a function. >Of course that doesn't mean that it will be executed. Since the latter is the case much of the time, and since then it is just unoptimized convenience-boilerplate, maybe a single-byte RETURN_NONE byte code could be introduced? Regards, Bengt Richter From afriere at yahoo.co.uk Sun Dec 14 19:35:06 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 14 Dec 2003 16:35:06 -0800 Subject: intro to python books References: Message-ID: <38ec68a6.0312141635.2cfd385a@posting.google.com> Kamus of Kadizhar wrote in message news:... > I'm looking for a good intro to python book. I'm very familiar with > programming, but know nothing of OOP or systems (OS type) programming. You might consider a book about OOP theory/technique per se. > > So, I need something that covers the finer points of Python - difference > between ' and " for example - and the greater things beyond that, like > implicit lists and classes. > > I've had good luck with the O'Reilly books in the past .. Lutz and Asher's 'Learning Python' (from O'Reilly) is about to (has just?) come out in its 2nd edition (finally), check it out here: http://www.oreilly.com/catalog/lpython2/ For something comprehensive and fairly recent, you might consider Alex Martelli's 'Python in a Nutshell.' http://www.oreilly.com/catalog/pythonian/ From peter at engcorp.com Tue Dec 23 10:54:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Dec 2003 10:54:21 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: <3FE8652D.2E8F21A8@engcorp.com> Aahz wrote: > > In article , > Michael Hudson wrote: > >Gerrit Holl writes: > >> > >> So the Zen of Python shouldn't *be called* the Zen of Programming. > > > >No, it should be called "19 Pythonic Theses", which has the advantage > >of being vaguely accurate... > > Actually, it should be called "20 Pythonic Theses", because that was > Tim's original title. Ah, so it should be called the same thing as what its title is? But it's _actually_ called the Zen of Python? Or is that just its name now? ;-) -Peter P.S. My heartfelt thanks to whomever it was who posted the Lewis Carroll reference lately... I'm _still_ trying to find my old copy of Through the Looking Glass to find that section! From gumuz at looze.net Wed Dec 17 04:17:46 2003 From: gumuz at looze.net (Guyon Morée) Date: Wed, 17 Dec 2003 10:17:46 +0100 Subject: Is anyone using Python for .NET? References: Message-ID: <3fe02120$0$269$4d4ebb8e@news.nl.uu.net> What I like to do is use the .NET framework as the GUI-engine for my (windows only) applications. Is this already possible? "Brandon J. Van Every" wrote in message news:brnuts$591mp$1 at ID-207230.news.uni-berlin.de... > Is anyone using Python for .NET? I mean Brian's version at Zope, which > simply accesses .NET in a one-way fashion from Python. > http://www.zope.org/Members/Brian/PythonNet > Not the experimental ActiveState stuff, which tried to compile IL and > apparently didn't succeed. > > Two motives for the question: > > 1) whether to use it for my C++ / C# / .NET / Python (?) game project. It's > a prototype, so in this context a "mostly working beta" is acceptable. I > won't need "ready for prime time" for another year yet. > > 2) whether it's viable at this time to consult Python + .NET interop as a > business model to various Suits. I'm gathering that due to lack of > resources on Brian's webpage, and lack of responses on their mailing list, > that it isn't. Suits need to perceive support, after all. > > So I'm wondering who's kicking Python for .NET's tires, as that would be > part of the agenda of getting Python development to be .NET friendly. > > Why have that agenda? Well, Microsoft does generally succeed at > out-marketing everybody, so if you're with them rather than against them, > you have a much better chance of having your technology widely adopted. > Also, people actually like .NET language interop for its technical merits > alone. It's a rare case where Microsoft is actually leading the industry > rather than cloning and conquering. The clone is now Mono, in the Unix > world. I hope that eventually, at least the IL components of .NET are not a > Microsoft thing per se. Programmers need easy language interop solutions. > > -- > Cheers, www.indiegamedesign.com > Brandon Van Every Seattle, WA > > Brandon's Law (after Godwin's Law): > "As a Usenet discussion grows longer, the probability of > a person being called a troll approaches one RAPIDLY." > From jjl at pobox.com Fri Dec 5 11:50:43 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Dec 2003 16:50:43 +0000 Subject: Web authentication References: <7xn0a8qsao.fsf@ruckus.brouhaha.com> <878ylsdu5o.fsf@pobox.com> <3FD05DCF.4923A95E@hotmail.com> Message-ID: <87fzfzmcnw.fsf@pobox.com> Alan Kennedy writes: > [John J. Lee] > > Doesn't/shouldn't http://user:passwd at example.com/blah.html work? > > > > I don't know where that syntax is specified (if anywhere) > > RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax > > Section: 3.2.2. Server-based Naming Authority > > Quoting from that section > > """ > URL schemes that involve the direct use of an IP-based protocol to > a > specified server on the Internet use a common syntax for the server > component of the URI's scheme-specific data: > > @: [...] Oops, how did I miss that? Thanks John From shaleh at speakeasy.net Tue Dec 23 04:12:56 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Tue, 23 Dec 2003 01:12:56 -0800 Subject: global and None In-Reply-To: References: Message-ID: <200312230112.56840.shaleh@speakeasy.net> On Monday 22 December 2003 23:17, Leo Yee wrote: > > So I try to solve the problem in this way: > --- code begin --- > > global g > g=None > def foo(): > global g > if g==None: > g=0 > foo() > > --- code end --- > > And it works but the python documentation told me the following: > "Names listed in a global statement must not be defined as formal > parameters or in a for loop control target, class definition, function > definition, or import statement. " > > Does anyone know what I should do to solve this problem? Thanks in advance. It is warning you against shadowing. For instance: g = None def foo(): global g for g in some_thing: act(g) Your code is correct. Of course, you have to ask yourself if a global is really the right choice. From jepler at unpythonic.net Wed Dec 31 15:38:53 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Dec 2003 14:38:53 -0600 Subject: PYTHONPATH unnecessary with PythonWin? In-Reply-To: References: Message-ID: <20031231203853.GI18443@unpythonic.net> Python searches some directories by default. The documentation probably describes this in more detail. Using PYTHONPATH, you can add to that list. For instance, it's often useful (particularly on Unix) to have a personal directory listed in PYTHONPATH (like ~/lib/python) for your own modules. Jeff From aahz at pythoncraft.com Tue Dec 2 21:10:19 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2003 21:10:19 -0500 Subject: custom sorting and __cmp__ References: Message-ID: In article , Lee Harr wrote: > >>>> a1 == c >Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in __cmp__ >AttributeError: C instance has no attribute 'level' > >Should I be catching comparisons to objects that do not have >my 'level' attribute and falling back to id comparison? >Or am I worried about nothing (YAGNI :o) ? Python is these days moving more and more toward preventing heterogeneous comparisons: >>> import datetime, time >>> d=datetime.date.fromtimestamp(time.time()) >>> d>1 Traceback (most recent call last): File "", line 1, in ? TypeError: can't compare datetime.date to int However, you should set things up so that you can use ``==``: >>> d==1 False The easy way to handle this is to use the new special methods for rich comparisons instead of __cmp__. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From mtadin66 at yahoo.com Wed Dec 31 06:14:33 2003 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Wed, 31 Dec 2003 12:14:33 +0100 Subject: Tkinter References: Message-ID: try googling with: tkinter tutorial the first result is: http://www.pythonware.com/library/tkinter/introduction/ Marijan Tadin "km" wrote in message news:mailman.68.1072855330.8134.python-list at python.org... > Hi all, > I am in need of some sample scripts which cover vital issues of starting Tkinter with Python. Can somebody provide me with such links ? > > thanks in advance, > > regards, > KM > From bucodi_no_spam at ahoo.fr Tue Dec 23 02:57:53 2003 From: bucodi_no_spam at ahoo.fr (Rony) Date: Tue, 23 Dec 2003 08:57:53 +0100 Subject: Flat file database References: Message-ID: Art Decco wrote on Tue, 23 Dec 2003 07:07:32 GMT in : > Is there any Python module designed to simplify the use of a plain text file > as a flat file database? > > ... You could have a look at kirbybase Rony -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi_no_spam at yahoo.fr (delete _no_spam) / | www.bucodi.com - My work \ www.ifrance/karamusique -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From http Mon Dec 1 20:35:50 2003 From: http (Paul Rubin) Date: 01 Dec 2003 17:35:50 -0800 Subject: Filtering through an external process References: <7xllpyyl1s.fsf_-_@ruckus.brouhaha.com> <3fcbf321$1@nntp0.pdx.net> Message-ID: <7xllpwm26h.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > > Anyone know if there's code around to filter text through an external > > process? Sort of like the Emacs "filter-region" command. For > Check out popen2 -- its the piece you need. No, that doesn't do the job. If you popen2 a process and send too much input without reading the output, the subprocess will block and your application will hang. That is explained in the docs. Doing it right is a little bit complicated. You need threads or asynchronous i/o. That's the functionality that's missing. From bdesth.tagada at tsoin-tsoin.free.fr Sun Dec 21 20:30:45 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Mon, 22 Dec 2003 02:30:45 +0100 Subject: [Perl Troll] UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <3fe644e9$0$24015$626a54ce@news.free.fr> John Roth wrote: (snip) > And I was quite serious about that. I have the feeling > that there is a good deal of fossilization of the brain > cells setting in. > > I could be wrong about that, but I begin to worry when > I see Larry Wall ripping Perl apart and redesigning > it, and I get the impression that the only reason for > Python 3.0 (which seems to be the same distance > in the future, regardless of when we talk about it) > is to make a few relatively minor incompatible > changes. > Could it be that Python having a much better design right from the start, there's no need to do it again ?-) From tjreedy at udel.edu Tue Dec 9 13:59:01 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Dec 2003 13:59:01 -0500 Subject: cell object dereferencing References: <3FD5FD4A.9060406@jandecaluwe.com> Message-ID: "Jan Decaluwe" wrote in message news:3FD5FD4A.9060406 at jandecaluwe.com... > Is there a way to dereference a cell object (that is, get > the object that it references to) in Python? [Background: a cell is an undefined internal implementation object used to make nested scoping work as advertised. One might think of it as a means for persisting cross-scope name-binding of objects in intermediate nested scopes of nested functions. Alternatively, a cell is 'persistent read-only shadow of an outer local'. For nested functions that access intermediate locals, .func_closure is a tuple of 'cells'.] Yes and no, depending on what you mean be 'dereference'. Within the nested function, you 'dereference' the variable the same way you do any bound ame -- write it! Outside the function, where the variable has no conceptual existence, you can grab a cell from the func_closure tuple, but I know of no way to access its value. Both repr() and str() return a description. If you want a globally accessible value, use a global variable. Terry J. Reedy From martin at v.loewis.de Sun Dec 21 19:15:42 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Mon, 22 Dec 2003 01:15:42 +0100 Subject: Count Files in a Directory In-Reply-To: <93f5c5e9.0312211545.363b91a6@posting.google.com> References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: hokiegal99 wrote: > I'm trying to count the number of files within a directory, but I > don't really understand how to go about it. You mean, you want the number of files in a directory? The number of immediate files, or the number including files in nested directories as well? If you want the number of immediate files, you can use os.listdir(path) to produce a list of files in a directory. You can then use len(L) to compute the number of items in a list. IOW, print len(os.listdir(path)) does what you might want. Regards, Martin From mesteve_b at hotmail.com Sun Dec 14 17:18:14 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 14 Dec 2003 22:18:14 GMT Subject: Idle won't start References: Message-ID: You didn't by any chance create a batch routine that sometimes creates a file by the name of "\Lib\idlelib\idle.pyw" did you. "Kerry Neilson" wrote in message news:ecebe16b.0312141050.4a10fbba at posting.google.com... > For the past couple of months, Idle won't start when I invoke it. I > am at a complete loss for why this is. When this happens, they python > command line still starts, and python works fine otherwise. > Most interesting to me is that a reboot won't fix the problem. But if > I just try it again sometime later it will work. Anyone have any > ideas? I'm running python 2.3 on windows 2000 professional. From david.bear at asu.edu Fri Dec 5 12:29:54 2003 From: david.bear at asu.edu (David Bear) Date: 05 Dec 2003 10:29:54 -0700 Subject: HELP: W2K Python + Cygwin shell script References: <3fca4139$0$1154$39db0f71@news.song.fi> Message-ID: I have used w32python interactively from a cygwin bash. its okay. but I think I remember that the python environment (syspath?) was not set properly. so, this would be something to check in your cygwin bash rc file.. -- David Bear phone: 480-965-8257 fax: 480-965-9189 College of Public Programs/ASU Wilson Hall 232 Tempe, AZ 85287-0803 "Beware the IP portfolio, everyone will be suspect of trespassing" From webmaster at beyond-thoughts.com Wed Dec 10 10:01:01 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Wed, 10 Dec 2003 16:01:01 +0100 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? In-Reply-To: <3fd728e3$0$213$e4fe514c@news.xs4all.nl> References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> <3fd728e3$0$213$e4fe514c@news.xs4all.nl> Message-ID: <3FD7352D.5030109@beyond-thoughts.com> Irmen de Jong wrote: > Dang Griffith wrote: > >>>> Tab completion for keywords and methods etc (you can get this in the >>>> standard python shell as well of course) >>> >>> >>> You can? How? >>> >>> --Irmen >> >> >> >> Press tab after typing part of the keyword/method. > > > Sean was talking about the 'standard python shell' so I tried > the default python (2.3) on my mandrake 9.2 box. > It doesn't work, it just inserts a tab character. > > --Irmen > You need an startup-file for python. (I copied this together out of python-news-mail (thank you once again) and some own ideas) .pystartup in your home-dir # Add auto-completion and a stored history file of commands to your Python # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is # bound to the Esc key by default (you can change it - see readline docs). # # Store the file in ~/.pystartup, and set an environment variable to point # to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash. # # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the # full path to your home directory. import atexit import os import readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") historyTmp = os.path.expanduser("~/.pyhisttmp.py") endMarkerStr= "# # # histDUMP # # #" saveMacro= "import readline; readline.write_history_file('"+historyTmp+"'); print '####>>>>>>>>>>'; print ''.join(filter(lambda lineP: not lineP.strip().endswith('"+endMarkerStr+"'), open('"+historyTmp+"').readlines())[:])+'####<<<<<<<<<<'"+endMarkerStr readline.parse_and_bind('tab: complete') readline.parse_and_bind('\C-w: "'+saveMacro+'"') def save_history(historyPath=historyPath, endMarkerStr=endMarkerStr): import readline readline.write_history_file(historyPath) # Now filter out those line containing the saveMacro lines= filter(lambda lineP, endMarkerStr=endMarkerStr: not lineP.strip().endswith(endMarkerStr), open(historyPath).readlines()) open(historyPath, 'w+').write(''.join(lines)) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath, historyTmp, endMarkerStr, saveMacro (I hope spaces will survive mailing) Additionaly you need to ~# export PYTHONSTARTUP=/root/.pystartup You can do this e.g. in .profile Pressing tab completes the input like common unix-shells. Pressing CTRL-w gives You an python code to print the history-file (or parts of it -- there's a [:] in the command that You can replace by [-50:]; which will give you the last 50 lines) cu cbf From logan at phreaker.nospam Tue Dec 2 05:56:09 2003 From: logan at phreaker.nospam (Logan) Date: Tue, 02 Dec 2003 11:56:09 +0100 Subject: wxPython / styles and marks in TextCtrl References: Message-ID: On Mon, 01 Dec 2003 20:47:38 -0600, Edward K. Ream wrote: > Probably it would be a good idea to investigate the wxStyledTextCtrl. There > are examples of using it in the wxPython demo program. This control isn't > documented in the main alphabetical list of classes in the version of the > docs I have. Iirc wxStyledTextCtrl is a wrapper for the scintilla classes. Hello Edward; thanks for your answer! Yes, StyledTextCtrl is a wrapper for Scintilla; the wxPython documentiation for it can be found here: http://www.pyframe.com/wxdocs/stc/index.html But actually, I was looking for something more 'light weight'; e.g. to write my own Scintilla-like component (which I would not like to base on Scintilla :-) Calling Scintilla (STC) the heavy weight champion and TextCtrl an amateur, I think there is something missing just in between. L. -- mailto: logan at phreaker(NoSpam).net From hokiegal99 at hotmail.com Tue Dec 30 11:23:51 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 30 Dec 2003 11:23:51 -0500 Subject: Is Python Mac Centric??? Message-ID: While trying to learn more about Python's standard modules, I noticed that there are *a lot* of Mac only modules... more so than Unix and Windows specific modules combined. Is there a reason for this? I am familiar with the Windows extensions by Mr. Hammond and wonder if they'll ever become apart of the official Python distribution. It looks as if something similar already exists for Macs with all these Mac only modules. Why is this? Also, I've noticed that OSX 10.3 comes with Python 2.3 installed, but that Windows XP does not. Python installation is much more cumbersome on Windows. The user has to dl Python and then Mr. Hammond's extensions to get up to speed with the new Macs out of the box. Does Python play favorites? I think it would have a much larger user base if Windows user got what mac users get. Could someone explain this to me? I don't mean this to start a platform war as I'm really agnostic on the matter. Just curious. Thanks!!! From paul at fxtech.com Tue Dec 16 10:22:52 2003 From: paul at fxtech.com (Paul Miller) Date: Tue, 16 Dec 2003 09:22:52 -0600 Subject: PyThreadState_Swap difference in 2.3.2? References: Message-ID: >Unfortunately, much of this stuff has never been thought through >correctly. Trying to work with multiple InterpreterState objects is >also very difficult, and in some cases simply does not work, as not all >global variables are stored in an InterpreterState. Theoretically >though, this is probably what you want - if a different InterpreterState >is current, I would expect a ThreadState specific to the >InterpreterState could be used - but I doubt it works It used to work perfectly in 2.2. Thus my dilemma. >The easy answer is to stop trying to create multiple interpreter states, >then use the PyGILState calls to manage your thread-state. These should >be 2 lines per function (rather than the many that exist now). If you >need to build in both pre 2.3 and 2.3+: But, I'm not looking for a replacement for per-thread state. I am actually maintaining multiple *interpreters*, each with all those global variables you talked about. I need to do this because I want to be able to create an "environment", load some scripts, run them, then delete that "environment" without affecting other "environments". If this PyGILState actually is an entire Python interpreter environment, then I'll happily switch to it. From toph at laposte.net Tue Dec 2 08:04:03 2003 From: toph at laposte.net (Toph) Date: Tue, 2 Dec 2003 14:04:03 +0100 Subject: [ python-list ] scrolling a frame Message-ID: Bonjour a tous, Hi, I am developing a software in Python using Tkinter. The choice of my team is not to use pyton MegaWidgets. I would like to scroll a frame. This is a peace of my code : # ----------------------------------------------------------------------------- #!/bin/env python from Tkinter import * root = Tk() global_frame = Frame(root, relief = GROOVE, borderwidth=4) canvas = Canvas(global_frame) # scrollbars: vscroll = Scrollbar(global_frame, command=canvas.yview) hscroll = Scrollbar(global_frame, command=canvas.xview, orient=HORIZONTAL) # The frame i want to scroll : frame = Frame(canvas, relief = GROOVE, borderwidth=2) cw = canvas.create_window(0,0, window = frame) global_frame.grid(row = 0, column = 0, sticky=NS) #put the widgets in global_frame canvas.grid(row = 0, column = 0) vscroll.grid(row = 0, column = 1, sticky=NS) hscroll.grid(row = 1, column = 0, sticky=EW) # fill the frame : for item in range(30): Label(frame, text = 'item %d'%item).grid(row = item, column = 0) Entry(frame, text = 'default text %d'%item).grid(row = item, column = 1, sticky=EW) # configure the scollbars to scroll the canvas : hauteur = frame.winfo_height() largeur = frame.winfo_width() canvas.configure(yscrollcommand = vscroll.set, xscrollcommand = hscroll.set, scrollregion = (0,0, largeur, hauteur)) #canvas.coords(cw)) # My problem is that i would like the scrollregion to scroll only the space taken by # the frame but my program does not do it well... root.mainloop() #------------------------------------------------------------------------------ I thank you in advance. Christophe Acc?dez au courrier ?lectronique de La Poste : www.laposte.net ; 3615 LAPOSTENET (0,34?/mn) ; t?l : 08 92 68 13 50 (0,34?/mn) -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Dec 15 15:38:23 2003 From: http (Paul Rubin) Date: 15 Dec 2003 12:38:23 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: <7xwu8xes00.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > I think your decision in favor of Lua's a good one. Guile and > Scheme, from the last I saw of them, are *not* slender enough to > compete. Forth is the one other serious language that can be tiny > enough to make Lua look stout; while Forth hasn't made a good > impression on me as a "configuration language", that might reflect > my limits more than Forth's. There are Scheme subsets like SIOD which are much smaller than either Guile or Lua. Forth is a little bit too contorted for my tastes, but there was once an Emacs-like editor that used something close to it as an extension language. PostScript, of course, also strongly resembles Forth. A minimal Forth can be even smaller than SIOD, but SIOD is pretty small and I'd probably use something like it in preference to Forth in any but the tiniest environments. From frobozz_electric at hotmail.com Wed Dec 3 12:37:51 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 3 Dec 2003 17:37:51 GMT Subject: Adding method to object References: <72krsvcpeur8hhu74s4bhlsq3bf60fu055@4ax.com> Message-ID: "marco" wrote in message news:bqkrsb$nf1$2 at s1.read.news.oleane.net... > Is it possible to do the same thing for an attribut, instead of a method ? > > i'd like to wrap an newAttribute to an oldAttribute one : > example: > i've got an instance "n" of an "xmlNode" class > i'd like to use "n.parentNode" instead of "n.parent" ... [snip] # try this ... n.parentNode = n.parent HTH Sean From raims at dot.com Sat Dec 13 09:38:50 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 13 Dec 2003 15:38:50 +0100 Subject: python2.3 upgrade References: Message-ID: <87ekv8vl39.fsf@mobile.foo> tudor writes: > Traceback (most recent call last): > File "/usr/sbin/redhat-switch-printer", line 84, in ? > main() > File "/usr/sbin/redhat-switch-printer", line 68, in main > from switchprinter_gui import mainDialog > File "/usr/share/redhat-switch-printer/switchprinter_gui.py", line 51, > in ? > import gtk > ImportError: No module named gtk Have you reinstalled pygtk for the right python version? -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From paddy3118 at netscape.net Sun Dec 14 06:16:37 2003 From: paddy3118 at netscape.net (Paddy McCarthy) Date: 14 Dec 2003 03:16:37 -0800 Subject: Python vs Unix shells References: <2ae25c6b.0312130213.2f5452c6@posting.google.com> Message-ID: <2ae25c6b.0312140316.77f7059f@posting.google.com> William Park wrote in message news:... > In Paddy McCarthy wrote: > > This is really a comment on "Python in Systems Administration: Part I > > -- Better Scripting" > > http://www.samag.com/documents/s=8964/sam0312a/0312a.htm > > by Cameron Laird. > > > > Reading the article, although I am a fan of Python, I kinda take issue > > with the example given. It doesn't seem to fit with the concept of > > 'many smaller utilities doing one thing well, connected via pipes' > > What did you expect from a Python consultant? He has the right to make > a living and advertise his expertise. Hi William, I don't understand why you made your comment? I was expecting replies of maybe "the pressures of getting an example to fit the article made his example maybe a little artificial" (but still useful). or people agreeing or disagreeing with the idea of modules that are also Unix scripts. I can't see how Cameron being a consultant has anything to do with it. Cheers, Paddy. From jacek.generowicz at cern.ch Tue Dec 9 04:41:52 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 10:41:52 +0100 Subject: Turning builtin functions into methods. Message-ID: Functions defined in Python have type types.FunctionType, and are descriptors whose __get__ method turns them into bound or unbound methods. Functions defined in extension modules have type types.BuiltinFunctionType, and have no __get__ method. Adding them as attributes to classes and calling them through an instance of the class does not result in them being called as methods: self is lost. What's the simplest way of getting around this ? Some background: I'm trying to speed up my application by recoding, in C, the Python functions which are being called in my inner loops. I have a number of classes which have a single method being called in the inner loops, so, rather than recoding the whole class, I'd like to recode only the relevant method, and glue it onto the class, like this class foo: def this(self, ...): ... def that(self, ...): ... import speedup foo.the_other = speedup.the_other where the_other is implemented in C, but is equivalent to def the_other(self, ...): ... Any suggestions ? Thanks, PS. I'm a bit disappointed that Python makes this distinction between functions defined in extension modules, and ones defined in pure Python, but I guess that there are good practical reasons for it. From bokr at oz.net Tue Dec 2 13:06:51 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Dec 2003 18:06:51 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: On Tue, 02 Dec 2003 08:19:25 GMT, "Raymond Hettinger" wrote: >> > Please can we have a name that better expresses the functionality? >> > >> > E.g., 'keyfunc', or 'xform' or something that says the method is expecting >> > a function that will be called with the sorting argument to produce the >value >> > used in sorting? "key=" doesn't do it IMO. >> >> I agree. To me, the word "key" has deep meaning with respect to hash tables >> and databases, and reading it as a parameter makes me first think it might >> require a string or integer. I would prefer something like "sortfunc" or >> "decorator", but both of your suggestions would be fine by me and preferable >> to "key". > >cmpfunc= and keyfunc= were both suggested by several non-Dutch such as myself. > >Then, Guido rightly pointed out that the keywords should just be pithy memory >joggers. Taken in that light, key= and cmp= do the job nicely. The definitions IMO both jog the wrong memories in that context. You might as well say "data" would do nicely as a name in place of the builtin "file". It jogs the memory that there's probably data access involved. But it obscures the "what kind" which is what "file" communicates. If you want pithy, then at least tack on a hint, e.g., "keyf" >and details are best left to docstrings and regular docs. Besides, after >learning the new DSU key just once, we *know* what kind of function is supposed IMO the "learning just once" argument is a Perl argument, once you accumulate a few features with misleading or no mnemonics ;-) >to go there. Further, when reading code, you get the additional context of >seeing which function was actually used: > > logentries.sort(key=lambda e: e.juliandate) # looks like a key function >to me Excuses, rationalizations. I don't wan't to incite a contest, but IMO "key=" is misleading ;-) Regards, Bengt Richter From news at grauer-online.de Tue Dec 9 15:17:29 2003 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 09 Dec 2003 21:17:29 +0100 Subject: Reading and writing Mozilla-mail in python In-Reply-To: References: Message-ID: After playing around with the mailbox an email modules i noticed some strange behaviours: after the first message is parsed, i got some (kind of parsing errors). My code: def test_copy(infile, outfile): from mailbox import UnixMailbox from email import message_from_file as mff try: fd = open(infile, 'r') try: for message in UnixMailbox(fd, mff): print message print '***********************************************' finally: fd.close() except: pass return output from script above: .... In-Reply-To: <3FB8D0C0.60300 at web.de> Sender: someone at somewhere.de Nein, leider noch nicht, komm auch erst in paar Tagen dazu. Fro *********************************************** From - Sun Dec 07 02:59:04 2003 X-UIDL: 6165 X-Mozilla-Status: 0001 X-Mozilla-Status2: 00000000 .... Look at the Line: Fro Whats going on here. Could someone please verify this? I'm using python 2.3.2 on Win2000 SP4 + all patches Thanks, Uwe From fredrik at pythonware.com Tue Dec 2 08:15:27 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 Dec 2003 14:15:27 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com><3FCC6C18.7090209@Linux.ie> Message-ID: Joerg Schuster wrote: > > > O.k. Thanks for pointing this out. Maybe I should have formulated my > > > question differently: Is there a trick (be it dirty or not) to make > > > "|" greedy in python? > > > > sort the re by size first? > > The point is not to get the match of the longest part of the > disjunction, but to get the match of that part of the disjunction > which is the longest one. (The match of ".*" may be much longer > than the match of "abc", although the latter regex contains more > characters.) you can use "sre_parse.parse(x).getwidth()" on a subexpression, to get the shortest/longest possible match. >>> from sre_parse import parse >>> parse("a?").getwidth() (0, 1) >>> parse("ab").getwidth() (2, 2) >>> parse(".+").getwidth() (1, 65535) (where >=65535 should be interpreted as "any number") From jacek.generowicz at cern.ch Fri Dec 12 07:24:21 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Dec 2003 13:24:21 +0100 Subject: Function application optimization. References: Message-ID: bokr at oz.net (Bengt Richter) writes: > I'd probably try a list comprehension > > >>> [f(a) for f,a in zip(fncs,args)] > ['func_0(zero)', 'func_1(one)', 'func_2(two)', 'func_3(three)'] Yup, been there, done that, it's slower. (I guess I should have mentioned that in the original post.) From mark at mceahern.com Wed Dec 31 00:52:36 2003 From: mark at mceahern.com (Mark McEahern) Date: Tue, 30 Dec 2003 23:52:36 -0600 Subject: position in a for loop? In-Reply-To: <5.2.0.9.0.20031230213049.034cf0f8@mail.zomething.com> References: <5.2.0.9.0.20031230213049.034cf0f8@mail.zomething.com> Message-ID: <1072849956.27658.267.camel@dev.internal> On Tue, 2003-12-30 at 23:30, EP wrote: > How I can tell where I am in a for loop? Great question. Use enumerate (new with Python 2.3, I believe). > I think I am working way too hard to try to determine this - there is > probably a very simple way to know? > > Spam_locations=[] > list=['linguine','Spam', 'clams', 'Spam', 'steak', 'onions', 'apples', > 'Spam'] > for food in list: > if food='Spam': > Spam_location.append(## position in list ##) Other minor points: * Don't use list as a name--you clobber the builtin name "list". * Your comparison probably should be if food == 'Spam' rather than an assignment of 'Spam' to the name 'food', which is what one equals sign (distinct from two) does. Assignment vs. comparison. An eternal gotcha. So that'd be: hits = [] foodItems = ['linguine','Spam','clams','Spam','steak'] for i, item in enumerate(foodItems): if item == 'Spam': hits.append(i) Pre-enumerate, you'd do something like: for i in range(len(foodItems)): item = foodItems[i] ... Cheers, // m From david at rebirthing.co.nz Mon Dec 8 07:06:09 2003 From: david at rebirthing.co.nz (David McNab) Date: Tue, 09 Dec 2003 01:06:09 +1300 Subject: ANN: pythonfs - create linux filesystems in python Message-ID: <3FD46931.1000802@rebirthing.co.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I've just built a framework which allows mountable linux filesystems to be implemented in pure python. It consists of a back-end to LUFS (lufs.sf.net), and is available from http://www.freenet.org.nz/python/lufs-python Simple to use - after adding the pythonfs code to LUFS, and building/installing, one only needs to copy the template.py python module and flesh out the methods in the Filesystem class. Generous docstrings spell out exactly what is needed. Have phun Cheers David - -- leave this line intact so your email gets through my junk mail filter -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQE/1GkxUuEuev/PjrcRArSzAJ4gbHZtRN6Di3I/sD/9cCk0m/86igCeLFvi grZoxZILdpugnNiuwb2fW5E= =fTSI -----END PGP SIGNATURE----- From news at grauer-online.de Tue Dec 9 16:52:57 2003 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 09 Dec 2003 22:52:57 +0100 Subject: Reading and writing Mozilla-mail in python In-Reply-To: References: Message-ID: Now i tried it under Linux (Suse 8.2) + self compiled python 2.3.2. It works!! So, what the hell is going on with my stupid win2000? Has anyone seen this before? It think i'm going to reinstall the whole Shit. Uwe Uwe Grauer wrote: > Whats going on here. > > Could someone please verify this? > > I'm using python 2.3.2 on Win2000 SP4 + all patches > > Thanks, > Uwe > From rodrigob at elo.utfsm.cl Fri Dec 5 10:57:27 2003 From: rodrigob at elo.utfsm.cl (Rodrigo Benenson) Date: Fri, 5 Dec 2003 12:57:27 -0300 Subject: Tkinter binding list Message-ID: <3fd0a76a$1_2@nova.entelchile.net> Hi, I have a weird need in tkinter. If I have a widget I can *set* a binding .bind("", the_callback) I also can *append* a binding .bind("", the_second_callback, "+") but now, I need to *replace* a callback. The easier way is to obtain the bindings, delete them all, and rebind the new list. So, how can I replace a callback, when there are more than one binding ? or, as an equivalente question, how can I obtain the list of callbacks binded to widget event ? Thanks, RodrigoB. From lutz at rmi.net Wed Dec 3 12:07:04 2003 From: lutz at rmi.net (Mark Lutz) Date: 3 Dec 2003 09:07:04 -0800 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> <3fcc9577$0$7676$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:<3fcc9577$0$7676$3a628fcd at reader1.nntp.hccnet.nl>... > lutz at rmi.net (Mark Lutz) wrote: > > >I'm using Python on a Sharp Zaurus C760 these days, > >one of the Japan models that you can get converted > >to English from a number of importers. It comes > >with a full VGA (640x480) swivel screen, and a nice > >keyboard. The keyboard isn't full size, but it's > >much better than the thumbs-key input of most PDAs. > > [...] > > Third and most important point for me is that I have some application > I want to use it for, it's my own little pygobo freeware script that > "nobody" wants to download but which is in my opinion the best > sgf-file viewer for baduk there is (at least for someone that can > program Python). However this viewer is written using TKinter and > there seems to be no such thing as Tkinter on any pda. Actually, I should have done a bit of googling on this myself, before responding on the Tkinter issue yesterday. You can find information about running Tk on the Zaurus here: http://wiki.tcl.tk/zaurus Still not a simple task, but it looks possible. It looks like you'll need to get X and Tk running in one of a variety of ways, and will probably also need to compile Python's Tk interface module to get Tkinter to work. Again, if I had an infinite amount of time... --Mark Lutz (http://www.rmi.net/~lutz) From alan_salmoni at yahoo.com Mon Dec 22 16:42:48 2003 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 22 Dec 2003 13:42:48 -0800 Subject: any one used googles api? References: Message-ID: Bill Sneddon wrote in message news:... > Has anyone used googles API who would be will to share > a simple example. I have been wanting to play around with > SOAP for a while and this looks like a place to start. > > I am going to mess with it in ASP when our IT guys set it up > for me. > > > I like Python but have not done anything with SOAP yet. > > http://www.google.com/apis/ Hi Bill, Like another poster suggested, I would recommend using PyGoogle. I used it to retrieve materials for a number of my own experiments and found that it was rather good - more effective that just spoofing a query (which I used to do). Here's an example that I used to retrieve a list of returns (document titles and "snippets") from the Google: btw - a "concern" is just a search string for this study. # program to retrieve loads of results from Google. # (c) 2002 Alan James Salmoni, HCI Group, Cardiff University # reminder: 10 concerns, 30 summaries each! # concerns are strings in a file called "concerns.txt" import google, os, os.path google.LICENSE_KEY = 'heeheenottellingyou!' # must get your own! fin = open('concerns.txt','r') fout = open('results.exp6.txt','w') deadpage = 'No Page' # this snippet gets 100 results for each of 10 concerns #titles = summaries = urls = [] for i in range(11): fin.readline() for i in range(0,9): concernstring = fin.readline() k = 0 data = google.doGoogleSearch(concernstring, 0+k, 10,1,'',1,'lang_en','','') fout.write(concernstring) # record the concern on the file fout.write(str(data.meta.estimatedTotalResultsCount)+'\n') # record # results for k in range(0,100,10): data = google.doGoogleSearch(concernstring, 0+k, 10,1,'',1,'lang_en','','') # search for "concernstring" indeces 0-100, filtering out similar results, no restrictions, # safesearch ON, in english and no input or output encoding! for j in range(10): #print 'concern: '+str(i)+' block: '+str(k)+' result: '+str(j) if (j+k) < data.meta.estimatedTotalResultsCount: if not os.path.isdir(str(i)): os.mkdir(str(i)) References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: <3FE6B841.90707@Linux.ie> Xah Lee wrote: > i have a bunch of java files that has spaced-out formatting that i > want to get rid of. I want to replace two end of line characters by > one end of line characters. The files in question is unix, and i'm > also working under unix, so i did: > > perl -pi'*~' -e "s@\n\n@\n at g" *.java Of course you can do it in Perl. The handiest way I think is: tr -s '\n' P?draig. From jacek.generowicz at cern.ch Tue Dec 9 04:22:38 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 10:22:38 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Jacek Generowicz writes: > Jacek Generowicz writes: > > > static int > > memoize_init(memoizeObject* self, PyObject* args, PyObject* kwds) { > > PyArg_ParseTuple(args, "O", &(self->fn)); > > Obvious bug: &(self->cache) !! > > > Py_INCREF(self->fn); > > self->cache = PyDict_New(); > > return 0; Apologies, I misreported the bug. self->fn is appropriate here ... using self->fn (instread of self->cache) as the dictionary in the other function is what was wrong, of course. > Fixing the bug gives me a factor of 3 speedup over the class-based > version. This is still true. From lists at webcrunchers.com Tue Dec 16 03:02:46 2003 From: lists at webcrunchers.com (JD) Date: Tue, 16 Dec 2003 00:02:46 -0800 Subject: More info on my Python problem.... Message-ID: <3BB7ABA8-2F9E-11D8-BFA1-0030656C6B9E@webcrunchers.com> I hope I didn't post this twice, but I didn't see my earlier posting, so I've posted it again. Please excuse of me you see a 2nd one, but I suspect this might be a problem with our mailer. This is another Python problem, I think might be unrelated to the earlier bug I found. This is related to a question I have about Python hanging up either from a shell, or by importing a module. If my code causes Python to just hang up, and not allowing me to break out with control-C or control-D, is there a way to find out what's going on? I don't think it's going into some infinite loop, because I can usually break out of them with control-C. What would cause the Python run-time system to just loose things? The console is dead, but it echo's carriage returns but that's all it does. Is there someone who I might contact via phone to walk me through this? (Assuming I can't get adequate information here? Or does anyone care about Python bugs?) This is in Python 2.3.3c1 on OpenBSD (though I doubt the OS matters). The symptom is that I run my program and Python locks up. I cannot control-C or control-D to get out of it; I have to log in separately and kill -9 the process. The process is listed as "D+" while it is hung, though it doesn't seem to be accessing the disk, and I'm quite sure there are no disk problems (though I'm not physically next to the server, so I can't check the drive LED). How should I approach debugging this? Are there Python tools? Or should I use gdb? ktrace? systrace? I'm assuming I have to do this, as a bug report which reads "Python locks up" isn't too useful. John From mir4uu at yahoo.com Thu Dec 11 09:36:40 2003 From: mir4uu at yahoo.com (mir nazim) Date: 11 Dec 2003 06:36:40 -0800 Subject: python vs php for web programming Message-ID: <425cc8d1.0312110636.56be9ecf@posting.google.com> i m currently using PHP with Apache (a.k.a 'mod_php') for my web development work. i came to know that python can also be used to do web programming using 'mod_python' for Apache. i wanted to know the difference between th two 'mod_php' and 'mod_python' in terms of: 1. speed of execution. 2. productivity 3. maintainance (i know python is most productive and maintainable language in the world, but is it same for web programming with Apache). 4. availability of features e.g, cookies and session hadling, databases, protocols, etc. I also wanted to know about Zope and comparison of its proformance, features, etc. with Apache. From danb_83 at yahoo.com Fri Dec 12 19:24:30 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Dec 2003 16:24:30 -0800 Subject: porting python script from linux to windows References: Message-ID: hokieghal99 wrote in message news:... > What are the specific steps that one should take to make a python script > that works on a Linux x86 machine also work on a Windows x86 machine? > > I am using os, re and string in the script. How do paths differ between > the two OSes? I am use to a unix-like path /blah/blah/blah. Would I need > to change this to x:\blah\blah\blah where x = drive letter? You woudn't *need* to; the drive letter can be omitted when the file is on the same drive. Also, Windows doesn't care what kind of slashes you use (except for cmd.exe). But you will have to, for example, change "/home/dan" to "c:\\winnt\\Documents and Settings\\dan". > What about > creating fs objects? file works the same on both? For the most part, yes, but in mind that, on Windows, it matters whether you open a file in text or binary mode. > os.walk works the same? Yes. From bokr at oz.net Sat Dec 20 17:39:39 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Dec 2003 22:39:39 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On Sat, 20 Dec 2003 06:38:20 -0500, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:bs0amc$hsl$0 at 216.39.172.122... >> On Fri, 19 Dec 2003 20:22:38 -0500, "John Roth" >wrote: >> >> > >> >"Steve Lamb" wrote in message >> >news:slrnbu77jp.nh8.grey at dmiyu.org... >> >> On 2003-12-20, John Roth wrote: >> >> > a third is the ability to forget the empty parenthesis after >> >> > a function/method call that doesn't require parameters. >> >> >> >> class ThisIs: >> >> avariable = 'a' >> >> def amethod(self): >> >> return 'b' >> >> >> >> thisis = ThisIs() >> >> print thisis.avariable >> >> print thisis.amethod() >> >> import this >> >> print "Read line 2." >> > >> >I'm not sure what your point is. Your example isn't going >> >to produce the expected result if you say: >> > >> >print thisis.amethod >> > >> >instead of >> > >> >print thisis.amethod() >> > >> >That is the place where I find Ruby syntax to be >> >helpful: the amount of time where I want the method / >> >function object is *far* lower than the amount of >> >time I want to call it. It's one of those conundrums >> >that doesn't seem to have a clean answer, though. >> > >> Ok, for line 2, run this ;-) >> >> class ThisIs: >> avariable = 'a' >> def amethod(self): >> return 'b' >> def silly(self): >> return 'heh' >> silly = property(silly) >> >> thisis = ThisIs() >> print thisis.avariable >> print thisis.amethod() >> print thisis.silly >> import sys >> class L2(list): >> def write(self, s): self.append(s) >> sys.stdout = L2() >> import this >> L2 = ''.join(sys.stdout).splitlines()[2] >> sys.stdout = sys.__stdout__ >> print "Read line 2." >> print '... which is:', L2 >> >> Regards, >> Bengt Richter > >I think you're missing the point I was trying to make. Sorry, I was being superficial. BTW, the output of the above is ---- a b heh Read line 2. ... which is: Beautiful is better than ugly. ---- ;-) >Sure, you can use a property to not have to put >in the explicit function call, but then you can't put >in the explicit function call *anywhere* you use that >property. > Nor can you supply explicit arguments if you want to, though you could provide an alternate name, so you could access either way. Nor can we do properties without accessing them via the attribute magic (i.e., not via bare global names for example). >Ruby syntax makes it *optional*. That's what is >missing here. I've floated various ideas/brain_farts more/less seriously for triggering magic via name access alterantive to getattr magic, but there seems to be no enthusiasm or else horrification at the thought, so I haven't stirred that pot for some time ;-) What would be the syntax you would like to use, with what effect? Regards, Bengt Richter From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 2 12:33:55 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 02 Dec 2003 18:33:55 +0100 Subject: Excuse me! References: Message-ID: <05jpsv4et8qifi2ul0sa1at0vjua4ucakm@4ax.com> Spam Collctor: >How can I use RFC822 to do a mail header parser? You'd have to read it, and then program one. >how do I make it? It has already been made: http://www.python.org/doc/2.3.2/lib/module-email.html -- Ren? Pijlman From llothar at web.de Sun Dec 14 08:11:48 2003 From: llothar at web.de (Lothar Scholz) Date: 14 Dec 2003 05:11:48 -0800 Subject: Strip HTML tags? References: <7b454334.0312131911.70647953@posting.google.com> Message-ID: <6ee58e07.0312140511.4cee51f6@posting.google.com> faizan at jaredweb.com (Fazer) wrote in message news:<7b454334.0312131911.70647953 at posting.google.com>... > Or how would I remove everything between < and > also the < , > as well using regex? You don't want to use regex for this. regex is only for very simple things readable. Use the HTML parser and concatenate the text you get from there. From qandil at eim.ae Thu Dec 18 16:51:43 2003 From: qandil at eim.ae (Kids Beauty) Date: Fri, 19 Dec 2003 01:51:43 +0400 Subject: Check this site, its cute Message-ID: <0HQ400AYM22DBP@dpmail1.emirates.net.ae> http://angelkids.textamerica.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From shaleh at speakeasy.net Sat Dec 27 10:53:43 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Sat, 27 Dec 2003 07:53:43 -0800 Subject: indendation question In-Reply-To: <20031226033210.GA24039@mrna.tn.nic.in> References: <20031226033210.GA24039@mrna.tn.nic.in> Message-ID: <200312270753.43615.shaleh@speakeasy.net> On Thursday 25 December 2003 19:32, km wrote: > Hi all, > > What is the standard and recommended way of indendation one should get to > use in python programming ? is it a tab or 2 spaces or 4 spaces ? i am > confused. kindly enlighten > > thanks, > KM Well the "official" standard can be seen in the python files distributed with python -- 4 spaces. That said, Python will use any whitespace you want as long as you are consistent. 3 spaces, a tab, whatever. From tonym1972club-internetfr Sat Dec 13 16:02:23 2003 From: tonym1972club-internetfr (Anthony McDonald (at in)) Date: Sat, 13 Dec 2003 22:02:23 +0100 Subject: optimization pointers? References: <3fd9cdf1$0$6970$7a628cd7@news.club-internet.fr> Message-ID: <3fdb7e6f$0$6968$7a628cd7@news.club-internet.fr> "Mel Wilson" wrote in message news:xIf2/ks/Kvyd089yn at the-wire.com... > > Nice touch! I tried slices and took a huge performance > hit (almost 3x the list version) but I didn't use `for ... in > xrange ...`. It must have all been in the while-loop test > and index incrementing. > > Regards. Mel. Thanks. My original attempt which incidentally used range was about half a second slower than yours with 700K of test data. Just as I was about to close the editor window I noticed your return statement. return len (voc.keys()) Which creates a list of keys to then apply len to, but thats an unneeded step as len applied directly to a dictionary returns the number of keys. I made the change and gained 7 hundreds of a second. Not much, still behind yours, but it suggested that chainging range to xrange and avoiding the list creation might help. Viola! The interesting thing that benchmarking with test data shows, is that the difference in speed between our 2 routines is about 0.05secs per 700K processed. That difference remains constant at least upto 80Mb of input data, implying that slices are no more efficent than string appending, and may actually in this case be less efficent. Anthony McDonald From __peter__ at web.de Sun Dec 7 05:35:17 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Dec 2003 11:35:17 +0100 Subject: how to determine if files are on same or different file systems References: Message-ID: Kamus of Kadizhar wrote: > Thanks to everyone on this list. I now have a functioning piece of > python code!! :-)) > > Now I'm trying to clean it up. > > I have the same (or similar) lines repeated several times: > > shutil.copy2(newArrivalsDir+'/'+movie,archivesDir) > thumb = string.replace(movie,'.avi','.jpg') > shutil.copy2(newArrivalsDir+'/tn/'+thumb,archivesDir+'/tn/') > > or > > os.rename(otherFavDir+'/'+movie,dir+'/'+movie) > thumb = string.replace(movie,'.avi','.jpg') > os.rename(otherFavDir+'/tn/'+thumb,dir+'/tn'+thumb) > > what varies is the name of the function (shutil.copy2 or os.rename > depending on if I am renaming or copying) and the names of the source > and dest directories. This particular snippet is repeated about a > half-dozen times. Probably time to turn it into a function def moveMovieAndThumb(fromDir, toDir, movieName): # your code or similar. > It would be nice if I could write a function that would determine if the > source and destination are on the same file system or not, and thus use > rename or copy appropriately, or if there is already such a built-in > function. No need to determine it beforehand, just try (untested): def movefile(src, dst): try: os.rename(src, dst) except OSError: shutil.copy2(src, dst) os.remove(src) Of course, if you are using Python 2.3 you should use shutil.move() as pointed out by Serge Orlov; the above was mostly posted to illustrate the popular concept "It's easier to ask forgiveness than permission", i. e. with Python's powerful exception handling mechanism you need not fear the failure of a particular code snippet, as long as you provide the appropriate error handling. Random remarks: - You might take a look at os.path.join() - Ok, this is paranoia, but I would ensure that ".avi" is only at the end of the string - Use methods of the str object rather than functions in the string module, e. g. "abc".replace("a", "d") rather than string.replace("abc", "a", "d") Peter From spiffy at worldnet.att.net Thu Dec 11 16:33:02 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Thu, 11 Dec 2003 21:33:02 GMT Subject: running non-python progs from python References: Message-ID: > I'd just like to add here, I really don't think you were being > "harrassed" at all. I can understand getting frustrated when you > can't get anything working, but from my experience with c.l.p, I > don't think I've ever seen anyone harrased by someone who actually > frequents the list. > > Kris > Thanks for clarifying. From Scott.Daniels at Acm.Org Mon Dec 1 18:07:02 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Dec 2003 15:07:02 -0800 Subject: Shared Memory Modules In-Reply-To: <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> Message-ID: <3fcbd6b8$1@nntp0.pdx.net> Irmen de Jong wrote: > However, I've just tried it, and managed to crash Python in mmap.pyd > with an application exception... twice. But trying to reproduce it > now fails-- Python keeps running. > I did this: > >>> import mmap > >>> mem=mmap.mmap(0,3000000,'irmen') > >>> mem[0]='a' > >>> mem[2000000]='a' > and initially, it crashed......... Python 2.3.2 on win xp) > --Irmen Probably not enough actual memory hanging around. Some systems (and from this I'd guess XP) allocate virtual memory by reserving address space, not actually allocating the RAM and/or backing store for that memory. Python has no control over this, and you have nothing good to do if the memory is over-allocated. When you create the memory, you could walk across it writing into it (forcing it to exist), but that would just force the failure to happen earlier. -Scott David Daniels Scott.Daniels at Acm.Org From bokr at oz.net Mon Dec 29 19:38:36 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Dec 2003 00:38:36 GMT Subject: [puzzle] References: <3fef8612$0$117$3a628fcd@reader2.nntp.hccnet.nl> <3ff0b01f$0$119$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: On Mon, 29 Dec 2003 23:44:07 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >"Terry Reedy" wrote: > >>I don't know what 'Glen Wheeler's problem' is, what your 'antonian' numbers >>are, what 'ISTMT' abbreviates, nor precisely what 'sorted reflected' means >>to your without an example, so I won't try to solve your puzzle. I will >>just comment on the class definition. > [... discussion, code to look at later ;-) ...] > >This probably does the same as Bengts script, but slower. The >advantage was supposed to be that it is not recursive and so it would >be more amenable to splitting it up among a cluster of computers. >Remember that Glen was aiming at N=5 or N=6. It would be possible to >assign a starting and ending tuple to a computer and let it search for >the corresponding hamilton paths within the sequence. After Glen posted """ G(1) = 2 G(2) = 8 (as you show below) G(3) = 144 G(4) = 91 392 G(5) = 187 499 658 240 (I can calculate this in under 8 hours) G(6) = ?? (but it's around 10^24) """ I gave up on brute force counting ;-) I did/do-n't have time to pursue it, but I was toying with recursively breaking it down into combinations of subspace paths and inter-connections, but I got lost in space ;-) Anyway, I wonder if there could be a closed form formula for G(n), and if the formula could be computed somehow, manipulating terms, etc., and then evaluated. Just a fantasy ;-) [...] > >my weird explorations and are also handicapped by my suboptimal >linguistic skills and idiosyncratic terminologies. So let me just >explain my general predisposition to this newsgroup as a source of >interesting programming problems and mathematical, linguistical and >philosophical diversions. That may be a bit different from the general >use as a forum for answering user questions. However, being an amateur >combinatorics enthousiast and hobby programmer this is the way I see >Python: as a tool to explore these kind of subjects, and appropriate >or not c.l.py is just the right kind of inspiration for me, not too >abstract and theoretical as for example mathematics newsgroups and at >the same time full of interesting -and more importantly: framed in an >executable pseudocode language- new concepts. > >It being a shame that hobbyprogrammers are not recognized for their >programming skills -if static typing chauvinists are all you are >worried about, consider yourself lucky- so that it is hard to get a >programming job, the next best thing -or even the better thing if you >can afford it- is to program in Python in an unbounded and free >exploratory fashion, inspired by the people that so generously donate >their ideas to this newsgroup, hoping to get solutions to problems or >presenting them just as ideas to be shared and enjoyed. > >The nice thing about posting it here is that even if nobody >understands what I'm rambling about now, someone else possibly will, >maybe even years and years later, if it is intelligible at all of >course. Another nice thing is that as soon as one hits the send button >the errors immediately appear and disturb one's sleep. This however is >a bit more of an ambiguous advantage. If my posts have reached the >level of unintelligibility of the Ruebot please inform me that I'm >sending spam and if this is backed up by other posters I will find >another place to exhibit my products. At least the code runs, ISTM. > FWIW, I enjoy your posts, even when I don't fully understand. I think it's worth while to have seen an alternate approach to a problem, even if not fully understood or explored. It can help contribute to an aha moment later when exploring similar territory. Happy New Year, Anton, don't go away ;-) Regards, Bengt Richter From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 12:26:08 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 18:26:08 +0100 Subject: Try except - bug? References: <104c369a.0312300851.4f23759e@posting.google.com> Message-ID: Askari: >but I can't understand why doesn't work in my program : > http://www.cvm.qc.ca/9974331/Temp/crypte.py [...] >when I run my program, I have this error : >============ >Traceback (most recent call last): > File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", >line 355, in crypte ^^^ > fileDest.close() >NameError: global name 'fileDest' is not defined >============ That's strange, because there is no fileDest.close() on line 355. Are you sure the message and the code you are showing us correspond? -- Ren? Pijlman From dw-google.com at botanicus.net Sat Dec 13 17:39:52 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 13 Dec 2003 14:39:52 -0800 Subject: Shell quoting as part of the standard library? Message-ID: <99dce321.0312131439.1612dee2@posting.google.com> Hello fellow users! I've been using Python in a couple of different environments for a few years now. I have quite often found that I have needed to deal with filenames which may contain characters that confuse the UNIX shell (space and double quote in particular). Quite a while ago I came up with two simple functions which allowed me to safely build a shell command line quickly. I've used the functions hundreds of times by now, and find myself constantly cut/pasting them into new projects. It is very likely that someone other than myself would find these functions to be useful, and I was wondering if such a thing might find a home in the standard library. http://botanicus.net/dw/tmp/shellquote.py Does this sort of thing have a home in the standard library? It doesn't really apply across platforms, which is my only real concern. Where should it be added to? shutil? If you are thinking of commenting on the way shell_quote_string always quotes, regardless of whether it is needed, please don't. If it acted in a more human-friendly manner then it would be called shell_friendly_quote_string, or something even more insane than that. :) Thanks, David. From mwh at python.net Tue Dec 2 07:52:38 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Dec 2003 12:52:38 GMT Subject: comparing nan "number" References: <87vfp01muq.fsf@pobox.com> <87znebe6ux.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Alexander Schmolck writes: > [...] > > possibly be `False` and {x:"some value}[x] might well raise an exception if > > `x` is a nan (or indeed one of infinitely many Numeric arrays with > [...] > > Don't you mean SomeMapping((x, "some value"))[x]? A dict lookup > doesn't use __eq__. Huh? Yes it does (*after* __hash__, of course, but...). Cheers, mwh -- how am I expected to quit smoking if I have to deal with NT every day -- Ben Raia From please.dont at email.com Tue Dec 23 03:56:46 2003 From: please.dont at email.com (Art Decco) Date: Tue, 23 Dec 2003 08:56:46 GMT Subject: Flat file database References: <7xy8t4m1mw.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote > > Most web hosts offer you access to a database, typically MySQL. Use > that if you can. Implementing what you're asking is harder than it > sounds. What happens if two people connect to your application both > try to update the database at the same time? Actually, I've done it before in Perl. Perl makes multithreaded access to files pretty easy (on Unix). But this case is much easier. It's just for personal use. I'll probably be the only user, so a minimal backup is all I need to do for data integrity. I don't need record locking or even file locking. Of course that may make my case so unusual that no module exists, but it's worth asking before I once again reinvent the concept of a simple flat-file database as I, and most other programmers, have done so many times before. And I don't think MySQL is available without switching to a more expensive type of account. This application, essentially a fancy Christmas card list, just isn't worth all that trouble, but it would be nice if someone knows of a Python module that makes simple text file management a little easier. From jepler at unpythonic.net Wed Dec 31 12:09:56 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 31 Dec 2003 11:09:56 -0600 Subject: timing a web response using urllib.urlopen?? In-Reply-To: References: Message-ID: <20031231170956.GE18443@unpythonic.net> import time t0 = time.time() do something t1 = time.time() print "elapsed time ", t1 - t0, "seconds" In your case, "do something" would be along the lines of f = urllib.urlopen(URL) f.read() to request the URL and read the whole response. Jeff From bokr at oz.net Sun Dec 7 19:49:59 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Dec 2003 00:49:59 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On Sun, 07 Dec 2003 21:39:03 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >Bengt Richter wrote: > >> This sounds very similar to what I have been trying to say. > >I would really suggest that you implement your ideas. You >*will* find that they are unimplementable. After adjusting >the ideas to constraints of reality, you *will* find that >you break backwards compatibility. After fixing the backwards >compatibility problems, you *will* find that your implementation >has very bad performance characteristics, compared to the >existing string types. > >Unfortunately, it is very difficult to nail down the problems >you will encounter, as you refuse to provide a complete I may be failing to communicate, but I am not refusing ;-) >specification of the interface and implementation that you >propose. Originally, I thought you are proposing modifications >to , but now it appears that you are proposing I was, and am (though I confess that discussion is making it a somewhat moving target, as more ideas pop up ;-) >a new data type, which has large similarities with 'unicode'>. If so, I fail to understand why you don't want >to use the existing Unicode type. It's not that I don't want to use it. I think it's great. I am just trying to sort out where the existing str is really being used as a character sequence type and where it is really a byte buffer type that has no character significance until a decoding intepretation is imposed. As I've said, ISTM most string literals in program sources are really character strings, and could well become unicode right in the tokenizer (that part is a new statement ;-) But there are some string literals that really do represent bytes, not characters, and there is a legacy of byte-producing object interfaces that claim to be producing the same type thing (str) as string literals. This is problematic IMO. ISTM there really are two different types that need to be disentangled (charstring vs bytestring, or chars vs bytes for short). I was trying to imagine tweaks to str that could make it play both roles more explicitly, but thinking more, it's probably a wrong approach. Bite the bullet and separate them ;-) OTTOMH I don't thing charstring should be unicode, because that excludes custom character sets that may not exist in unicode, and/or will be a pain to create a private unicode map for. That's why I think charstring must be effectively be something like a (bytestring, codec) pair. Undoubtedly it will have an intimate optimized relationship to unicode. But a charstring type would have the option of delegating efficiently in single-encoding environments, IWT, where things would work much as they do now. How to bring in the bytestring type is "interesting". I guess one approach would be to let it be str minus its current charstring uses. But there's so many charstring uses that maybe it makes more sense to let str be the charstring. But there are so much legacy interfaces that produce bytestrings as str ;-/ Round and round. So I am pulled back the idea of .coding-attributed str's, even though it's not too clean. Maybe charstrings as a str subclass? Ugh. I think conceptual correctness (or lack thereof) has bitten ;-/ > >Notice that /F has something completely different in mind: >He is still talking about the Python Unicode type, and just >suggesting that a different internal representation should >be used. Speculating about the motivation, I would think he >has efficiency in the face of round-trip conversions in mind, >but not a change in visible behaviour. That's not completely different ;-) I was trying to tweak str to play its dual roles of charstring and bytestring explicitly, and I think the charstring side is almost exactly what /F was talking about. A reasonable implementation would be to have charstring be /F's unicode exactly, though I'm always wanting to be "conceptually correct" so the concept of charstring would have to include totally arbitrary character sets, not just those found in unicode ;-) Regards, Bengt Richter From andreif at mail.dntis.ro Tue Dec 23 15:56:46 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 23 Dec 2003 12:56:46 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <7xad5jh8q2.fsf@ruckus.brouhaha.com> Message-ID: <21bb8d55.0312231256.6fcef8b7@posting.google.com> Paul Rubin wrote in message news:<7xad5jh8q2.fsf at ruckus.brouhaha.com>... > John Hunter writes: > > Stormbringer> in my opinion (especially considering the range of > > Stormbringer> those integers - one is in the range 1..100000 and > > Stormbringer> the other in the range 1..500000). > > > > What about using a binary file of unsigned ints which you load into a > > python dictionary and do everything in memory? There would be no > > extra overhead in the file and it would be very fast, if you are able > > to hold the 100,000 ints in memory. > > No it's much worse than that. The 100,000 ints are index numbers > for individual words. The 500,000 ints are articles and there can > be thousands of words in each article. So you may need to store > billions of ints, not just 100,000 of them. Yes, I agree. The messages aren't very large (under 5K each, although I've seen one or two of 500K) but there are lots of words. Turns out there is a much better solution than what I could have written, and it's named Lupy. Andrei From jjl at pobox.com Wed Dec 17 09:24:25 2003 From: jjl at pobox.com (John J. Lee) Date: 17 Dec 2003 14:24:25 +0000 Subject: Python in a spreadsheet References: <3064b51d.0312151318.277c8c06@posting.google.com> Message-ID: <87iskffrom.fsf@pobox.com> Nick Vargish writes: > beliavsky at aol.com writes: > > > Is it possible to call a Python function from Calc (the Open Office > > spreadsheet) or Microsoft Excel? Are their web sites or books > > describing how to do this? > > You could check out the latest version of StarOffice from Sun (version > 7, I believe) -- apparently it has Python scripting support built-in. > > I found that pretty interesting... Isn't Sun committed to something > called Joe or Java or something like that? Yeah, but that's for the "enterprise technologists" -- I could think of another word for them, though . John From deets_noospaam at web.de Tue Dec 9 09:53:26 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 15:53:26 +0100 Subject: parsing equations References: Message-ID: > i have a question. > Given the string '3+2*6' i need to parse it and obtain the result, so > 15. Does a module for this operation exists? i need to do simple > operations, but also on floating point numbers. Use the builtin function eval to evaluate an arbitrary python expression: >>> eval("3+2*6") 15 Regards, Diez From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 30 05:07:11 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Dec 2003 11:07:11 +0100 Subject: Newbie question about memory management In-Reply-To: References: Message-ID: <3ff14e4f$0$317$e4fe514c@news.xs4all.nl> Oh Kyu Yoon wrote: > I am writing my first python program, and I have to deal with several lists > of double precision numbers that are about 10,000,000 in length. > If I have 5 such lists, 5 x 10,000,000 x 8bytes ~ 400 MB which is too much > for the computer memory. > Does anyone have better strategies to do this? Yes; keep them on disk. All of them, most of them, or partially, you don't tell us what you're doing with the lists, and so it is hard to guess what would be the best approach. --Irmen. P.S. also look at the 'array' module. From eppstein at ics.uci.edu Fri Dec 19 17:49:10 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 19 Dec 2003 14:49:10 -0800 Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: In article , bokr at oz.net (Bengt Richter) wrote: > Here is one that works also for negative numbers (includes the least > significant > of the arbitrarily extended sign bits): > > >>> def bitnos(self): > ... """Little-endian bit number generator""" > ... bits = long(self) > ... sign = bits<0 > ... bitno = 0 > ... while bits>0 or sign and bits!=-1L: > ... if bits&1: yield bitno > ... bitno += 1 > ... bits >>= 1 > ... if sign: yield bitno > ... I'm not sure I would call that working -- what I'd expect for a negative number is to generate an infinite sequence. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From hokiegal99 at hotmail.com Tue Dec 23 11:22:12 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 11:22:12 -0500 Subject: return statement in functions In-Reply-To: <3fe86429$0$186$e4fe514c@news.xs4all.nl> References: <93f5c5e9.0312221718.23e42dac@posting.google.com> <3fe86429$0$186$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > hokieghal99 wrote: > >> Here's how I call the report function: >> >> report(fs_object_count,clean_dir_names,etc., etc.) >> > > You're forgetting to actually *call* the other functions too, > (you just pass the functions themselves, as you see in your output, > Python prints the function objects that you pass to the report > function). > So try this: > > report(fs_object_count(),clean_dir_names(),...) > > these you forgot: ^^ ^^ > > > --Irmen That did it. Many thanks to you!!! From hans at zephyrfalcon.org Fri Dec 19 00:02:34 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 19 Dec 2003 00:02:34 -0500 Subject: Default attribute in base class precludes delegation In-Reply-To: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> References: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> Message-ID: <3FE2866A.3090500@zephyrfalcon.org> Gabriel Genellina wrote: > Hi > > In the following code sample, I have: > - a Worker class, which could have a lot of methods and attributes. In > particular, it has a 'bar' attribute. This class can be modified as needed. > - a Base class (old-style) which defines a default class attribute 'bar' > too. I can't modify the source code of this class. Note that Workes does > not inherit from Base. > - a Derived class which must inherit from Base and is a wrapper around > Worker: it contains a Worker instance and delegates almost anything to > it. This class can be modified as needed too. > > For most attributes, as they are not found in the Derived instance's > dict, __getattr__ is called and the attribute is retrieved from the > Worker instance. > But for the 'bar' attribute, it is found in the Base class and just the > default value is returned. __getattr__ is never called. > I need to avoid this, and return Worker instance's value instead of > Base's default value. > That is, in the last line of the example, I want: d.bar == 'Hello' > How could it be done? > > --- cut --- > # This class does the "real" work and I can modify it as needed > class Worker: > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > # This is just a base class from which I must inherit but I can't modify it > class Base: > bar = None > > # This is a wrapper for Worker and I can modify it. > # I want to get most attributes from Worker class > # but for 'bar' I always get the default from Base, > # its declaration there effectively hides the attribute > # from the delegated Worked instance. > class Derived(Base): > def __init__(self, worker): > self.worker = worker > > def __getattr__(self, name): > return getattr(self.worker, name) > > w = Worker(1234, 'Hello') > print 'w.foo', w.foo # prints 1234 > print 'w.bar', w.bar # prints Hello > d = Derived(w) > print 'd.foo',d.foo # prints 1234 > print 'd.bar',d.bar # prints None, I want to get Hello As you already found out, d.bar looks up Base.bar, and __getattr__ isn't invoked (since it is only called if an attribute is *not* found). The easiest solution might be, to change the name of the attribute 'bar' in Worker, since you can modify this class. If at all possible, make sure it has no attribute names that are defined in Base also. Is this an acceptable solution for you? It sounds cheesy, but it might be better than inventing all kinds of twisted code constructs to get around this problem. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From raims at dot.com Mon Dec 29 06:59:23 2003 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 29 Dec 2003 12:59:23 +0100 Subject: ANN: Python Language Reference References: Message-ID: <87d6a77s2s.fsf@mobile.foo> hwlgw at hotmail.com (Will Stuyvesant) writes: > But isn't Lynx text-only? I want to see the pics! Even though I am > not the kind of pervert that want to do things to them with the mouse. I think that Lynx in framebuffer should display images too. I'm not sure because i use Links not Lynx :) -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From tjreedy at udel.edu Sat Dec 13 16:54:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Dec 2003 16:54:10 -0500 Subject: ANN: lunatic-python 0.1 References: Message-ID: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> "Bengt Richter" wrote in message news:brfq00$so5$0 at 216.39.172.122... > On Sat, 13 Dec 2003 04:05:39 -0200, Gustavo Niemeyer wrote: > > >https://moin.conectiva.com.br/LunaticPython > Why the https? > > I expect you have a good explanation, but why not allow the explanation to be > seen via plain http, e.g., on an introductory page that might also tell > enough about the project so people can decide whether they want to go further? Accessing above with default IE6 brings up Untrusted Certificate page. With choices Proceed, Stop, AddCertificate (to root table). It seems conectiva issued itself its own certificate. I hope this is just silliness rather than a devious attempt to get people to accept its self-certification, which I was not about to do. I know enough that I thought it probably safe to proceed without adding cert, but not enough to be sure. Some people would stop there, and I might have on another day. I recommend you take this up with conectiva. Terry J. Reedy From dave at pythonapocrypha.com Tue Dec 2 12:37:05 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 2 Dec 2003 10:37:05 -0700 Subject: python's threading has no "interrupt"? References: Message-ID: <047f01c3b8fa$e7430610$6500000a@YODA> Jay wrote: > >So, if I understand this correctly, this amounted to a manual task switcher, > >right? (as no more than one job was allowed to run concurrently). Was this > >really the desired behavior? If each process halts while the others run and > >does so only to prevent starvation in the other processes, wouldn't you get > >more or less the same results by just using normal forking/threading wherein > >the OS ensures that each process/thread gets a slice of the CPU pie? (IOW, > >unless there was some other reason, it seems that the explicit yielding was to > >work around the constraints of the process model) > > Partially, the processes were sharing a (sometimes very large) common > in-memory object web so forking seperate os level threads was not > feasible. Also, the server ran on multiple OS platforms so OS level > tricks or threading mechanisms were not viable Ok, but it should still be very doable with just threads (as opposed to forking new processes - although forking might still work well with shared memory), and preemptive threading is more the norm than not these days, at least on the OS's that Python runs on - so having the OS schedule the threads doesn't require any special "tricks", it just works. > So... what was going wrong that warranted killing the process in the first > > >In practice the need for that is pretty rare, especially for a server, > >the main case coming to mind being the execution of user-supplied code (which > >is pretty scary in and of itself!). > > Irt didn't happen that often but it was mostly due to the client > disconneecting permaturely and when yuor server is handling heavy > traffic, it does become a resource issue after awhile. Having the handler detect and clean up by itself after a premature client disconnect is both cleaner and results in _lower_ average resource usage because it could be detected much more quickly and reliably than some watchdog thread (this approach can work well on both poll-based and threaded connection handling). You'd also get the benefit of more information in making the decision: a watchdog cannot distinguish between slow progress and no progress. > Like I said in > anoter post, there was also bookkeeping down during this time as well. Again though, you get the scheduling "for free", so e.g. there's no problem with having a bookkeeping thread in Python either. -Dave From tjreedy at udel.edu Tue Dec 30 13:21:58 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 13:21:58 -0500 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> <87ad5a2s08.fsf@strauser.com> Message-ID: >> def ishexnumber(sx): >> import re > If I run this many times, as is likely in our application, does the > 'import re' chew up memory? No. Imported modules are cached in sys.modules. After the first import, 'import x' is equivalent to "x = sys.modules['x']" (or something like this). From mbabcock at fibrespeed.net Fri Dec 12 12:13:01 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Fri, 12 Dec 2003 12:13:01 -0500 Subject: Kinda newb-ish question In-Reply-To: References: Message-ID: <3FD9F71D.8000506@fibrespeed.net> python-list-request at python.org wrote: >x=1 >while 1==1: > x=x+1 > y=range(1,x) > z=0 > q=9 > for count in y: > q=x%y > if q==0: > z=z+1 > > y is a range, you defined it earlier. count is the current item in y for any given loop, so you probably wanted to say q = x % count. Right? -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From lists at webcrunchers.com Mon Dec 15 21:56:21 2003 From: lists at webcrunchers.com (JD) Date: Mon, 15 Dec 2003 18:56:21 -0800 Subject: More info on my Python problem... Message-ID: <6D9E18D1-2F73-11D8-BFA1-0030656C6B9E@webcrunchers.com> This is more details about my problem, which I already managed to post as a Python bug to Sourceforge This problem is not related to the bug I encountered earlier, and this is related to a question I have about Python hanging up either from a shell, or my importing a module. I want to figure out if this really IS a python bug, but I suspect that if it hangs up the console, it would be a bug. Is there someone who I might contact via phone to walk me through this? (Assuming I can't get adequate information here? Or does anyone care about Python bugs?) This is in Python 2.3.3c1 on OpenBSD (though I doubt the OS matters). The symptom is that I run my program and Python locks up. I cannot control-C or control-D to get out of it; I have to log in separately and kill -9 the process. The process is listed as "D+" while it is hung, though it doesn't seem to be accessing the disk, and I'm quite sure there are no disk problems (though I'm not physically next to the server, so I can't check the drive LED). How should I approach debugging this? Are there Python tools? Or should I use gdb? ktrace? systrace? I'm assuming I have to do this, as a bug report which reads "Python locks up" isn't to useful. John From fredrik at pythonware.com Wed Dec 3 14:46:17 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Dec 2003 20:46:17 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE3352.2040504@rogers.com> Message-ID: Mike C. Fletcher wrote: > >0xED has never been a valid 7-bit ASCII character. > > Sure, but Python used to accept 8-bit characters in the platform's > default encoding as part of string characters... all 2.3 installs I have give me a DeprecationWarning when I do that, not a UnicodeDecodeError. what version are you using? From fperez528 at yahoo.com Mon Dec 22 20:53:31 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 22 Dec 2003 18:53:31 -0700 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: John Roth wrote: > Another is the pervasive use of the visitor pattern, and > a third is the ability to forget the empty parenthesis after > a function/method call that doesn't require parameters. I briefly scanned the thread, and didn't see (perhaps I missed it) anyone metioning how this collides with the whole 'callables as first class objects' philosophy of python. Maybe I'm missing something (I don't know a thing about Ruby, so I'll speak strictly from the python side), but if parens were optional, how would the following work? # Here I want the function local_fn = some.nested.module.function # Here I want the result local_var = some.nested.module.function() Or: try: function_table[key] except KeyError: # do something In this case, I DON'T want the function called, I just need to know if I have it. Anyway, in my code I have tons of cases where I critically need to distinguish between using a 'naked' function and calling it, and I find it always a pleasure that in python, simply using () or not allows me to, unambiguously, handle both cases. Perhaps there is an alternative which I haven't seen or understood, but I'm genuinely interested in how you'd approach this issue if the () were optional. I'm also curious about how it is handled in the Ruby world, which as I said I'm not familiar with. Regards, f. From theller at python.net Wed Dec 17 16:07:39 2003 From: theller at python.net (Thomas Heller) Date: Wed, 17 Dec 2003 22:07:39 +0100 Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> <93f5c5e9.0312161912.3f5c5bc4@posting.google.com> Message-ID: Derrick 'dman' Hudson writes: > On 16 Dec 2003 19:12:34 -0800, hokiegal99 wrote: >> William Park wrote in message news:... >>> Heike C. Zimmerer wrote: >>> > William Park writes: > >>> > > FYI, in shell, you would go >>> > > find . -type f -name '*.mp3' | xargs rm >>> > >>> > Which will fail if the file name contains any spaces or other special >>> > characters (not too unusual for .mp3 - Files). >>> >>> In which case, you look up 'man find xargs' and edit the command to >>> find ... -print0 | xargs -0 ... >> >> What would you man on a Windows box??? > > Start by clicking > Start -> Programs -> Cygwin -> Bash Shell No, enter 'del /s *.mp3' at the command prompt. If you are running windows, you should know it. From borcis at users.ch Fri Dec 19 08:21:16 2003 From: borcis at users.ch (Borcis) Date: Fri, 19 Dec 2003 14:21:16 +0100 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: <3FE2FB4C.5020909@users.ch> Glen Wheeler wrote: > I'm using one dictionary to store all of the data, with tuples of > ints as keys and a tuple as the data associated with each key. The > data tuples contain a few ints and two more dictionaries. > Can you think of a way to reduce the memory used here? What's the length of the key tuples, and are there bounds on the component ints ? Is the number of ints in the data tuples fixed ? What's in the subdictionnaries, typically ? "millions of 5 bit integers" hints of the possibility of a radical change of representation, but a radical change of representation can only be devised if we know what's stable - the task. From jester.dev at NOSPAMcomcast.net Thu Dec 11 18:20:01 2003 From: jester.dev at NOSPAMcomcast.net (Lord Jester) Date: Thu, 11 Dec 2003 23:20:01 GMT Subject: Linux GUI for python? Message-ID: Looking for any suggestions for a GUI for python under linux. Right now I'm just starting out but latter on I want to get into building programs that have GUIs. Any suggestions? From mshapiro at sunlitsurf.com Thu Dec 18 12:55:36 2003 From: mshapiro at sunlitsurf.com (Marc Shapiro) Date: Thu, 18 Dec 2003 12:55:36 -0500 Subject: Calling a function in __main__ from a module? Message-ID: I am relatively new to python (I have used it on and off for a few small projects over the last few years) so I imagine that what I am trying to do has already been done, but practical experience, even if it is reinventing the wheel, is still useful, so... I am trying to write a module to handle drop down menus using curses (on linux). Curses seems to have a wrapper for the panels library, but not forms, or menus. I am not even sure that the menus library would give me what I want (as I also do not have much curses experience in other languages), so I am writing my own module. The code works fine if I include it with my application code in a singe file. If I seperate out the menu class and related functions into a seperate module, however, then when I try to have it call a funtion in the man (calling) file I get an error saying: Traceback (most recent call last): File "./hp", line 62, in ? curses.wrapper(main) File "/usr/lib/python2.3/curses/wrapper.py", line 44, in wrapper res = func(stdscr, *rest) File "./hp", line 58, in main mb.mainloop(items) File "/home/mns/menu.py", line 258, in mainloop exec cmd + "('" + name + "')" File "", line 1, in ? NameError: name 'NOP' is not defined 'NOP' is the name of the function that I am trying to call. It does not exist in the menu module, but is in the calling (hp) module. I can't qualify the name (i.e. __main__.NOP() ) since __main__ can not be used for qualification, only called module names can be used that way. How do I get the module to call functions in a parent module. Tkinter would set up a callback function and bind it to an event. Can something similar be done for a console program using curses? -- Marc Shapiro -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From mwh at python.net Fri Dec 26 05:36:14 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Dec 2003 10:36:14 GMT Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: "Martin v. L?wis" writes: > Michael Hudson wrote: > > > True. I don't know if the various linkers around are smart enough to > > not load debugging information until it's asked for... > > Atleast on Unix, not mapping debug information at run time has a long > tradition. In ELF, each section has a LOAD flag indicating whether > a section needs to be mapped or not. So the ELF dynamic loader does > not specifically know to omit debug information, but only loads > sections that the static linker told it to. That makes sense. I also guess that as shared libraries are mmaped into the applications address space they won't use physical memory until referenced anyway. But relocations probably mess with that. Cheers, mwh -- The ultimate laziness is not using Perl. That saves you so much work you wouldn't believe it if you had never tried it. -- Erik Naggum, comp.lang.lisp From cr88192 at hotmail.com Thu Dec 25 01:58:10 2003 From: cr88192 at hotmail.com (cr88192) Date: Wed, 24 Dec 2003 22:58:10 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: I am mostly responding because I found it amusing that I disagreed with nearly every point mentioned here, this is not meant as any kind of discouragement though... it is quite likely that I just have a very much different set of ideals... From marko.faldix.tudisweck at mplusr.de Mon Dec 15 08:38:59 2003 From: marko.faldix.tudisweck at mplusr.de (Marko Faldix) Date: Mon, 15 Dec 2003 14:38:59 +0100 Subject: codecs latin1 unicode standard output file References: Message-ID: Hi, "Fredrik Lundh" schrieb im Newsbeitrag news:mailman.148.1071488341.9307.python-list at python.org... > Marko Faldix wrote: > > > I try to describe. It's a Window machine with Python 2.3.2 installed. Using > > command line (cmd). Put these lines of code in a file called klotentest1.py: > > > > # -*- coding: iso-8859-1 -*- > > > > print unicode("My umlauts are ?, ?, ?", "latin-1") > > print "My umlauts are ?, ?, ?" > > > > Calling this on command line: > > > > klotentest1.py > > > > Indeed, result of first print is as desired, result of second print delivers > > strange letters but no error. > > your console device doesn't use iso-8859-1; it probably uses cp850. > if you print an 8-bit string to the console, Python assumes that you > know what you're doing... > > > Now I call this on command line: > > > > klotentest1.py > klotentest1.txt > > > > This fails: > > Traceback (most recent call last): > > File "C:\home\marko\moeller_port\moeller_port_exec_svn\klotentest1.py", line > > 3, in ? > > print unicode("My umlauts are ?, ?, ?", "latin-1") > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position > > 15: ordinal not in range(128) > > > > In my point of view python shouldn't act in different ways whether result is > > piped to file or not. > > when you print to a console with a known encoding, Python 2.3 auto- > magically converts Unicode strings to 8-bit strings using the console > encoding. > > files don't have an encoding, which is why the second case fails. > > also note that in 2.2 and earlier, you example always failed. > > So I just have to use only this: print "My umlauts are ?, ?, ?" without any encoding-assignment to use for standard output on console AND redirecting to file. In latter case, it looks nice with e.g. notepad, just strange on console, so settings for console are to adjust and not python code. Right? Marko Faldix From http Wed Dec 17 17:52:41 2003 From: http (Paul Rubin) Date: 17 Dec 2003 14:52:41 -0800 Subject: I see advice on how to debug a python module that hangs up the process References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: <7xr7z32h1i.fsf@ruckus.brouhaha.com> JD writes: > I think this is a job for kernal-trace, or gdb (low level debugger), > and this is what I need to now how to do. Running Python under gdb isn't terribly difficult. What's the problem? Also, if you mentioned whether your program uses threads, I missed it. From mcherm at mcherm.com Tue Dec 16 10:13:21 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 16 Dec 2003 07:13:21 -0800 Subject: rexec.py unuseable Message-ID: <1071587601.3fdf2111afc59@mcherm.com> I (Michael) wrote: [Speaking of how to provide restricted execution in Python] > Actually, I rather prefer the approach that has been mentioned before > of trying to use capabilities. > See, for instance, the threads on > Capabilities found here: > http://mail.python.org/pipermail/python-dev/2003-March/thread.html#33854 Luke replied: > capabilities, acls, schmapabilities, same thiiing :) No... they're not. Read the thread I mentioned above, or read this, and some of the other documentation for the language E: http://www.erights.org/elib/capability/ode/ode-capabilities.html Later Luke writes: > btw yes you're right, it's better off called "capabilities" > but the name CCLs - capability control lists - is a bit of > a mouthful :) Again, I mean something different, NOT CCLs, but capabilities. Hmm... how about a quick summary from me (but I'm not an expert). Suppose that had some code which had an object representing a directory, with a method "open(filename, mode='r')" that opened files in the directory. Given this object, you could imagine constructing new objects with more limited capabilities. For instance, you might create a readOnlyDirectory object which had a method "open(filename)" that didn't allow specifying the mode as anything but 'r'. Or you might open a file and then pass a file object with "read()", "write()", "seek()", and other such methods, which would only access that file. So _IF_ the only way to access files were through this object (and that's a BIG if), then you could imagine a world where HAVING and object was equivalent to being able to do something. If a bit of code had access to a read-only-file object then it could read that file, but couldn't write to it, or do anything else with the file system unless it ALSO had access to some OTHER objects. That's capabilities... and it would work for most kinds of restricted resources, not just the file system. The key idea is that HAVING a pointer to the object is equivalent to having the permission to USE that object, and whatever it provides access to. There are several ways to "escape" out of this system. One way is to access some global ability... for instance, you might use the "open()" function from __builtins__. For capabilities to work in Python access to "dangerous" globals would need to be restricted. Another way is to just create an object out of nowhere, or forge a pointer to an object. Fortunately, in Python these are already impossible... pure Python code cannot forge references or create objects without access to the type or class. (C extensions can do anything and are unsafe.) Another way is to access the more powerful object that "empowers" a less powerful one... perhaps using the (supposed to be private) _directory field in the readOnlyfile object. So capabilities in Python are impossible without some sort of private data for objects (this is not a particularly onerous requirement). Yet *another* approach would be to use introspection... for instance, in Python today, given any file object, the class itself ("file") can be obtained via introspection, and then used to create other file objects. Using capabilities in Python would require that "restricted" objects have some more limited form of introspection... perhaps one could only obtain a "fake" class object which had a __equals__ method that simulated being the real class, but which had no __init__ so it couldn't be used to create new instances. At any rate, you get the idea. Capabilities are possible in Python only if some sort of "restricted mode" is created, which restricts access to some built-in abilities and which creates "restricted" objects with some private data and limited introspection. But IF you had these things (and they're NOT trivial), then capabilities may be a conceptually more elegant approach than ACLs, lleading to more elegant programs. -- Michael Chermside From michele.simionato at poste.it Fri Dec 12 01:28:49 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 11 Dec 2003 22:28:49 -0800 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> <3fd7bf36$0$28702$626a54ce@news.free.fr> <8ef9bea6.0312111011.6a49053d@posting.google.com> Message-ID: <95aa1afa.0312112228.7f0e09e8@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0312111011.6a49053d at posting.google.com>... > When I saw that it > has codeblocks ("block" in Io syntax) and weaklinks, I told myself: > "OK, really smart". When I saw that it can print the source code of a > block, I told myself: "OK, extremely smart". :) Why do you want to print out the source code of a block? Are you thinking about dynamic modification of the source code and recompilation of the code block on the fly? If you want those features then lisp-like languages are a natural choice. Or do you have something else in mind ? Michele From r.s at XXmindspring.com Sat Dec 6 03:42:33 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Sat, 06 Dec 2003 08:42:33 GMT Subject: min and max id numbers References: <0_dAb.983$_r6.908@newsread1.news.pas.earthlink.net> <7xhe0ejy3t.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote ... > The id of an object in CPython is just its memory address. Obviously > you could not guarantee the HI object staying higher than all the > other objects since the interpreter can always allocate more memory. > To do what you're asking you'd have to modify the interpreter to have > a new kind of sentinel object and have ident return special values for > those objects. I guess you could do that if you really wanted, but it > would be a crazy crock. Well, I only meant it as a "crazy crock" kind of game, but without modifying the interpreter. Suppose Jane is allowed N keystrokes at Python's interactive window, then likewise for John, and none of their own code can be imported. Say anyone making the machine hang, or not come back to the prompt within 5 minutes, loses. The machine only has so much memory, so is it really obvious that John can always create an object HI-er than any of Jane's? (Sorry if in my ignorance I'm imagining an altogether ridiculous scenario ;o) From wilkSPAM at OUTflibuste.net Mon Dec 22 11:53:27 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Mon, 22 Dec 2003 17:53:27 +0100 Subject: web programming: experiences with non-zope frameworks? References: Message-ID: <87llp44wvs.fsf@blakie.riol> Hi, I think the first thing is to choose if you prefer a thread, fork or event driven engine. Also, will you have to handle differents protocols ? I choose twistedmatrix for his event driven asychore engine, multi-procols. http://twistedmatrix.com After, you maybe need a template engine, you must choose if you want a template graphist-friendly or not. For this we choose (with my graphist) Cheetah. http://cheetahtemplate.org But sometimes i use cgi or BaseHTTPServer and my own little framework and template engine... Because it's finaly quite easy to do it (it's why there are so many of them maybe). I use all of this in production without any problem of scalability (a lot less than with php) I think the web frameworks are very stable (instead of classic applications) because they are immediatly tested with a lot of users and the errors are easy to catch. So don't worry about the pioneer condition of python web programmers ;-) For other things, like sql, it's like every python application... There is a web-sig now to discuss about a common api/interface. http://www.python.org/sigs/web-sig/ bye -- Wilk - http://flibuste.net From mir4uu at yahoo.com Wed Dec 24 02:05:09 2003 From: mir4uu at yahoo.com (mir nazim) Date: 23 Dec 2003 23:05:09 -0800 Subject: Flat file database References: Message-ID: <425cc8d1.0312232305.777e8ca0@posting.google.com> Rony wrote in message news:... > Art Decco wrote on Tue, 23 Dec 2003 07:07:32 GMT in : > > > Is there any Python module designed to simplify the use of a plain text file > > as a flat file database? > > > > ... > > You could have a look at kirbybase > > Rony > -- > Rony > > /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ > / bucodi_no_spam at yahoo.fr (delete _no_spam) > / > | www.bucodi.com - My work > \ www.ifrance/karamusique -- My hobby > \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ yeh, Ront is right, it is a plain simple python program (one file). if u can do without sql, it may be helpful. get it here http://www.netpromi.com/kirbase From dennis.posadas at intel.com Tue Dec 9 18:04:00 2003 From: dennis.posadas at intel.com (Posadas, Dennis) Date: Wed, 10 Dec 2003 07:04:00 +0800 Subject: python unicode display of chinese characters Message-ID: Hi, I've done some google searching w/c referred me to a couple of articles on unicode, but I'm looking for something really simple - not for a web application. See my sample code below. Any ideas how to convert it to display maybe Simplified Chinese ? Rgds, Dennis ==================================================== #ucode.py #get unicode number ucode_num = str(raw_input('Enter the string : ')) #define constants encode_type = 'utf-8' display_type = 'cp-347' #for IBM consoles #define unicode character_display = unicode(ucode_num, encode_type) #print character to be displayed print character_display.encode(display_type) From mensanator at aol.compost Mon Dec 1 00:35:48 2003 From: mensanator at aol.compost (Mensanator) Date: 01 Dec 2003 05:35:48 GMT Subject: Python Learning Foundation References: Message-ID: <20031201003548.16817.00001258@mb-m07.aol.com> >Subject: Re: Python Learning Foundation >From: bokr at oz.net (Bengt Richter) >Date: 11/30/03 9:51 PM Central Standard Time >Message-id: > >On 01 Dec 2003 03:19:07 GMT, mensanator at aol.compost (Mensanator) wrote: > >>>Subject: Python Learning Foundation >>>From: rstephens at vectron.com (Ron Stephens) >>>Date: 11/30/2003 7:40 PM Central Standard Time >>>Message-id: >>> >>>The newly rechristened Python Learning Foundation is a web site >>>dedicated to the assistance of people learning the Python programming >>>language. Features include: >>> >>>1. Daily lists of new and recent Python-related web articles, >>>Sourceforge projects, and Vaults of Parnassus listings. These are >>>generated using Hans Nowak's Python web spider, mygale.py, and are >>>automatically updated each day. (You can visit Han's interesting blog >>>at zephyrfalcon ) >On a plain text newsreader that last line was (changing '<' and '>' to '[' >and ']' resp): > >at [a href = "http://www.zephyrfalcon.org/weblog/"]zephyrfalcon[/a] ) > >>> >>>2. Now, there are also daily postings of new and recent web articles, >>>Sourceforge projects and etcetera for four additional categories, >>>Zope, Jython, Tkinter, and wxPython, as well as historical listings of >>>web articles on these subjects. Other specific topics can be covered >>>regularly upon user request. >>> >>>3. Links to 76 online tutorials about Python and Python related >>>subjects. >>> >>>4. More than 28 reviews of books about Python. >>> >>>There are many other topics and features covered in the web site, and, >>>of course, the best is yet to come. >>> >>>Please visit the Python >changing angle brackets to square brackets as above, that last line was: >Please visit the [a href = "http://www.awaretek.com/plf.html"]Python > >>>Learning Foundation. >> >>Would a URL be too much to ask for? >You can probably see it if you look at the source text of the post. >Your reader apparently interpreted the HTML (which shouldn't be posted >to the newsgroup anyway except as code examples, but OTOH your reader >will probably have problems showing you HTML code examples). Thanks. My reader (AOL) will make an un-tagged URL, such as http://www.awaretek.com/plf.html into an active link. It makes no sense that it would interpret the tags so that they disappear from view and yet not actually make the enclosed text into a link. Bastards. > >Regards, >Bengt Richter > > > > > > > -- Mensanator Ace of Clubs From ulysses_dm at yahoo.com.cn Fri Dec 5 03:48:15 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 5 Dec 2003 00:48:15 -0800 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> <43e3984e.0311230527.74eed7a3@posting.google.com> <43e3984e.0312030436.3640d21b@posting.google.com> Message-ID: <43e3984e.0312050048.1948e841@posting.google.com> Dear sir, I post a bug report with demo app in python in SF. Track Number is 854589 ,subject is "Can't use GetText in win32,i386" . Please help me. Thanks. Ulysses martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > ulysses_dm at yahoo.com.cn (ulysses) writes: > > > > Can you please post a bug report to SourceForge then? Please include > > > the .mo file, and a small Python script showing the error. > > > Do you mean http://gettext.sourceforge.net/ ? > > No, sf.net/projects/python > > > Can I Email to you , sample script and MO file. > > I promise It's very small . I don't how to write to SF. > > Please don't. Just request an SF account, and submit a bug report. > > Regards, > Martin From mwh at python.net Thu Dec 25 06:42:31 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Dec 2003 11:42:31 GMT Subject: 2.3 list reverse() bug? References: Message-ID: cartermark46 at ukmail.com (Mark Carter) writes: > I did this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > > >>> d1 = [1,2] > >>> d2 = d1 > >>> d2.reverse() > >>> print d1 #note: d1, not d2 > [2, 1] > >>> > > Surely that can't be right: d1 should still be [1,2]. If it is > "right", then I expect that many people are in for a suprise. Try reading this: http://starship.python.net/crew/mwh/hacks/objectthink.html Happy Christmas everyone! Cheers, mwh -- Counting lines is probably a good idea if you want to print it out and are short on paper, but I fail to see the purpose otherwise. -- Erik Naggum, comp.lang.lisp From oren-py-l at hishome.net Sat Dec 20 07:15:21 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 20 Dec 2003 07:15:21 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <20031220121521.GA99675@hishome.net> On Fri, Dec 19, 2003 at 07:29:57PM -0500, John Roth wrote: > "Ville Vainio" wrote in message > news:du7ekv0z7g3.fsf at amadeus.cc.tut.fi... > > I don't know if you have seen this before, but here goes: > > > > http://text.userlinux.com/white_paper.html > > > > There is a jab at Python, though, mentioning that Ruby is more > > "refined". > > I'm not sure about refined, but it does seem to have several > things that I think I'd like. One is a much > better way of handling anonymous functions, aka "blocks." > Another is the pervasive use of the visitor pattern, and I've always considered the visitor pattern as a rather poor substitute for generators, not as a something worth having for its own sake. Using generators instead of visitors+anonymous functions obviously reduces the need for anonymous functions (not that it's any excuse for not having something better than Python's lambdas!). Oren From http Sat Dec 13 02:47:52 2003 From: http (Paul Rubin) Date: 12 Dec 2003 23:47:52 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3FD9D38F.C85433C9@engcorp.com> Message-ID: <7x8ylhgnvb.fsf@ruckus.brouhaha.com> Jarek Zgoda writes: > > It surprises me that you write that. I regard Tcl as the > > language which has gone the farthest in internationalization, > > No, I don't mean "broken unicode support", the problem lies in Python > interfacing with Tk, when Python's unicode means something different, > than Tk unicode. I thought python supported only 16 bit Unicode so it can't fully interoperate with a 32-bit implementation. From newsgroups at jhrothjr.com Sat Dec 20 16:13:16 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 16:13:16 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <2rkeb1-fs3.ln1@beastie.ix.netcom.com> Message-ID: "Dennis Lee Bieber" wrote in message news:2rkeb1-fs3.ln1 at beastie.ix.netcom.com... > John Roth fed this fish to the penguins on Saturday 20 December 2003 > 04:19 am: > > > > > > John Osterhout (TCL). I want a language I can embed in tools as a > > common scripting language. > > > Given that last entry, I'll speak blasphemy since I feel there is a > fifth candidate. REXX, especially as implemented on the Amiga, /was/ > such a common scripting language without needing to be "embedded" > within the application/tool (it actually was done in a way that > permitted one script to glue multiple "tools" together). Oh, there were a lot of those languages, but that was what Osterhout wanted for TCL - something that could be embedded in various tools. He had a problem, and it was lots of tools, each of which used its own special purpose, completely incompatible and usually poorly implemented language. REXX was very much a niche specific language, mostly on IBM systems (because IBM also wanted to consolidate languages.) It grew beyond there, but not by all that much. Part of it's quirky charm is the way that it's i/o system faithfully mirrored the old VM/CMS system. John Roth ============================================= < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From http Tue Dec 16 03:54:02 2003 From: http (Paul Rubin) Date: 16 Dec 2003 00:54:02 -0800 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: <7xhe0116tx.fsf@ruckus.brouhaha.com> matt at killermookie.org (Matthew Sims) writes: > For lists, I understand this: > C=["need","some","help"] > print C[1] > some > > But I can't seem to do this: > C[3]="here" > > I know about C.append("here") but this brings me to my question... > > Is there anyway to assign to an element that wasn't defined in the > beginning? Like if I wanted element 5 assigned but not element 4 > without using "" or None? The simplest way is with a dictionary instead of a list: D = {0:"need", 1:"some", 2:"help"} print D[1] some Then you can do D[3] = "here" D[97] = "way over there" D["banana"] = "yellow" etc. From duncan at NOSPAMrcp.co.uk Tue Dec 2 04:22:49 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 2 Dec 2003 09:22:49 +0000 (UTC) Subject: Equivalence of dictionary keys? References: <3FCC058C.6070205@irl.cri.nz> Message-ID: Blair Hall wrote in news:3FCC058C.6070205 at irl.cri.nz: > I would like to determine whether two dictionaries have the > same set of keys. Can anyone tell me if I HAVE to sort > the key sequences as in this code snippet: > > # d1, d2 already created > k1 = d1.keys() > k1.sort() > k2 = d2.keys() > k2.sort() > > # are the keys the same? > same = (k1 == k2) > > I am guessing that two dictionaries with the same keys > will sort them in the same order but is this true? Here's a simple counter-example using not two but one dictionary. Just manipulating a dictionary can change the order of the keys: >>> d = {'a':1, 'b': 2, 'c': 3} >>> d.keys() ['a', 'c', 'b'] >>> for i in range(100): d[i] = i >>> for i in range(100): del d[i] >>> d.keys() ['c', 'b', 'a'] >>> However, the answer to your original question is NO, you don't have to sort the keys to find out whether the two dictionaries are the same. You could just iterate over one set of keys and check for membership of the other set. def samekeys(d1, d2): if len(d1) != len(d2): return False for k in d1: if not k in d2: return False return True dict1 = {'a':1, 'b': 2, 'c': 3} dict2 = dict1.copy() for i in range(100): dict1[i] = i for i in range(100): del dict1[i] print dict1.keys() print dict2.keys() print samekeys(dict1, dict2) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From mnations at airmail.net Fri Dec 19 01:34:26 2003 From: mnations at airmail.net (Marc) Date: 18 Dec 2003 22:34:26 -0800 Subject: Hiding console with program compiled in PY2EXE Message-ID: <4378fa6f.0312182234.42c4fe73@posting.google.com> Hi all, I know that to hide a console normally you simply change the extension from .py to .pyw. That's simple enough. However I can't seem to accomplish the same thing after freezing the program. I've tried building the setup file with the python script as a .pyw file, but it crashes and doesn't give me a reason. This is of course because the debug window doesn't open, so you don't know what happened (ahh, the irony). Does anyone know how to successfully freeze a program with py2exe? Many thanks, Marc From engsolnom at ipns.com Mon Dec 29 14:03:46 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Mon, 29 Dec 2003 11:03:46 -0800 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: On Mon, 29 Dec 2003 07:10:15 GMT, "Paul McGuire" wrote: > wrote in message >news:6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com... >> Hi, >> I've been using constructs(?) like the below. >> >> def display(instance, start = None, end = None): >> >> if instance.__class__.__name__ == 'UPCA': >> do some UPCA stuff >> if instance.__class__.__name__ == 'UPCE': >> do some UPCE stuff >> >> launched by: >> >> lx = UPCA(sx), where sx is a string >> then: >> display(lx) >> >Why don't you just define a display() method on the UPCA and UPCE classes, >and instead of display(lx), call lx.display(). If UPCA and UPCE inherit >from a common base class (presumably with an abstract or default display() >method, but not necessarily), this is called "polymorphism". > >Something like this: > >class StringDisplayer(object): > def __init__(instance, instring ): > instance.dispString = instring > >class UPCA(StringDisplayer): > def display(instance, start = None, end = None): > # UPCA-specific display stuff goes here > >class UPCE(StringDisplayer): > def display(instance, start = None, end = None): > # UPCE-specific display stuff goes here > >sx = "abc" >lx = UPCA(sx) >lx.display() > >Your example also uses "instance" for the pointer to self, which works okay, >but is non-traditional; the conventional name for the self pointer is >"self". > >In general, any time you are if-testing on the class of an object, you are >probably doing something polymorphic. If there is common behavior also, put >this in the base StringDisplayer class, and invoke it using >"super(UPCA,instance).display()" in the display() method of the UPCA class, >and likewise in the UPCE class. > Thanks to all for the good responses to my original post. A couple of comments.... After thinking about it, (right after hitting enter, of course), I concluded I can not 'discover' the name of the instance, for the same reason that if x = 10, I can't ask '10' what the name of its reference is. It simply doesn't know, and, as one responder pointed out, doesn't care . All your replies confirmed this. As to the (good) suggestions I use : lx = UPCA() lx.display() I considered this approach. The reason I rejected it is that the actual program has a total of 13 UPCA-like classes (different names, of course). In use, each class may have one or many instances at a time, as determined by the user script. My idea was to include the calling instance 'name' in the display ...not strictly needed, but a nice touch. I could use: display(lx, 'lx') I'm thinking about this...it'd be a user option to include the 'lx'. Why the display in the first place? The user *may* desire to display the class output, probably most often while trouble-shooting a user script problem. Some of the classes have a common (or near common) display routine, others are totally different. If I use lx.display(), the display code has to be contained as a method in each class. I chose, for ease of maintenance, to make a display module with all the display routines gathered together in one spot. . In the event a future programmer decided to make a change to the display routine for a given class, or needed to add a class/display, I feel there's less chance of his/her messing up the UPCA-like classes. I guess I'm a believer in classes/methods doing a limited number of things, and doing them well. Is that a C hang-over? A thought: Another idea might be to make a display base class, and inherit the proper display method in each UPCA-like class. But that still leaves the problem of passing the instance name to the display method. As to the 'ishexdigit' question, thanks for suggested approaches...lots of meat there for this newbie to bread-board and try out. Norm From hokiegal99 at hotmail.com Mon Dec 22 12:27:59 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 22 Dec 2003 12:27:59 -0500 Subject: Count Files in a Directory In-Reply-To: <93f5c5e9.0312211545.363b91a6@posting.google.com> References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: def fs_object_count(setpath): file_count = 0 dir_count = 0 for root, dirs, files in os.walk(setpath): file_count += len(files) dir_count += len(dirs) return file_count, dir_count I'm using this. Thanks to all for the tips and corrections! It works very well on small sets of data (<= 5GB) it is very accurate on this data. On largeer (> 20GB) filesystems, the count will be off by 30 to 40 objects. For example on one 22GB filesystem the OS thinks there are 100,222 objects in the path, Python thinks there are 100,260... Any ideas on this difference? Thanks!!! From bignose-hates-spam at and-benfinney-does-too.id.au Wed Dec 17 18:36:41 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 18 Dec 2003 10:26:41 +1050 Subject: Save the pythons. References: Message-ID: On 17 Dec 2003 13:45:39 -0800, f29 wrote: > I don't believe that noone has yet spotted that python is becoming > java. This is, on the face of it, a falsity: Java is Java, Python is Python. If you mean that Python is gaining traits of other languages, then that's a normal and natural process in the evolution of a language (whether computer-bound or human-bound). It only becomes a point worth discussing if the traits being gained are undesirable; and *that* is a matter for subjective discussion. > Each new version is fully equipped with more garbage than before. > Classes are great, but once there are 1000 of them, inheriting from > each other, I cannot avoid comparing this unpleasant situation to > java. None of the packages in the standard library occupy more than disk space until they are imported. If you want a cut-down standard library, you have the source available to build it however you want. These two traits, certainly the latter, make Python better than Java. > Python power is in it's syntax, not addons. Indeed. Very few changes occur to the simple Python syntax in each release; that is, as you say, its power. > Let's not copy perl's experience I don't understand this point; are you saying that Python's syntax is changing undesirably? You've only mentioned increasing volume of classes, not changes to the langauge syntax. I don't see how you can fear that Python will "copy Perl's experience". > and one java is already far too much for earth. I think the undesirable traits of Java are avoided in Python. - Java is not free software. Python is. (Most of the other differences stem from this one, as free software allows people to make changes primarily based on technical merit if they choose.) - Java's standard library and development environment are increasingly tightly controlled by Sun, and nobody else can have input into the development of the language and library. Python's development is community-driven, with a BDFL at the helm. - Java's large class library is typically distributed as binary blobs that are difficult to divide. Python's standard library is all separate packages, most of it implemented as Python source code. Removing a package is as simple as deleting the files, or (more neatly) rebuilding the library from source without the package. - Java's syntax is simpler than C++, but it still strives to be like that behemoth. Python, as you've pointed out, has a clean syntax that doesn't accumulate cruft. As for "each new version is fully equipped with more [packages] than before", I see that as an advantage, especially since anyone can decide to rebuild without any unwanted packages. Also, the cruft gets cleaned out fairly regularly; if a package is better re-done or re-implemented in another, newer package, the old one is deprecated and eventually disappears. -- \ "The best is the enemy of the good." -- Voltaire | `\ | _o__) | Ben Finney From bokr at oz.net Sat Dec 13 14:40:48 2003 From: bokr at oz.net (Bengt Richter) Date: 13 Dec 2003 19:40:48 GMT Subject: ANN: lunatic-python 0.1 References: Message-ID: On Sat, 13 Dec 2003 04:05:39 -0200, Gustavo Niemeyer wrote: >What is it? >----------- > >Lunatic Python is a two-way bridge between Python and Lua, allowing >these languages to intercommunicate. Being two-way means that it >allows Lua inside Python, Python inside Lua, Lua inside Python >inside Lua, Python inside Lua inside Python, and so on. > >Where to get it? >---------------- > >Documentation, examples, and downloads are available at: > >https://moin.conectiva.com.br/LunaticPython Why the https? I expect you have a good explanation, but why not allow the explanation to be seen via plain http, e.g., on an introductory page that might also tell enough about the project so people can decide whether they want to go further? You could just include a link to the above in the plain page, and tell people what to expect if they click it. Regards, Bengt Richter From Mike at DeleteThis.Geary.com Thu Dec 4 04:06:40 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 4 Dec 2003 01:06:40 -0800 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> Message-ID: Todd Gardner wrote: > I would appreciate any ideas how to write to the parallel port > (Mem 0x378) when runnning WinXP or Mandrake 9.2. > > In C and LabVIEW I use the OutP command to write to > directly to a memory address. I don't know about Linux, but in Windows NT/2000/XP you need a kernel mode device driver. This Google search may help: windows xp parallel port i/o driver -Mike From birdiepageANTI at SPAMciudad.FILTERcom.ar Tue Dec 16 09:42:25 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Tue, 16 Dec 2003 11:42:25 -0300 Subject: Newbie : Gif transparency with Pil problem. In-Reply-To: <2c60a528.0312160414.7a3aabbe@posting.google.com> References: <2c60a528.0312160414.7a3aabbe@posting.google.com> Message-ID: Andrew Clover wrote: > I don't think PIL saves GIFs with transparency at all - at least it didn't > last time I played with it, which is one reason I wrote this: > > http://www.doxdesk.com/software/py/gifWriter.html Wow, I really really thank you, I'll check it and besides using it, I'll see what I can learn from it, as it has some nice functions from what I've already read of the code. Gedece From bokr at oz.net Thu Dec 4 15:53:16 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Dec 2003 20:53:16 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On 04 Dec 2003 20:22:52 +0100, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >bokr at oz.net (Bengt Richter) writes: > >> Still, the actual characters used in the _source_ representation will have to >> be whatever the -*- xxx -*- thing says, right? -- including the characters >> in the source representation of a string that might wind up utf-8 internally? > >Yes, and no. Yes, characters in the source code have to follow the >source representation. No, they will not wind up utf-8 >internally. Instead, (byte) string objects have the same byte >representation that they originally had in the source code. Then they must have encoding info attached? > >The source declaration only matters in the following respects: >- the source may be erroneous, if the bytes form illegal encodings > in the declared source encoding. >- a unicode object will be created based upon the source encoding, > by decoding the bytes in the unicode literal. >- the meaning of certain bytes might not be what it would be in > ASCII. In particular, byte 92 does not always denote a > backslash (\), in all encodings. As a result, if byte 92 appears > in a string literal, the end of the string literal might depend > on the encoding. > >> >The byte string type is not going away. It is a useful type, e.g. when >> >reading or writing to or from a byte stream. >> > >> Is this moving towards a single 8-bit str base type with various >> encoding-specifying subtypes? > >I don't think so. If byte strings where tagged with encoding, you >have to answer many difficult questions, like "what is the result >of adding strings with different encodings?", or "what encoding tag Isn't that similar to promotion in 123 + 4.56 ? We already do that to some extent: >>> 'abc' + u'def' u'abcdef' IOW, behind the concrete character representations there are abstract entities (which the unicode charts systematically match up with other abstract entities from the integer domain), so in the abstract we are representing the concatenation of abstract character entities of the same universal type (i.e., belonging to the set of possible characters). The question becomes what encoding is adequate to represent the result without information loss. There could even be analogies to roundoff in e.g. dropping accent marks during some conversion. But there is another question, and that is whether a concrete encoding of characters really just represents characters, or whether the intent is actually to represent a concrete encoding as such (including the info as to which encoding it is). In the latter case one couldn't convert to a universal character type without loss of information. IOW, ISTM for literals one would need a way to say: 1. This is a pure character sequence, use the source representation only to determine what the abstract character entities (ACEs) are, and represent them as necessary to preserve their unified identities. 2. This is a quote-delimited substring of the source text, use the source encoding cookie or other governing assumption to determine what the ACEs are, then as in 1. 3. This is an encoding-restricted string literal (though necessarily represented in the concrete character encoding of the module source, with escapes as necessary). Determine what the ACEs are, using the encoding information to transform as necessary, but store encoding information along with with ACE representation, because the programming intent is to represent encoding information as well as ACE sequence. 3a. Alternatively, store the original _source_ as an ACE sequence with associated _source_ encoding AND encoding called for by the literal. This is tricky to think about, because there are >= three encodings to consider -- the source, what's called for by the literal, and possible internal representations. >has a string returned from a socket read", etc. 8-bit byte encoding by default, I would think, but if you expand on the idea of cooked text input, I guess you could specify an encoding much as you specify 'r' vs 'rb' vs 'rU' etc. BTW, for convenience, will 8-bit byte encoded strings be repr'd as latin-1 + escapes? > >Instead, applications should apply encodings whereever needed, using >Unicode strings for character data, and byte strings for binary data. > Still, they have to express that in the encoding(s) of the program sources, so what will '...' mean? Must it not be normalized to a common internal representation? BTW, does import see encoding cookies and do the right thing when there are differing ones? Regards, Bengt Richter From peter at engcorp.com Thu Dec 4 08:11:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Dec 2003 08:11:21 -0500 Subject: Newbie data structes question References: Message-ID: <3FCF3279.C9C292CB@engcorp.com> Kamus of Kadizhar wrote: > > So, here's my python question: > > What data structures and flow controls are most appropriate? Any neat > flow control in python? Nope. Python is built on a small set of entirely uninteresting control structures, designed to lead you into a state of mind where you think more about the logic of your code than about whether you can whip something off as a one-liner or obfuscate it to show your brilliance in comparison to lesser programmers. ;-) -Peter From Dustin.Tennill at EKU.EDU Mon Dec 15 14:38:12 2003 From: Dustin.Tennill at EKU.EDU (Tennill, Dustin) Date: Mon, 15 Dec 2003 14:38:12 -0500 Subject: build on AIX without Tk Message-ID: Hello all, I am brand new to this list, not sure if this the right place to ask this question. I have two AIX 5.1 64-bit boxes and would like to have Python on both of them but don't need any of the graphical elements (Tk/Tcl/Tkinter). One of the boxes happened to have Tk/Tcl stuff installed on it, so I was able to build Python 2.3.2 without a hitch. The other box does not have Tk/Tcl installed, and I don't particularly need it there. Below is the error message I get when attempting to make: building '_tkinter' extension ./Modules/ld_so_aix cc_r -bI:Modules/python.exp build/temp.aix-5.1-2.3/_tkinter. o build/temp.aix-5.1-2.3/tkappinit.o -L/usr/X11R6/lib -L/usr/local/lib -ltk8.2 - ltcl8.2 -lX11 -o build/lib.aix-5.1-2.3/_tkinter.so ld: 0706-006 Cannot find or open library file: -l tk8.2 ld:open(): A file or directory in the path name does not exist. ld: 0706-006 Cannot find or open library file: -l tcl8.2 ld:open(): A file or directory in the path name does not exist. *** WARNING: renaming "_tkinter" since importing it failed: from module build/li b.aix-5.1-2.3/_tkinter.so No such file or directory error: No such file or directory make: 1254-004 The error code from the last command is 1. Stop. Is there any way to build without including tkinter support? (Or am I just doing something wrong????) Thanks for any help at all . . . Dustin Tennill Systems Admin Eastern Kentucky University dustin.tennill at eku.edu From aahz at pythoncraft.com Tue Dec 30 23:33:10 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2003 23:33:10 -0500 Subject: Tkinter and OS X 10.3? References: <7ba1cb43.0312301205.30156acf@posting.google.com> Message-ID: In article <7ba1cb43.0312301205.30156acf at posting.google.com>, Brian Parkinson wrote: > >I have tried to get Tkinter working on my Mac (OS X 10.3). I installed >MacPython 2.3 and the TclTkAquaBI-8.4.2.0.dmg. > >When I type: > >import Tkinter >r = Tkinter.Tk() > >I get a window all right, but clicking on the window causes the >following error: > >SetFrontProcess failed,-606 I've got OS X 10.3.2, MacPython 2.3, and TclTkAqua-8.4.4.dmg; it's working okay for me. (My threaded Tkinter app works better than the non-threaded version. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From fredrik at pythonware.com Sun Dec 7 11:15:27 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 17:15:27 +0100 Subject: Humpty Dumpty (was Re: Lists and Tuples) References: Message-ID: Aahz wrote: > From my POV, the ambiguity comes from layering on additional > meanings beyond that supported by the C API. what C API? (duck) From aleaxit at yahoo.com Sun Dec 28 03:53:17 2003 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 28 Dec 2003 09:53:17 +0100 Subject: 2.3 list reverse() bug? In-Reply-To: <20031228091057.V12838@bullseye.apana.org.au> References: <20031228091057.V12838@bullseye.apana.org.au> Message-ID: <200312280953.17500.aleaxit@yahoo.com> On Saturday 27 December 2003 11:11 pm, Andrew MacIntyre wrote: > On Fri, 26 Dec 2003, Alex Martelli wrote: > > list(x) is my favourite way to make a shallow copy of list x, but x[:] > > and copy.copy(x) are essentially equivalent. > > Behaviourally yes, performance wise no. [alex at lancelot x]$ timeit.py -c -s 'x=range(999)' 'x[:]' 100000 loops, best of 3: 18.3 usec per loop [alex at lancelot x]$ timeit.py -c -s 'x=range(999)' 'list(x)' 10000 loops, best of 3: 22 usec per loop [alex at lancelot x]$ timeit.py -c -s 'x=range(999)' -s'import copy' 'copy.copy(x)' 10000 loops, best of 3: 22 usec per loop Close enough, for me, that the words "essentially equivalent" appear to be quite justified. How much of your program's time is spent doing shallow copies of lists, that these tiny differences in overhead are, to you, ESSENTIAL to your program's performance? Alex From manish.j at gmx.net Sun Dec 21 08:14:53 2003 From: manish.j at gmx.net (Manish Jethani) Date: Sun, 21 Dec 2003 18:44:53 +0530 Subject: "unknown protocol" error in httplib using HTTPS Message-ID: I'm using Python 2.3.3 to do HTTPS using the httplib module. Here's the code: from httplib import HTTPSConnection con = HTTPSConnection('www-proxy', 80) con.set_debuglevel(1) con.request('GET', 'https://nexus.passport.com:443/rdr/pprdr.asp') res = con.getresponse() print res.status, res.reason print res.read() Here, "www-proxy" is the HTTPS proxy server that I have to go through (I can't connect directly). I'm trying to GET "https://nexus.passport.com:443/rdr/pprdr.asp" via the proxy, but I'm getting a "unknown protocol" error in return: File "test.py", line 9, in ? con.request('GET', 'https://nexus.passport.com:443/rdr/pprdr.asp') File "c:\python23\lib\httplib.py", line 718, in request self._send_request(method, url, body, headers) File "c:\python23\lib\httplib.py", line 739, in _send_request self.endheaders() File "c:\python23\lib\httplib.py", line 712, in endheaders self._send_output() File "c:\python23\lib\httplib.py", line 597, in _send_output self.send(msg) File "c:\python23\lib\httplib.py", line 564, in send self.connect() File "c:\python23\lib\httplib.py", line 985, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) File "c:\python23\lib\socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) socket.sslerror: (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol') What's the problem here? I just want to use SSL over my HTTPS proxy using httplib. Any help. Thanks! Manish -- http://mannu.livejournal.com/ From francisgavila at yahoo.com Sun Dec 7 21:52:23 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 7 Dec 2003 21:52:23 -0500 Subject: Base conversion method or module References: <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc@4ax.com> Message-ID: Jeff Wagner wrote in message ... >On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" wrotf: > >>Jeff Wagner wrote: >> >>> I found the Python cookbook recipe you were referring to. It is as follows: >> >>(what's wrong with just posting an URL?) > >What a great idea ;) ... >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 Hey, I found another one which is the more general "inverse of int/long" function I was pining for (and thus learning for the n-th time that one should check the cookbook first before reinventing the wheel): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/222109 For some reason it's in the "Text" category, and uses the term "radix," which is less common than "base". Hettinger's version (found in the discussion below) is better. Shouldn't something like this get into the builtins, so we can get rid of hex/oct in Python3k? -- Francis Avila From rainerd at eldwood.com Mon Dec 22 16:15:33 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Mon, 22 Dec 2003 21:15:33 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: Jarek Zgoda wrote: > sys.exit() doesn't return to caller -- but it doesn't mean it doesn't > return a value. Actually that's exactly what it means. The code to return None may be included in the sys.exit function object, but it is never executed. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From opengeometry at yahoo.ca Thu Dec 11 20:58:23 2003 From: opengeometry at yahoo.ca (William Park) Date: 12 Dec 2003 01:58:23 GMT Subject: Python code to replace shell scripts References: Message-ID: Daven Nair wrote: > Hi, > > I would like to know if Python supports codes similar to shell scripts: > > count=`ps -ef|grep "pattern"|wc -l` > for count in `echo $count` > do > done > fi > > Can I export a variable say var from os.system("var=`ps -ef|grep pattern|wc > -l`") No. 'os.system()' will fork a subshell, and, as you know, subshell cannot change parent's environment. Furthermore, your shell script is not proper. It should go like for count in `...`; do ... done In any case, although Python does something well, shell does most things better. (It's okey... I've got my helmet on.) -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From jjl at pobox.com Mon Dec 22 10:10:32 2003 From: jjl at pobox.com (John J Lee) Date: Mon, 22 Dec 2003 15:10:32 +0000 (GMT) Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: <20031222032550.GA15674@titan.progiciels-bpi.ca> References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> <20031221235511.GA11803@titan.progiciels-bpi.ca> <20031222032550.GA15674@titan.progiciels-bpi.ca> Message-ID: On Sun, 21 Dec 2003, [iso-8859-1] Fran?ois Pinard wrote: > [John J Lee] [...] > > If Mark Hammonds Windows editor does it, I don't see why Emacs and vi > > shouldn't. > > I know, for having worked at a Python code reformatter (in Python, of > course!), that proper presentation of Python source may be tricky. > If all involved people were able to agree on the same presentation > principles, it would be nice seeking a common solution for many editors. > Could even become part of the standard library, who knows! :-) I had the impression that Mark's thing (Pythonwin, I think it's called -- or is that the MFC wrapper? I can never remember.) used the standard library, or hooked in at the C level, so that syntax colouring is always correct -- unlike Emacs (and unlike vi, I guess). John From mwilson at the-wire.com Sat Dec 13 12:28:36 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 13 Dec 2003 12:28:36 -0500 Subject: Implicit Conversions References: Message-ID: In article , "=?iso-8859-1?B?UmVuZek=?=" wrote: >I wanted to know the order of implicit conversions and which sort of = >values >allow them. From searching around in books and the archive of this = >mailing >list, it seems to be that only numbers are implicitly converted within = >each >other and bools can be implicitly converted to ints? However, I'm unable = >to >find any other implicit conversions and the order of the implicit >conversions (something like int->float->long). Any help would be greatly >apprectiated. Also, I'm not on the mailing list so can everyone please = >cc me >in the replies? Anybody? Speaking as a Python programmer (not a Python developer), I would say that Python doesn't generally do implicit conversions. The programmer keeps track of the types of the operands passed to operators and functions, and the operators and functions do what they can with what they get. You have it right that the arithemetic operators work so as not to lose "comprehensivity": an operation on a complex yields a complex OR an operation on a float yields a float, OR an operation on a long yields a long OR the operation yields an int. (Those are Python short-circuiting OR's there.) Regards. Mel. From pinard at iro.umontreal.ca Mon Dec 1 11:10:17 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 1 Dec 2003 11:10:17 -0500 Subject: Python for web ? In-Reply-To: References: Message-ID: <20031201161017.GA5293@titan.progiciels-bpi.ca> [Jay O'Connor] > black wrote: > >1. Could Python be used in web programming ? (i guess yes ?) Yes, a lot! :-) > >2. If the answer of above is yes, then can we programms with Python in > >both server and client side or either ? I guess yes to both. For my own usages, I use Python servers where Python code is easily put within HTML pages. If I really wanted to have Python executed on the client side browsers, I would likely follow the Jython path, as Jython is Python over Java, and some Web browsers are already able to run Java. (I did not really try Jython yet, however.) > If by 'client side' you mean 'Python embedded in the HTML page' like > PHP, I think it's possible but I tend to avoid it. First off, for any > such HTML embedded scripting you have to have a server that while parse > and execute the script. If you design carefully, the overhead could be quite negligible, besides the cycles burned by the very execution of scripts. I would not really see this as an impediment, in practice. > More importantly, though, I'm not a big fan of the architecture of > having HTML code interspersed with script coding. I think you'd end > up with a better software design with a normal CGI-template approach Indeed. Templates allow a much nicer separation of the work between the Web designers and artists on one side, and programmers on the other side. Some templating systems are heavier than others (for both humans and machines), one has to be careful when choosing or designing them. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From eugine_kosenko at ukr.net Tue Dec 2 17:33:28 2003 From: eugine_kosenko at ukr.net (=?utf-8?b?0JXQstCz0LXQvdC40Lkg0JrQvtGB0LXQvdC60L4=?=) Date: Wed, 3 Dec 2003 00:33:28 +0200 Subject: Unicode output to file In-Reply-To: References: Message-ID: <200312030032.30385.eugine_kosenko@ukr.net> ? ????????? ?? 1 ??????? 2003 08:53 Martin v. L?wis ???????(a): > =?windows-1251?b?xeLj5e3o6SDK7vHl7eru?= writes: > > I use here Russian letters, and need special encoding for them. The > > property 'encoding' is read-only, and is None by default. How to > > cast the encoding for a file? > > You should use codecs.open instead of the builtin open function; this > allows you to pass an encoding for the file stream. Big thanks! This just helped me! From jzgoda at gazeta.usun.pl Sun Dec 28 03:00:33 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 28 Dec 2003 08:00:33 +0000 (UTC) Subject: How to determine if an instance of your program is already running? References: <4f0a9fdb.0312272353.6f85eaf3@posting.google.com> Message-ID: Miki Tebeka pisze: > You can have your program create a known directory (which IIRC an > atomic operation). When a new instance tries to create it, there will > be an exception. > > Make sure that when you application is closing to remove this > directory. Traditional way is to create pidfile somewhere -- in user's home directory, /var/run... -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From jjl at pobox.com Tue Dec 9 13:04:56 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Dec 2003 18:04:56 +0000 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: <87n0a1uat3.fsf@pobox.com> martin at v.loewis.de (Martin v. L?wis) writes: > allenabethea at aol.com (Allenabethea) writes: > > > Why is python incompatible with .net? Why can't python be coded in > > C#? > > Who says that it cannot be coded in C#. It is a matter of fact that it > currently isn't, but it would be possible to reimplement the Python > interpreter in C# (instead of implementing it in C). > > As for generating MSIL byte codes: This is also possible, and has been > demonstrated. It also has been demonstrated that an initial > implementation is likely to be *very* slow. http://www.python.org/~jeremy/weblog/ """Jim Hugunin is at it again""": http://primates.ximian.com/~miguel/ironpython """I've been working off and on for the past couple of months on a new implementation of Python for the CLR called IronPython. It compiles Python programs into verifiable IL and then dynamically executes them.""" Interestingly, many of the (micro-) benchmarks show that IronPython is *faster* than Python 2.3. > The question is whether a Python implementation for .NET would be CLS > compliant (CLS == Common Language Specification). The existing > implementation has shown that this is not possible without giving up > parts of the Python semantics. [...] Still true, I guess. John From jacek.generowicz at cern.ch Tue Dec 9 16:55:30 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 22:55:30 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Jacek Generowicz wrote: > > > aahz at pythoncraft.com (Aahz) writes: > > > >> I think you're going to need to write a solution that doesn't call > >> functions (function unrolling, so to speak). Instead of returning a > >> memoizer function, just use a dict of dicts. > > > > Sounds interesting. But how do I get the dictionary to use the > > function which it is memoizing, to calculate values which haven't been > > cached yet? > > Guessing into the blue: > > try: > result = cache[fun, args] > except KeyError: > result = cache[fun, args] = fun(args) Allow me to remind you of the memoizer I posted at the top of the thread: def memoize(callable): cache = {} def proxy(*args): try: return cache[args] except KeyError: return cache.setdefault(args, callable(*args)) return proxy One key feature of this is that I can use it to replace any[*] function with a functionally equivalent but faster one, without having to change any of the call sites of the original. IIUC, Aahz suggested to replace the proxy function with a dictionary. This sounds reasonable, as, after all, the proxy maps its arguments to its return values, while a dictionary maps keys to values. The whole point of this is that function call overhead is large compared to dictionary lookup, which is (almost) all that the proxy does. However, it's the "almost" that creates the problem. If I'm prepared to mess around with the calls to the original functions and replace them with your suggestion, then, of course the problem is solved ... however, I _really_ do not want to replace the calls to the original ... > Maybe it's time to show some inner loop lookalike to the wider > public for more to the point suggestions... Sure. def foo(some_type): ... return something foo = memoize(foo) data = [int, float, my_class, his_class, str, other_class] * 10**6 map(foo, data) [+] [*] ... with hashable arguments, etc. etc. [+] Can you see why I don't want to mess with the call site ? From aahz at pythoncraft.com Sun Dec 7 15:03:55 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2003 15:03:55 -0500 Subject: Instance Exception Oddity: Implicit and Explicit not the same? References: Message-ID: In article , RT Lange wrote: >>>> class E1(Exception): pass > >>>> class E2(E1): pass > >>>> i = E2('foo') >>>> raise E1(i) >Traceback (most recent call last): > File "", line 1, in ? > raise E1(i) >E1: foo Why are you passing an exception instance to the constructor for a different exception? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From mrfaro at libero.it Mon Dec 8 12:56:51 2003 From: mrfaro at libero.it (Gabriele Farina) Date: Mon, 08 Dec 2003 17:56:51 GMT Subject: [wxPython] Managing Skin engines Message-ID: Hi guys, can someone ask me how can I manage something like Windows-media-player skins engine using wxPython?? Do I have to build soething like a small gui engine using Canvas or there are other ways?? There is a way to apply font or bg style to all the widgets?? bye From dennis.posadas at intel.com Thu Dec 11 09:46:56 2003 From: dennis.posadas at intel.com (Posadas, Dennis) Date: Thu, 11 Dec 2003 22:46:56 +0800 Subject: thanks ! I can now display chinese characters Message-ID: This works, and should seem pretty obvious to some, alas not to me :( - first insure that the OS has all the fonts loaded in - *.pyc versions of the codecs should be in lib/encodings For my needs, unichr(x) where x is a number from the Unicode map like 0x4e34 works for me. Dennis From daniel.dittmar at sap.com Thu Dec 4 10:02:16 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 4 Dec 2003 16:02:16 +0100 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: Fuzzyman wrote: > Pythons internal 'pointers' system is certainly causing me a few > headaches..... When I want to copy the contents of a variable I find > it impossible to know whether I've copied the contents *or* just > created a new pointer to the original value.... > > For example I wanted to initialize a list of empty lists.... > > a=[ [], [], [], [], [] ] [...] > What is the correct, quick way of doing this (without using a loop and > appending...) ? >>> l = [ [] for i in xrange (3)] >>> l [[], [], []] >>> l [0].append ('a') >>> l [['a'], [], []] Daniel From fredrik at pythonware.com Sat Dec 13 06:51:43 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Dec 2003 12:51:43 +0100 Subject: Evaluating time References: <20031213125616.312773b0.secchi@sssup.it> Message-ID: Angelo Secchi wrote: > What is the best way to check how long a python script takes to be > executed ? for simple cases, use import time t0 = time.time() # walltime ... code ... print time.time() - t0, "seconds" or import time t0 = time.clock() # cpu time (*) ... code ... print time.clock() - t0, "seconds" *) the exact definition of CPU time is platform dependent for detailed benchmarking of small snippets in 2.3 and later, use the timeit module: http://www.python.org/doc/current/lib/module-timeit.html From genjox at yahoo.com Mon Dec 8 19:04:57 2003 From: genjox at yahoo.com (Robert) Date: 8 Dec 2003 16:04:57 -0800 Subject: Python 2.2.3 memory leaks? Message-ID: Hi there, I'm having to use 2.2.3 to port to other platforms. I started porting a few months ago, and only recently had time to finish it. I just noticed there seems to be some memory leaks, and not only in some static function variables they use. There also seems to be one in their memory pool allocator. This may be a shot in the dark, but does anyone know anything about fixing these? If someone does, please point me in the right direction. =] Thanks for any advice! Robert From niemeyer at conectiva.com Mon Dec 15 11:49:56 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Mon, 15 Dec 2003 14:49:56 -0200 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: <20031215164956.GB3615@burma.localdomain> > > I really don't see Python and Lua overlapping in their fields right > > now. Lua is clearly not developed with general system tasks in mind, > > and Python is clearly not developed to be a configuration language, > > I think there was some flame wars on TCL/whatever a while (well, ages) > back, where RMS was insisting that people should not settle for > stripped down languages in favor of "complete" languages. I tend to > agree. Heh.. "people should not".. That's the tipical RMS arrogance. It's easy to say "people should not" when you don't actually need something. I'm a big Python fan, and a contributor as well. Choosing Lua for apt-rpm was not a preference, but a need. APT-RPM is used in installer environments, where Python is not available. The APT-RPM library has about 500kb already. Turning a multi-megabyte interpreter as a requirement is not an option in that case. Today, the Lua interpreter source code is included inside APT-RPM tarball. I've also included in the build all default Lua standard libraries (string handling, etc), a posix module, and a regular expression module, moving the static library size to 130kb (no external dependencies, besides libc). As an interesting note, I've also written a SWIG based Python interface, which is available with the APT-RPM tarball as well. Unfortunately SWIG is not very good at handling C++, so I had to patch it while buildling the APT-RPM support. More recently, I've been in contact with David Beazley, and there's a chance that the next SWIG will support enough C++ to compile the Python bindings. If that doesn't happen, I'll probably move to a handmade interface in the future. I'm trying to avoid that, as this will be a huge work, given the wide API. > Python is a wonderful configuration language, and I don't see > the need to do much "configuring" on systems that can't handle Python. Understood. Something like "You're in trouble anyway.. why should you make your work any easier?". I disagree. > BTW, how big is something like Guile or other minimal Scheme anyway? > Why wouldn't it do? Guile's static library is about 1MB in size. In that case I'd choose Python, not Guile. I don't remember about Scheme, but while looking for some embeddable language I've gone trough that path, and ended up in Lua as the best option. Let me know if you find something better. > > or as small as possible. This may change in the future, but I belive > > (and hope) that instead of Lua becoming a general purpose language, > > the Python core will get smaller, with something like the pypy > > project. > > How small does it need to be for your application? Do you have something with 1kb? :-) -- Gustavo Niemeyer http://niemeyer.net From paulo.pinto at cern.ch Mon Dec 1 09:29:56 2003 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Mon, 01 Dec 2003 15:29:56 +0100 Subject: Turning off warnings Message-ID: Hi, I need to generate a temporary name for a file and pass it as argument to a shell script. Now when I use os.tempnam() or os.tmpnam() I get a runtime warning about security issues. I am well aware of them, but in the context of this application I really don't need to care about it. Is there any way to turn the message off? Thanks, Paulo From tjreedy at udel.edu Tue Dec 16 09:43:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Dec 2003 09:43:16 -0500 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: "J.R." wrote in message news:brmf9g$t59$1 at newshost.mot.com... > I got following conclusion after reading your reply and other documents: > > Actually, the python is passing the identity (i.e. memory address) of each > parameter, and it will bind to a local name within the function. Some months ago, there was a long thread on whether Python function calling is 'call by name', 'call by value', or something else. Without reiterating long discussion, I think from a user's viewpoint, it is best considered 'call by name-binding', with the value-carrying object 'passing' being by cross-namespace binding. One can think of the return process as being similar in that the return object is substituted for the function name as if it had been bound to that name. The usage I believe promoted by Knuth and supported by some here defines 'parameter' as the within-function local name and 'argument' as the outside value/object bound to that name at a particular function call. Yes, CPython does that with ids that are memory addresses, but that is implementation rather than part of the language definition itself. Who know what we do when we act as Python interpreters! Terry J. Reedy From jay at jaydorsey.com Sun Dec 7 09:42:22 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sun, 7 Dec 2003 08:42:22 -0600 Subject: Accessing Python script with ColdFusion In-Reply-To: <6.0.0.22.2.20031207014944.0596e760@mail.stpo.com> References: <6.0.0.22.2.20031206145251.052fc5c8@mail.stpo.com> <20031207030732.GA22553@gentoo.Earthlink.net> <6.0.0.22.2.20031207014944.0596e760@mail.stpo.com> Message-ID: <20031207144221.GA3796@gentoo.Earthlink.net> On Sun, Dec 07, 2003 at 01:55:02AM -0800, Michael Wood wrote: > I've tried using a timeout of 1 and 3. It didn't make any difference. I > also just tried setting the outputFile argument to a file in a folder that > I know is accessible to CF. It created an empty file. So no joy there. > In my experiences CFEXECUTE is buggy (along with most of the other CFtags that do anything worthwhile--CFHTTP, CFMAIL, etc.) You might be better off doing a CFHTTP to a Python CGI script which runs the mailman script (popen() would probably work). Are you certain the script is being executed properly (whatever action you choose is actually being performed)? Have you tried wrapping the CFEXECUTE in CFSAVECONTENT as I mentioned earlier as well? If you're not getting anything written to a text file it probably won't matter because it seems nothing is getting returned by the tag. I would suggest working with a simple python script for debugging. It might be something as simple as redirecting sys.stdout. It seems to me though that if you're getting a message back when you run it from CLI, CF should be getting a message back as well. If I had access to a CF box I'd probably be able to work it out for you, but right now I don't. Jay From rol at post.com Mon Dec 8 13:08:02 2003 From: rol at post.com (Rene Olsthoorn) Date: Mon, 8 Dec 2003 19:08:02 +0100 Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: <3fd4be04$0$204$e4fe514c@news.xs4all.nl> Brad, Thomas, Thanks for your help. Brad, you were right. It is a same name problem. The sys.path trick that Brad uses is good. If that does not work try the following: Go to your Python 2.3 site-packages directory. Locate the file libxml2.py and copy it to libxml2py.py In your code use: import libxml2py as libxml2 Then, the exe generated by py2exe correctly runs. Thomas, LibXML is a very fast XML parser. It has python bindings. http://xmlsoft.org/python.html Greets, Rene Olsthoorn. "Thomas Heller" schreef in bericht news:fzfzt4zm.fsf at python.net... > "Brad Clements" writes: > > > "Rene Olsthoorn" wrote in message > > news:3fcf581e$0$200$e4fe514c at news.xs4all.nl... > >> Dear readers, > >> > >> py2exe has a problem including libxml2. Not at building time, but at > >> runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has > >> the problem? (and can you drop me your setup.py scipt, please). > >> > > > > Perhaps you hit the same problem I did when using libxml2 and libxslt in a > > service created by p2exe. > > > > Here are notes from my project diary (these notes are meant for my client to > > reconcile my bill vs. what I did) > > ----- > > The service builds, I can install it, but get an error when I run it: > > > > The instance's SvcRun() method failed > > File "win32serviceutil.pyo", line 663, in SvcRun > > File "UMXWIN32SVC.pyo", line 41, in SvcDoRun > > File "Rose\WebServer\UMXMServer.pyo", line 53, in ? > > File "Rose\WebServer\umx_handler.pyo", line 16, in ? > > File "Rose\WebServer\HTTPHandler.pyo", line 95, in ? > > File "Rose\WebServer\XMLProcessor.pyo", line 34, in ? > > > > exceptions.ImportError: dynamic module does not define init > > function (initlibxslt) > > > > This says that the service cannot import the libxslt module for some reason. > > > > I built a test script that py2exe runs in console mode, it also fails in the > > same way. > > > > I think libxml is using some kind of dynamic import mechanism, we need to > > work around. > > > > Aha, figured it out. example problem with libxml2. > > > > libxml2.py is a module that imports libxml2mod.pyd which imports libxml2.dll > > > > But, py2exe creates a default path like this: > > > > c:\\temp\\rose, c:\\temp\\rose\\library.zip > > > > This means that python tries to import from the directory first, before > > importing from library.zip. So, python imports libxml2.dll, not libxml2.py > > > > My workaround is to reverse the order of the imports in the startup script: > > > > zipfile = sys.path[-1] > > sys.path.insert(0,zipfile) > > Which version of py2exe are you using, and what is this libxml2? > > IIRC, in the latest version py2exe doesn't put the executable's > directory on the path anymore, but file names like libxml2.py, > libxml2.pyd, and libxml2.dll all at the same time have the potential to > confuse it! > > Thomas From bkelley at wi.mit.edu Thu Dec 11 11:00:34 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 11 Dec 2003 11:00:34 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: <7xad5z1jq5.fsf@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: <3fd89449$0$565$b45e6eb0@senator-bedfellow.mit.edu> Paul Rubin wrote: > >>Here is my humble opinions in a nutshell (missing a lot here): >>wxPython has a grid control to die for and many, many classes, good >>printer support and looks like a native GTK app on Linux and a native >>app on windows and macintosh. > > > Oh wow, yes I guess it's cross platform then. Hmm, what Micro$oft > tool do I need to build and run it? Is Visual C++ enough? I guess > I can get the client to pay for some stuff like that. Also, is there > a Glade-like drag and drop gui editor for it? None. Just download the wxpython binaries and away you go. If you want to build from scratch Visual C++ is enough. wxGlade is a good designer although it does have some warts. wxDesigner is good as well, although not free. http://www.wxpython.org/ wxGlade http://wxglade.sourceforge.net/ wxDesigner http://www.roebling.de/ And join the wxpython mailing list. You'll be glad that you did. Brian From tjreedy at udel.edu Mon Dec 1 16:25:56 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 1 Dec 2003 16:25:56 -0500 Subject: Using and Implementing iterators with classes such as linkedlists References: Message-ID: "Adelein and Jeremy" wrote in message news:mailman.13.1070304403.16879.python-list at python.org... > First of all, I apologize for the double posting - I thought there > was some problem with the Yahoo group so I joined the main mailing > list and repeated instead of waiting as I should have. > > Thanks for the speedy and helpful responses. I now grok the downside > of using internal iterators. Now, for the external iterator, I am > thinking that I would do this: > > class LinkedList: > > ... > > def __iter__(self): > return LinkedListIterator(self.__head) > > > class LinkedListIterator: > > def __init__(self, headNode): > self.__current = headNode > > def __iter__(self): > return self > > def next(self): > if self.__current.next == None: > raise StopIteration > self.__current = self.__current.next > return self.__current.next > > Of course, this LinkedListIterator is for a LinkedList that has a > dummy header node, but the concept is the same in any case. I > understand the concept of generators, but I do not fully comprehend > all of the nuances; for that and a few other reasons, I am avoiding > their use here. My initial answer would have been the same as Duncan's -- __iter__ returning a generator-iterator. I *strongly* recommend that read more about them until you feel comfortable using one. This is one of their designed uses. Less typing and more speed than an instance of a separate iterator class. The latter is more general but the extra generality is useless here. > A few questions though: > > 1) I think it is best to pass only one node to the iterator, as > opposed to the whole list - is that "correct"? Give the iterator-maker (class or genfunc) whatever it needs to start iteration. 'Best' is what it easiest. > 2) The __iter__() method is necessary in LinkedListIterator, am I > correct? All iterators should have __iter__ returning self so user can accept either iterable, self iterating or not, or iterater and call iter(itwhatever) and get iterator without trying to test. > 3) Does this code display suitable Python idiomatic expression? Ignoring preferability of gen-it, overall, yes. >For > example, and in particular, is my use of '==' (as opposed to 'is > not') acceptable and good from this viewpoint? No. Generic comparison 'x==None' is slower than 'x is None', althought not as bad as 'x==True' instead of 'x' after 'if'. The singleton-ness of None is a feature of Python intended to be used as in latter expression. Terry J. Reedy From newsgroups at jhrothjr.com Tue Dec 23 14:05:46 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Dec 2003 14:05:46 -0500 Subject: Flat file database References: Message-ID: "Art Decco" wrote in message news:UQRFb.115936$8y1.365571 at attbi_s52... > Is there any Python module designed to simplify the use of a plain text file > as a flat file database? > > I realize that's a bit vague, but I'm just wondering about the best approach > for creating a little database-backed CGI app using Python on a server with > no real database available. The server belongs to the ISP, and I don't get > to install "real" software, but they do have a cgi-bin directory for me, and > they do have a relatively recent Python, so I've got Python cgi apps working > via "#!/usr/local/bin/python". I can get the apps to write and read plain > text files right in the cgi-bin directory, too, so I can use that as a > simple, flat file database. Python 2.3 has a CSV module to read and write files in Comma Separated Variable format. This might do the job for you if you can stand to read the file and convert it to in-storage objects, and then write out a new version if it's updated. Another possibility along the same lines is the pickle module: that can put out an entire tree of objects, and then read them back in. That's been around for a while. That will be availible for any release of Python that your ISP is likely to have installed. As far as relational support, I'd suggest hitting Google to see what you can turn up. John Roth From peter at engcorp.com Thu Dec 11 08:52:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Dec 2003 08:52:56 -0500 Subject: OT: Peter Hansen needs to use some humility (was Re: Python&Expect) References: <3FD7263E.110F9CC4@engcorp.com><3FD7906E.13832168@engcorp.com> Message-ID: <3FD876B8.74E1ABE1@engcorp.com> Fredrik Lundh wrote: > > Cameron Laird wrote: > > > Long term, the latter might be a greater benefit. I know how > > much it means to me when someone helps me learn how to use > > resources better. > > who has time to learn? wasn't the internet supposed to > eliminate all that? http://www.google.com/search?q=how+to+use+resources+better ;-) From gerrit at nl.linux.org Wed Dec 17 16:19:30 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 17 Dec 2003 22:19:30 +0100 Subject: tuples and cartesian coordinates In-Reply-To: <16352.48717.970544.828159@montanaro.dyndns.org> References: <20031217201815.GA5831@nl.linux.org> <16352.48717.970544.828159@montanaro.dyndns.org> Message-ID: <20031217211930.GA6331@nl.linux.org> Skip Montanaro wrote: > Gerrit> the FAQ says: > > >> For example, a Cartesian coordinate is appropriately represented as a > >> tuple of two or three numbers. > > Gerrit> I find it strange to use tuples for a coordinate.... > > Gerrit> Shouldn't coordinates be mutable? > > See the recent (long) thread on this subject: > http://tinyurl.com/zoyt Hmm, the only message I see on the question whether tuples are useful for *coordinates* is: http://tinyurl.com/35ojd yours, Gerrit. -- 160. If a man bring chattels into the house of his father-in-law, and pay the "purchase price" (for his wife): if then the father of the girl say: "I will not give you my daughter," he shall give him back all that he brought with him. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From francisgavila at yahoo.com Mon Dec 22 20:38:15 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 20:38:15 -0500 Subject: Python re repetative matching References: Message-ID: Rich wrote in message ... >Im new to regex's and cant quite figure out how to get them to work, what >I want is a tuple of all the matches from the regex. Ive simplified my >actual problem and still cant get it to work For the following answers I assume you only feed one line at a time. (If this is an unacceptable restriction, things get uglier.) First, try and think if you need re's. Re's are always last resort. In this particular case, it seems to me that s = "@5489 heel all and thumb toe" s.split(' ', 1) is all you need. If you need more precision (and the digit sequence is always 4 chars long), the basic pattern is as follows: re.split(r'(?<=@\d{4}) (?=.*)', s) >Ive so far got this: >print re.findall( r'(@\d+)|(\w+)', "@5489 heel all and thumb toe" ) You need nongrouping parens, and \w+ will split words. Split to digits and words, discarding nothing: re.findall(r'(?:@\d{4})|(?:.+)', s) Split each item separately, discarding whitespace. re.findall(r'(?:@\d{4})|(?:\w+)', s) >I also tried my orginal idea > >a = re.match( r'(@\d+)\s+(\w+)', "@5489 heel all and thumb toe" ) >print a.groups() re.match( r'(@\d+) (.+)', s ).groups() >This matches the number and the first word, so I thought the following >should rematch after the first word and give me what I wanted... but it >dosent for some reason It doesn't because '\w' means 'words', i.e. [1-9a-zA-Z_]. It doesn't match spaces, so once it comes up against a space, it stops. > >a = re.match( r'(@\d+)\s+(?:(\w+)\s*)', "@5489 heel all and thumb toe" ) >print a.groups() So you do know about nongrouping parens? Anyway, this doesn't match after the first word because it only matches words, not spaces. >This is my next iteration, still gives me the number (first group) and >only the word (the second match). So I extend it to ... > >a = re.match( r'(@\d+)\s+(?:(\w+)\s*)*', "@5489 heel all and thumb toe" ) >print a.groups() > >Now this gives me the number and the last but one word ? WHY! Because * does not magically make new groups. It seems to me it should match the last word, though, instead of next-to-last, but I won't think about it too much because this re is hideous as it is, and shouldn't be used. >My logic suggests that this should do what I want... what am I missing, >Ive spent all night trying to figure this out. Your first error was using regular expressions: 'Some people, when confronted with a problem, think "I know, I'll use regular expressions". Now they have two problems.' --Jamie Zawinski, comp.lang.emacs Use string methods, especially split(). Also, I am no longer sure whether you want all items/words to be groups separately, or if you want one group of numbers, and the rest words. Either one is trivial for string methods: s.split() for each in a group. s.split(' ', 1) for only two groups. However, the first one is impossible for REs (I think) if the number of groups is variable, and ugly if the number of groups is fixed. The second one I've done ad nauseum here. See the RE Howto: http://www.amk.ca/python/howto/regex/ Also, there's an O'Reilly book "Mastering Regular Expressions" which is said to be excellent. Also Mertz wrote a "Text Processing with Python" (or something like that) which is also said to be excellent. Mertz also has a bunch of online columns on Python, all of which are very good. But my guess is that you don't really need any of these. -- Francis Avila From mfranklin1 at gatwick.westerngeco.slb.com Fri Dec 5 08:46:11 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 05 Dec 2003 13:46:11 +0000 Subject: tkFileDialog.askopenfilenames not regonizing -multiple option In-Reply-To: References: Message-ID: <1070631971.21261.1.camel@m-franklin> On Fri, 2003-12-05 at 13:32, Tim Williams wrote: > Hi. > > I'm using Python 2.3 and trying to use tkFileDialog to get a list of > files. I get a message about the '-multiple' option is not a valid > option in the call to Open. > > > Python 2.3 (#1, Aug 4 2003, 10:43:11) > [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from Tkinter import * > >>> import tkFileDialog > >>> root=Tk() > >>> files=tkFileDialog.askopenfilenames() > Traceback (most recent call last): > File "", line 1, in ? > File "tkFileDialog.py", line 133, in askopenfilenames > return Open(**options).show() > File "tkCommonDialog.py", line 52, in show > s = w.tk.call(self.command, *w._options(self.options)) > _tkinter.TclError: bad option "-multiple": must be -defaultextension, > -filetypes, -initialdir, -initialfile, -parent, or -title > > > > ~> tclsh > % info tclversion > 8.3 > You will need to upgrade to tcl/tk 8.4 as the multiple option was not added until then. Regards, Martin. > Thanks for any help. -- Martin Franklin From mfranklin1 at gatwick.westerngeco.slb.com Mon Dec 1 10:36:57 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 01 Dec 2003 15:36:57 +0000 Subject: Turning off warnings In-Reply-To: <20031201152638.GA4181@nl.linux.org> References: <20031201152638.GA4181@nl.linux.org> Message-ID: <1070293016.1829.13.camel@m-franklin> On Mon, 2003-12-01 at 15:26, Gerrit Holl wrote: > Paulo Pinto wrote: > > I need to generate a temporary name for a > > file and pass it as argument to a shell > > script. > > > > Now when I use os.tempnam() or os.tmpnam() > > I get a runtime warning about security issues. > > > > I am well aware of them, but in the context of > > this application I really don't need to care > > about it. > > > > Is there any way to turn the message off? > > You can either do so from the commandline, or use the warning module. > You probably want to use the latter. > The documentation for the warnings module can be found at: > > http://www.python.org/dev/doc/devel/lib/module-warnings.html > > You probably want to do: > > warnings.filterwarnings("ignore") > > Hope this helps! > Or use the *updated for security in 2.3* tempfile module pydoc tempfile or http://www.python.org/doc/current/lib/module-tempfile.html Regards Martin -- Martin Franklin From andrew-pythonlist at puzzling.org Tue Dec 2 07:05:02 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 2 Dec 2003 23:05:02 +1100 Subject: Telnet server implementation In-Reply-To: References: Message-ID: <20031202120501.GB23838@frobozz> On Tue, Dec 02, 2003 at 03:49:23AM -0800, kumar wrote: > Hi all, > > I want to write a telnet server for an embedded linux box using > python.The problem is that it doesn't give a shell ( just a limited > CLI commands for configuring it . )My requirement is to write a telnet > server ( residing on the box) listening on some specific port where it > can listen to telnet requests from clients and provide them an > interactive command line session. I tried using the python's > async_chat module but it is very limited ..any wrappers around this > module so that it can be used more interactively ?? . Any pointers > would be highly appreciated . The current available CLI on this box > allows me to write python scripts remotely , ftp it and run them, so > executing them won't be problem. You should be able to use Twisted's telnet implementation for this. There's an implementation included where the command line session is a pseudo-python interactive interpreter, which is implemented in twisted/manhole/telnet.py, the Shell and ShellFactory classes. You easily can see this in action by running Twisted's mktap and twistd commands: mktap telnet --port 4040 --username foo --password bar twistd -nf telnet.tap You should be able to figure out how to implement your own telnet command interpreter in Twisted by reading that code -- if not, please ask for help on twisted-python at twistedmatrix.com -Andrew. From skip at pobox.com Fri Dec 26 09:46:23 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Dec 2003 08:46:23 -0600 Subject: print arabic characters In-Reply-To: <20031225145455.01ad3747.wtrenker@shaw.ca> References: <3014031e.0312220305.c38ffa3@posting.google.com> <3014031e.0312242351.d2604c2@posting.google.com> <20031225145455.01ad3747.wtrenker@shaw.ca> Message-ID: <16364.18879.211049.535187@montanaro.dyndns.org> Bill> I don't know if this is of any benefit but I was using the latest Bill> Opera web browser on my Linux system and happened to try out the Bill> Arabic introduction page on the unicode.org site. The url is: Bill> http://www.unicode.org/standard/translations/arabic.html Looks gorgeous in Safari. Again, I don't read Arabic, so I can't tell what it's saying, just that it looks nice. (Arabic strikes me as a very pretty language.) Interestingly enough, the highlighting is backwards. If I press and drag the mouse button from the right edge of a line, the background highlighting starts from the left edge. It appears Apple doesn't have all the kinks worked out. Skip From ptmcg at users.sourceforge.net Wed Dec 17 15:53:56 2003 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Wed, 17 Dec 2003 20:53:56 GMT Subject: Parsing an HTML file References: <5e290f27.0312170808.4590723e@posting.google.com> Message-ID: "CodeGuru73" wrote in message news:5e290f27.0312170808.4590723e at posting.google.com... > I am trying to find the best way to parse a bunch of html files. They > are all simillar in structure and I need to get them into a database. > Their relevant structure is: > > >

    title

    >
    authors
    >
    Main html content
    > > I basically need to get the values between

    , >
    and
    > > I am able to read the the files into an array. Check out this simple XML parsing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157358 -- Paul From mwh at python.net Fri Dec 5 07:38:12 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 5 Dec 2003 12:38:12 GMT Subject: segfault in extension module References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: Nat Echols writes: > > Well, I can't see anything flagrantly wrong with that. > > > > Does a debugger provide any hints? > > Someone else suggested this, and this is what the backtrace from gdb > indicated: > > #0 0x420744fe in _int_free () from /lib/tls/libc.so.6 > #1 0x420734d6 in free () from /lib/tls/libc.so.6 > #2 0x0809dc0d in _PyObject_GC_Del () > #3 0x080ce86f in PyDict_Next () > #4 0x080d191d in _PyModule_Clear () ^^^^^^^^^^^^^^^ *That's* very odd. > (It goes on like this for a while. . .) Can we see a little more? Cheers, mwh -- ZAPHOD: Listen three eyes, don't try to outwierd me, I get stranger things than you free with my breakfast cereal. -- The Hitch-Hikers Guide to the Galaxy, Episode 7 From jzgoda at gazeta.usun.pl Wed Dec 10 16:44:44 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 10 Dec 2003 21:44:44 +0000 (UTC) Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> <3fd788bd$0$204$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong pisze: >>>Think about that last just a bit more. Asyncore is SUCH an >>>upgrade over what most of the world is doing. >> >> Can you explain "over what most of the world is doing" a bit more? >> I'm seriuosly interested. > > [Perhaps a bit offtopic?:] > > While you're at it-- is there somewhere a *recent* tutorial on > using asyncore/asynchat? Sam Rushing's one (found via Google) > is from 1999... > (I'm interested in using asyncore directly, not as part > of a framework such as Twisted or Medusa). Frederik Lundh has excellent chapter on network protocols with many examples for asynchronous servers and clients in his "Python Standard Library" book, available online at http://effbot.org/zone/librarybook-index.htm It's the best I have found. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From noemail at noemail4u.com Wed Dec 10 08:09:31 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Wed, 10 Dec 2003 13:09:31 GMT Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: Message-ID: <74cc162865d76ebb99c70f018945a32f@news.teranews.com> On 9 Dec 2003 16:19:35 -0800, seberino at spawar.navy.mil (Christian Seberino) wrote: >I know IPython is another interpreter for Python and was wondering >what people liked about it and if I should switch to it. > >If it is so good then why is it not part of the standard Python >tarball? > >Chris I use it on Win32 and like that it provides a simpler/more direct interface to the file system. I.e., I can do things such as "cd blahblahblah" and change the directory, rather than importing os and calling os.chdir("blahblah"), "ls" instead of os.listdir('.'), and that sort of thing. Also, you can create your own command aliases, along the lines of cshrc, bash, etc. Another feature I've used, at least occasionally, is the ability to save the session history. When I'm exploring a module I've not used before, I do a lot of schtuff that doesn't work, get it to work, then move forward (not work, work, not work, work). By the time I've reached my goal, though, I've become addled and have forgotten which pieces parts works and which didn't. With IPython, I can save that history and review what worked and what didn't, delete the chaff and try the wheat again later. At least one reason it's not part of the standard tarball is that it's owned by a different group of people. --dang p.s. One could argue that my approach to learning new modules could use improvement. And while that may be true, I've found that learning to recognize error messages, and what causes them, makes it easier to help others. From seberino at spawar.navy.mil Tue Dec 9 19:03:16 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 9 Dec 2003 16:03:16 -0800 Subject: Anyone use ELSE minor-mode in Emacs? Message-ID: I am looking at the ELSE home page and trying to figure out if I should invest the time to learn about the ELSE minor mode for Emacs. Is there any programmer out there using ELSE that is getting great benefit from it? What does ELSE minor-mode for Emacs do that is so great for you? Chris From cjw at sympatico.ca Sat Dec 6 17:57:03 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 06 Dec 2003 17:57:03 -0500 Subject: Lists and Tuples In-Reply-To: References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: <_8tAb.17345$yd.2795432@news20.bellglobal.com> Jeff Wagner wrote: > On 04 Dec 2003 21:31:12 -0800, Paul Rubin wrotf: > > >>Jeff Wagner writes: >> >>>I've spent most of the day playing around with lists and tuples to >>>get a really good grasp on what you can do with them. I am still >>>left with a question and that is, when should you choose a list or a >>>tuple? I understand that a tuple is immutable and a list is mutable >>>but there has to be more to it than just that. Everything I tried >>>with a list worked the same with a tuple. So, what's the difference >>>and why choose one over the other? >> >> >> >>Try this with a list: >> >> a = [1, 2, 3, 4, 5] >> a[3] = 27 >> print a >> >>Then try it with a tuple. > > > That's because a tuple is immutable and a list is mutable but what else? I guess I said everything I > tried with a tuple worked with a list ... not mentioning I didn't try to break the immutable/mutable > rule I was aware of. Besides trying to change a tuple, I could cut it, slice and dice it just like I > could a list. They seemed to have the same built-in methods, too. > > From what I can see, there is no reason for me to ever want to use a tuple and I think there is > something I am missing. Why would Guido go to all the effort to include tuples if (as it appears) > lists are just as good but more powerful ... you can change the contents of a list. Should you wish to use a sequence as the key for a dictionary, then a tuple would be the choice. Colin W. > > Jeff From M.Waack at gmx.de Sun Dec 28 14:04:23 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Sun, 28 Dec 2003 20:04:23 +0100 Subject: pointers References: Message-ID: Aahz wrote: > In article , > km wrote: >> >>may i know if there is any plans of introducing the concept of >>pointers into python language as in C ? (atleast in future versions >>?) > > There will never be pointers in Python. Why on Earth would you > want them? Python has pointers. Its just a matter of definition;) Only pointer arithmetic is missing - aehm not available, no one misses it. Mathias From jacek.generowicz at cern.ch Thu Dec 11 04:02:27 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Dec 2003 10:02:27 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: "Francis Avila" writes: > Aahz wrote in message ... [about map] > > and it's usually less readable than some other way of getting > > speed. Actually, I use map in my code because I find it very elegant and very readable[*]. Usually, the speed has nothing to do with it. But if I already have a map, and I'm interested in speed then I'm loathe to replace it with something slower. > I think in the OP's case, any little drop of speed he can get more than > justifies the very, very slightly un-idiomatic use of map instead of a > for-loop. Why do you consider my use of map to be un-idiomatic? I want to transform a sequence into another one, by applying a function to each element of the original. This is exactly the point of map. What am I missing? > Be warned that map() may go away in future Pythons, though.... Yes, I've heard idle rumours to this effect. I think it would be a great shame. Yes, I realize that there are list comprehensions. I appreciate both, and find that sometimes one looks more natural than the other, and sometimes it's the other way around. I find this ability to pick the right-looking idiom worth more than a One Way To Do it principle. [*] There seems to be a faction in the Python community which considers map, reduce, filter and lambda to be evil infiltrators from those perfidious inventions that are functional languages, and therefore the claim is made that they have no place in Python. Some newbies believe this **** and the myth spreads. Just my 2 cents. From tudor.tatar at tin.it Sat Dec 13 09:48:33 2003 From: tudor.tatar at tin.it (tudor) Date: Sat, 13 Dec 2003 14:48:33 GMT Subject: python2.3 upgrade References: <87ekv8vl39.fsf@mobile.foo> Message-ID: <5FFCb.88560$AX1.3685023@news1.tin.it> Lawrence Oluyede wrote: > tudor writes: > >> Traceback (most recent call last): >> File "/usr/sbin/redhat-switch-printer", line 84, in ? >> main() >> File "/usr/sbin/redhat-switch-printer", line 68, in main >> from switchprinter_gui import mainDialog >> File "/usr/share/redhat-switch-printer/switchprinter_gui.py", line 51, >> in ? >> import gtk >> ImportError: No module named gtk > > Have you reinstalled pygtk for the right python version? > I have pygtk-1.99 which I guess is too old.... But I don't think I'm gonna find rpms for my rh8 of the new pygtk, so I'll have to renew the whole gtk2 ! which kinda sounds scarry to me... From peter at engcorp.com Sun Dec 7 21:33:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Dec 2003 21:33:52 -0500 Subject: Questions about datetime module References: Message-ID: <3FD3E310.B78FD3CB@engcorp.com> ??????? ??????? wrote: > > I have several questions about the module datetime. The module has been added > to Python 2.3. It seems that its interface is raw and dirty. Sounds like an opinion that really ought to have some explanation if it's to sound like anything other than whining... > Who is maintainer of the module? Who may answer for my questions and > proposals? Post stuff here for discussion, or consult the appropriate Python Enhancement Proposal (or "meta-proposal", really) listed at the top of http://www.python.org/peps/ to learn how to do this sort of thing in a more formal fashion. You could also probably post something to a list at SourceForge, but I suggest discussion here first, since it seems likely many people will not share your views on the matter. After all, there was ample opportunity for review prior to the final release of Python 2.3... -Peter From fredrik at pythonware.com Sun Dec 7 18:40:46 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 00:40:46 +0100 Subject: Base conversion method or module References: <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc@4ax.com> Message-ID: Jeff Wagner wrote: > I found the Python cookbook recipe you were referring to. It is as follows: (what's wrong with just posting an URL?) > I am getting an error when I import this module and call it. > > #!/usr/bin/python > > import BaseConvert > print BaseConvert.convert(90,BASE10,BASE2) > > Name Error: name 'Base10' is not defined. > > This probably has something to do with namespaces which was biting me > a while ago. I thought that since the 'Base' definitions were global to this > module (BaseConvert.py) by being defined outside the function (convert), > that when I imported this module, they would be global, too. in Python, "global" means "belonging to a module", not "visible in all modules in my entire program" > What am I still missing? change the call to use BaseConvert.BASE10 and BaseConvert.BASE2 to learn more about local and global names, read this: http://www.python.org/doc/current/ref/naming.html From claird at lairds.com Wed Dec 10 17:55:37 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 10 Dec 2003 22:55:37 -0000 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> Message-ID: In article , Jarek Zgoda wrote: >Lawrence Oluyede pisze: > >>> Think about that last just a bit more. Asyncore is SUCH an >>> upgrade over what most of the world is doing. >> >> Can you explain "over what most of the world is doing" a bit more? > >Most of the world still blocks execution with synchronous sockets. Event >driven programming is not a wholly accepted idea. . . . Sooooooo true. Hang out with Perlites or C++ians sometime; you'll hear them talk about how easy it is to do networking now, and then they start saying words like "fork" and "thread". My point is that their accepted concurrency models involve serious burdens in regard to performance and developmental fragility. Mr. Zgoda's right: event-driven networking remains poorly appreciated, and those of us who favor it find it MUCH preferable to the alternatives. -- Cameron Laird Business: http://www.Phaseit.net From martin at v.loewis.de Sat Dec 20 04:52:04 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Dec 2003 10:52:04 +0100 Subject: [Python-Dev] rexec.py unuseable References: <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> <20031216212312.GL17021@lkcl.net> <20031218092922.GF6324@lkcl.net> Message-ID: Luke Kenneth Casson Leighton writes: > so like i said, i believe it to be a relatively simple job to spec > out how to add the means _by which_ ACLs can be usefully evaluated. [...] > is this making sense at all? I now see the problem more clearly: *All* you are trying to explain is "How can I arrange that some sort of policy is applied to function calls". Your ACL system does not do anything else: It just applies some policy, and arranges to restrict callers. This has nothing to do with rexec, though. In your system, by default, restriction applies to all callers. In rexec, there is a clear distinction between restricted callers, and unrestricted code. By default, all code is unrestricted, and code gets restricted by declaring it so (by having a different set of builtins); restriction automatically propagates to all code imported in restricted mode. This is not possible to achieve with ACLs. Regards, Martin From mesteve_b at hotmail.com Mon Dec 15 15:42:36 2003 From: mesteve_b at hotmail.com (SteveB.) Date: 15 Dec 2003 12:42:36 -0800 Subject: Idle won't start References: Message-ID: <18649d35.0312151242.a344493@posting.google.com> No, I had a similar issue with something else, and it was because I interfered with the app by creating a file with the same name. Just a long shot. > > Not that I am aware of, but I do have this file. Is it a problem? From r.s at XXmindspring.com Thu Dec 11 21:57:22 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Fri, 12 Dec 2003 02:57:22 GMT Subject: optimization pointers? References: Message-ID: "Mel Wilson" wrote ... > One simple improvement is to get rid of > > if an_item not in a_list > > which does a linear search over the list. > A dictionary is faster. > > Without a full benchmark, it seems that [...] > will show about a x6 speedup. I really appreciate the suggestions -- both yours and Anton's. After making the changes you indicated, the code runs in about 1/500th the time of the original (i.e. about 2 sec per MB for strings in RAM). The sets idea also speeds things up tremendously, but not as much -- it takes about 70% longer than the dictionary approach. Thanks again. -- r.e.s. From miki.tebeka at zoran.com Tue Dec 23 18:26:43 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 23 Dec 2003 15:26:43 -0800 Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> Message-ID: <4f0a9fdb.0312231526.394a518e@posting.google.com> Hello Michael, > > Can anyone tell me why when builiding Python gcc gets "-g" option as well as "-O3"? > > Apart from bigger objects what does "-g" gives a non-developer of Python? > > It means if you manage to core python, we can hold your hands to find > out with gdb where it's crashed. Why do you ask? Just out of curiosity. Seen it in many apps when building and always wondered. > Disk space is cheap. Yes but memory sometimes isn't. On my cygwin installation the libpython2.3.dll goes from 2.9MB to 1.1MB. On machines with little RAM (embdded ...) this matters a lot. Thanks. Miki From rmunn at pobox.com Tue Dec 16 15:58:54 2003 From: rmunn at pobox.com (Robin Munn) Date: Tue, 16 Dec 2003 20:58:54 GMT Subject: ignore References: Message-ID: Elaine Jackson wrote: > testing There are groups like misc.test for this kind of post; please use them instead of comp.lang.python. Thank you. -- Robin Munn rmunn at pobox.com From garyr at fidalgo.net Thu Dec 4 11:07:48 2003 From: garyr at fidalgo.net (Gary Richardson) Date: Thu, 4 Dec 2003 08:07:48 -0800 Subject: anydbm bug ? Message-ID: According to the Python Library Reference invoking anydbm.open() with flag value 'n' should always create a new empty database. However, the following code produces an error. I stumbled upon this while writing some test code. Opening and closing the file before invoking anydbm.open() was an attempt to delete the results of a previous test. Does this indicate a bug in anydbm? import anydbm filename = r'C:\My Documents\Python\misc\testdb.tmp' f = open(filename, 'w') f.close() file = anydbm.open(filename, 'n') produces: PythonWin 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\My Documents\Python\PicDas_\Script1.py", line 5, in ? file = anydbm.open(filename, 'n') File "C:\PYTHON22\LIB\anydbm.py", line 83, in open raise error, "db type could not be determined" error: db type could not be determined >>> From hokiegal99 at hotmail.com Tue Dec 23 14:05:25 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 14:05:25 -0500 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> <3fe86429$0$186$e4fe514c@news.xs4all.nl> Message-ID: Jp Calderone wrote: > On Tue, Dec 23, 2003 at 11:44:39AM -0500, hokieghal99 wrote: > >>[snip] >> >>That works, but it only returns the first item in the list. The >>functions are returning a list of paths or of files/dirs. For example, >>the function 'clean_dir_names' should return a complete list of >>directory names that it has removed bad characters from. >> >>def clean_dir_names(path): >> for root, dirs, files in os.walk(path, topdown=False): >> for dname in dirs: >> new_dname = re.sub(bad,'-' ,dname) >> if new_dname != dname: >> newpath = os.path.join(root, new_dname) >> oldpath = os.path.join(root, dname) >> os.renames(oldpath, newpath) >> return new_dname >> >>How do I make the report function see all of the contents of the list >>and not just the first item of the list? >> > > > No. "return new_dname" terminates execution of the function. If you want > many results, you need to collect them in a list and return the list, or use > a generator. > > Jp That's odd, it seems silly to terminate something that should be recursive (os.walk) before it's finished being recursive. What's the logic behind that idea? From tjreedy at udel.edu Tue Dec 23 11:33:02 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2003 11:33:02 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" wrote in message news:vugbm8mgin8a35 at news.supernews.com... > > "Francis Avila" wrote in message > news:vufdk79q4g4i8a at corp.supernews.com... > > > > Of course, the typical Ruby accusation against Python is that it (Ruby) is > > "purer OO". I don't know what they mean by "purer". > > I suspect they are objecting to the use of built-in functions, and > the use of functions in modules. Ruby > uses methods for everything, and everything inherits from a base > object that has a huge number of methods. Python is simply not > going to go down that path. Personally, I don't have any opinion > about which is better, both styles work. > > The other possibility is the pervasive use of the visitor pattern > rather than Python's use of for statements for iterations. This, > combined with the ease of creating anonymous functions, does > seem to make a significant difference - at least it's what most > Ruby afficianados talk about when they say what they like about > the language. > > > If they mean the > > fundamental types not being subclassable, that's an old wart that's very > > nearly gone. Otherwise, I don't know what they could possibly mean, > > considering absolutely everything in Python is an objects upon objects > upon > > objects. A class is an object, the methods of an instantiated class are > > objects, the function a method wraps is an objects, the code of the > function > > is an object.... I think about the only thing that is not an object in > > Python is a name, and I can't think how *that* would work. > > Interesting question, especially since it does seem to come up > every few months. > > Technically, since names are simply keys in dictionaries, they > *are* objects. I think the descriptor facility is a start on > addressing that question, though. > > Rather than asking how it would work (the obvious answer > is a different dictionary implementation for use in objects) > it might be better to ask what you would use it for. > > John Roth > > > > -- > > Francis Avila > > > > From usenet_spam at janc.invalid Tue Dec 16 23:06:06 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 17 Dec 2003 04:06:06 GMT Subject: case-sensitivity References: Message-ID: bokr at oz.net (Bengt Richter) schreef: > IIRC the old Pascal (as defined by Jensen/Wirth manual) also ignored > characters beyond 8 in identifiers, though I think it allowed them. And Turbo Pascal had a similar but larger limit IIRC. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From anton at vredegoor.doge.nl Mon Dec 29 17:44:07 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 29 Dec 2003 23:44:07 +0100 Subject: [puzzle] References: <3fef8612$0$117$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <3ff0b01f$0$119$3a628fcd@reader2.nntp.hccnet.nl> "Terry Reedy" wrote: >I don't know what 'Glen Wheeler's problem' is, what your 'antonian' numbers >are, what 'ISTMT' abbreviates, nor precisely what 'sorted reflected' means >to your without an example, so I won't try to solve your puzzle. I will >just comment on the class definition. a) Glen Wheeler's problem: see a recent thread here on c.l.py with subject: "How to use a 5 or 6 bit integer in Python?" b) antonian numbers (base 10 example,last column): 0 <=> 0 1 <=> 1 2 <=> 2 3 <=> 3 4 <=> 4 5 <=> 5 6 <=> 6 7 <=> 7 8 <=> 8 9 <=> 9 10 <=> 00 11 <=> 01 12 <=> 02 13 <=> 03 14 <=> 04 15 <=> 05 16 <=> 06 17 <=> 07 18 <=> 08 19 <=> 09 c) ISTMT: ISTM *that* d) "sorted reflected" an analogy to the binary reflected gray code sequence, in this case a permutation of a set of integers which corresponds to a lexicographic ordering of a list of lists containing the digits of antonian numbers. >> class AntonianSorted: >> >> def __init__(self, n, k): >> self.limits = [k for i in range(n)] >> self.state = [] >> self.iterator = self.__gen__() >> >> def __iter__(self): return self >> def next(self): return self.iterator.next() > >The generation will go faster if you delete the above three line and change >'gen' to 'iter' in the next. Yes, but speed is not important in this stage. Keeping open options is. This way it would be possible to replace the generator with another. Maybe your solution works for that too. Anyway, I just cut and pasted something I saw in a post by Michele Simionato and hacked it into something simpler, perhaps without really understanding what the original purpose of the code was. Welcome to postmodernism. > >> def __gen__(self): >> state, limits = self.state, self.limits >> while 1: >> if len(state) < len(limits): >> state.append(0) >> else: >> i = len(state)-1 >> while i > 0 and state[i] == limits[i]-1: >> state.pop() >> i -= 1 >> if state[i] < limits[i]-1: >> state[i] += 1 >> else: >> raise StopIteration >> yield state[:] > >Making __iter__ itself a generator function (which returns an iterator, as >__iter__ should) is the smoothest way to use generators with classes. >Wrapping genit.next with a regular function undoes perhaps half the speed >benefit of generators. They are fast partly because they do not have to >stash and retrieve local in the instance and partly because they resume >without the normal (slow) function call process. Writing __iter__ as >generator also make the instance reiterable. Yes, I see that now. Thanks for explaining. > >In this case, I do not see any reason to wrap the generator in a class >instead of calling it directly, but perhaps you have a usage in mind where >persisting the instance after the generator run makes sense. The main reason to use a class was that it makes it possible to access self.state from outside the object, for example to prune states with an illegal predecessor. Here's a script I wrote some time ago, it does about the same as Bengts script in the Wheeler thread. It's about trying to count all possible paths a fly can take along the edges of a hyperdimensional cube where all corner points should be visited only once (not necessarily ending in a position adjacent to the starting corner): class Treecount: def __init__(self,limits): self.limits = limits self.state = [] self.iterator = self.__gen__() self.pruned = False def __iter__(self): return self def next(self): return self.iterator.next() def prune(self): self.pruned = True def __gen__(self): state, limits = self.state, self.limits while 1: if len(state) < len(limits) and not self.pruned: state.append(0) else: i = len(state)-1 while i > 0 and state[i] == limits[i]: state.pop() i -= 1 if state[i] < limits[i]: state[i] += 1 else: raise StopIteration self.pruned = False yield state[:] def jumps(n): nc = 2**n res = [] for i in range(nc): neighbours = [] for j in range(n): v = i ^ (1< Message-ID: "Peri" wrote in message news:34ea966a.0312270509.5ecc2095 at posting.google.com... > I'm trying to create Python parser/interpreter using ANTLR. > Reading grammar from language refference I found: > or_expr::= xor_expr | or_expr "|" xor_expr > > For me it looks like infinite recursion. Better to call it unbounded recursion. This is what makes general CF languages/grammars more extensive/powerful that regular languages. In particular, the recursion is written as left recursion. The equivalent right recursion would be or_expr::= xor_expr | xor_expr "|" or_expr The recursive 'call' is to the right of the connector literal instead of the left. There are two types of linear CF parsers: bottom-up LR and top-down LL. Each handles recursion written one way and chokes on recursion written the other way. The two types have opposite requirements. (I forget which is which.) Since Antler choked on left recursion, I presume that it is the 'other' type than Python's and that it requires right rather than left recursion. So try reversing all the recursive definitions. (Or try first the one that gives first error message and see if you get farther.) Terry J. Reedy From eugine_kosenko at ukr.net Sun Dec 7 13:59:06 2003 From: eugine_kosenko at ukr.net (=?windows-1251?b?xeLj5e3o6SDK7vHl7eru?=) Date: Sun, 7 Dec 2003 20:59:06 +0200 Subject: How to fresh or delete a file in azip-archive via zipfile module? Message-ID: <200312072059.06784.eugine_kosenko@ukr.net> Hi! I need to fresh a zip-archive using zipfile. However, it seems it is no function to fresh the archive. When I use the append-mode of ZipFile, the written file is merely appended to the archive while the old copy is still in the archive. As a result, there are several files with the same name in the archive. Is it valid state of the archive? I would to achieve the result using a delete/remove operation, but it is also is not defined in the zipfile module. The method I use now is the recreation the archive each time from scratch. Is it possible to resolve the situation in a more simple way? From dck at NOSPAM.gazeta.pl Mon Dec 1 04:58:22 2003 From: dck at NOSPAM.gazeta.pl (DCK) Date: Mon, 1 Dec 2003 10:58:22 +0100 Subject: How to delete this file ??? Message-ID: Hello I've path to file, which look like this: \\COMPUTER\D$\C++\FILE_TO_DELETE.JPG This path was generated by os.path.walk() function. When i try to delete this file, os.remove() can't find it, os.path.fileexists() can't find it :( I can delete other files (i.e. \\COMPUTER\D$\C\FILE_TO_DELETE.JPG). I guess there's a problem with this C++ directory (++ exacly). I tried to change it to C\+\+, but this still not work. I've no idea how to delete this file. I work under WinNT 4.0 with sp6, python 2.3 with unicode support. I have adminstrator rights. Can somebody help me ? -- /===============--------- / Wygenerowal: DCK / dnia: 2003-12-01 10:49:25 /===========--------- From gagenellina at softlab.com.ar Fri Dec 19 00:33:59 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 19 Dec 2003 02:33:59 -0300 Subject: Default attribute in base class precludes delegation In-Reply-To: <3FE2866A.3090500@zephyrfalcon.org> References: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> Message-ID: <5.2.1.1.0.20031219020923.01fe2040@192.168.0.115> At 19/12/2003 00:02, you wrote: >>class Worker: >> def __init__(self, foo, bar): >> self.foo = foo >> self.bar = bar >> >>class Base: >> bar = None >> >>class Derived(Base): >> def __init__(self, worker): >> self.worker = worker >> def __getattr__(self, name): >> return getattr(self.worker, name) >>w = Worker(1234, 'Hello') >>print 'w.foo', w.foo # prints 1234 >>print 'w.bar', w.bar # prints Hello >>d = Derived(w) >>print 'd.foo',d.foo # prints 1234 >>print 'd.bar',d.bar # prints None, I want to get Hello > >As you already found out, d.bar looks up Base.bar, and __getattr__ isn't >invoked (since it is only called if an attribute is *not* found). > >The easiest solution might be, to change the name of the attribute 'bar' >in Worker, since you can modify this class. If at all possible, make sure >it has no attribute names that are defined in Base also. Is this an >acceptable solution for you? It sounds cheesy, but it might be better >than inventing all kinds of twisted code constructs to get around this problem. That won't work, unfortunately. Other code expects Derived to have a 'bar' attribute (since it inherits from Base). My workaround was to *really* set an instance attribute 'bar' in Derived, and try to ensure that it's always in sync with Worker: def __init__(self, worker): self.worker = worker self.bar = worker.bar def setBar(self, bar): self.worker.bar = bar self.bar = bar This works if a) all people always use setBar on Derived, and b) no one assigns to worker.bar directly. I would like another way, more "automatic", where people dont have to "remember" these rules... (BTW, the real attribute name is 'title', wich is used all around the system, that's why it's a bit difficult to assert the above rules everywhere) Gabriel Genellina Softlab SRL From susi2000 at web.de Wed Dec 10 05:11:02 2003 From: susi2000 at web.de (Susanne) Date: 10 Dec 2003 02:11:02 -0800 Subject: How to Parse a Script before execution References: <188007e5.0312080805.10cf0056@posting.google.com> Message-ID: <188007e5.0312100211.4436b935@posting.google.com> Hello, i was looking for a solution in the groups, and someone did it with: struct _node * myNode = PyParser_SimpleParseFile(...); PyNode_Compile(myNode); PyEval_EvalCode(...); I am using Python 2.3 and there my Visual Compiler says, that there is no PyNode_Compile(). I also looked into different books, and in the html-help of Python 2.3, but found nothing usable. Perhaps anyone of you has an idea, how to solve my problem. Thanks Susanne From lists at webcrunchers.com Wed Dec 17 16:20:32 2003 From: lists at webcrunchers.com (JD) Date: Wed, 17 Dec 2003 13:20:32 -0800 Subject: I see advice on how to debug a python module that hangs up the process In-Reply-To: References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: On Dec 16, 2003, at 9:35 PM, Gustavo Campanelli wrote: > I'm still newbie at Python, but not at programing, so this is just a > wild guess. Have you checked that you are not using a reserved word as > function or parameter name? We are absolutely sure about that. What I think is going on, is there might be some fluke where there might be an Intel instruction that might cross a memory segment. We tried selectively cutting out code in the offending function, to determine exactly what part of the function it hangs up at, and we get different results each time. The problem is not repeatable or predictable, and this is why we need to have some kind of improved control over the Python runtime "engine" or mechanism. I can HACK the function into working, by doing things to change the length of the code, but this isn't going to solve the problem or give me the REAL picture of what's going on in the code. I need a real low level mechanism that would allow me to run python under control of a low level debugger, one that would allow me to break out of the function and determine really where it hangs up. > If the function hangs when it's invoked, are you using some Object as > part of the call? Have you checked that object? I think it's at a much lower level then this. The exact function HAD been working in the past, but other modifications of the code has somehow made it so this function is now hanging up. I think this is a job for kernal-trace, or gdb (low level debugger), and this is what I need to now how to do. John From jjl at pobox.com Sun Dec 14 19:37:12 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Dec 2003 00:37:12 +0000 Subject: minidom and pulldom References: Message-ID: <877k0yhq6f.fsf@pobox.com> pinto at map.com (David Pinto) writes: > I'm trying to use either the minidom or pulldom to find table tags in > html web pages. I've tried parsing two web pages that show up fine in > my browser, but I get errors when I call minidom.parse, or try to get > events with pulldom. Is there a parser that is as forgiving as web > browsers? Didn't this get answered just the other day? minidom and pulldom are built on XML parsers. HTML is not XML. If you want a tree, I recommend using pushing the HTML through mxTidy or uTidylib, and feeding the resultant XHTML to the XML API of your choice. John From tim.golden at viacom-outdoor.co.uk Tue Dec 30 09:30:38 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 30 Dec 2003 06:30:38 -0800 Subject: Monitoring an MS Exchange mailbox References: Message-ID: <8360efcd.0312300630.7c3527d3@posting.google.com> Tim Golden wrote in message news:... > >From: Lindstrom Greg - glinds [mailto:Greg.Lindstrom at acxiom.com] > > [snip request to avoid logon prompt when attaching to MS Exchange] > > > You have three options that I can think of. > [snip examples (1) & (2)] > 3) One other option, with limitations, is to construct a > profile info string on the fly, and pass that to the > logon method: > > > import win32com.client > > EXCHANGE_SERVER = "xyz" > MAILBOX_NAME = "tim.golden" > # > # Obviously replace the server and > # mailbox names to suit. > # > > session = win32com.client.Dispatch ("MAPI.Session") > session.Logon ("%s\n%s" % (EXCHANGE_SERVER, MAILBOX_NAME)) > Oops. That last line should read: session.Logon (ProfileInfo="%s\n%s" % (EXCHANGE_SERVER, MAILBOX_NAME)) Sorry; that's the only one I didn't cut-and-paste into a Python session before posting. Just goes to show... TJG From gashton at cmedltd.com Wed Dec 10 04:24:54 2003 From: gashton at cmedltd.com (Graham Ashton) Date: Wed, 10 Dec 2003 09:24:54 +0000 Subject: About the use of **args References: Message-ID: On Wed, 10 Dec 2003 09:38:55 +0100, Zunbeltz Izaola wrote: > I'm starting a new proyect and i'm in doubt about diferent interfaces > for my clases. My clases will have a lot of attributes and i'm want to > know what aproach could be the best > > 1) Define one SetAttribute/GetAttribute pair of method for each > attribute. > 2) Define one SetAttribute/GetAttribute which argument is a key=value > format. I asked a similar question myself when I started out with Python, and I got some very good answers that served me well. http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=rVCZ6.1492%24h45.9746%40news.uk.colt.net&rnum=2&prev=/groups%3Fq%3Dgraham%2Bashton%2Battribute%2Bpython%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3DrVCZ6.1492%2524h45.9746%2540news.uk.colt.net%26rnum%3D2 My preferred technique is to just set attributes directly on the object, like this: shoe = Shoe() shoe.laced_up = True shoe.is_on_foot = True shoe.resoled = False You may think that it's a bit nasty because it breaks encapsulation, etc., but Python is designed to let you do stuff quickly and cleanly. You're not always in a situation where you need to enforce access so strictly. Using attributes directly is more of a Python idiom (see the last two posts in the thread I posted earlier). Since that earlier thread Python has been given a nice way of customising attribute access; properties. Basically, they let you define get/set methods that get run when you access/assign to an attribute. You benefit by getting a cleaner interface to your class, and you only have to define get/set methods when you actually need them (i.e. when they have side effects other than getting/setting the attribute). For example: class Shoe: def __init__(self): self._laced_up = False self.is_on_foot = False self.resoled = False def _set_laced_up(self, boolean): self._laced_up = boolean if boolean: self.is_on_foot = True def _get_laced_up(self): return self._laced_up laced_up = property(_get_laced_up, _set_laced_up) I've not run that so it may have syntax errors. It should illustrate the principle though; you can use attributes directly until you want to take actions when you set them. Then you can make the attribute "private" and replace it with a property that access the real attribute, and does whatever else you want to do when it's accessed. Hope that makes sense. -- Graham From aleax at aleax.it Sat Dec 27 18:20:48 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Dec 2003 23:20:48 GMT Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: Bjorn Pettersen wrote: ... > ambigous when I stated it. If you look at my response to Alex, you'll see > that I really do mean that copies are virtually never needed [in the > aesthetic, not the Turing complete sense], and if you do use them you're BTW, the reason copy.copy exists is to make _polymorphic_ (shallow) copies: copying without needing to know what object you're copying. E.g., consider: def remove_baddies(container, badp): for x in copy.copy(container): if badp(x): del container[x] do I hear you cringing? OK, this code is _polymorphic_: it works just as well whether container is a list (applies badp on the items) or a dict (applies badp on the keys) or any other container which implements the needed protocols (copyable, iterable, indexable by the items you get when iterating, supports item-deletion). Can you show us how to obtain this level of polymorphism w/o copy? Or, don't you consider polymorphism elegant? Personally, I do! Alex From Andreas.Ames at tenovis.com Tue Dec 2 06:51:51 2003 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Tue, 2 Dec 2003 12:51:51 +0100 Subject: notes on compilation Python with MinGW gcc Message-ID: <788E231C269961418F38D3E360D1652526C9E6@tndefr-ws00021.tenovis.corp.lan> Hi, bokr at oz.net (Bengt Richter) writes: > All I get from the above (after s/3D//g) is "An error occured[sic] > in the logger." sorry, it seems I don't know enough about the magic secrets of sourceforge urls. Just go to the python patch tracker and choose patch with id 841454 ('Cross building python for mingw32'). cheers, andreas From jdhunter at ace.bsd.uchicago.edu Mon Dec 15 10:52:59 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Dec 2003 09:52:59 -0600 Subject: ANN: matplotlib-0.40 python plots with matlab syntax Message-ID: matplotlib is a pure python 2D plotting library with a matlab syntax which produces publication quality figures using in a variety of hardcopy formats (PNG, JPG, TIFF, PS) and interactive GUI environments (WX, GTK) across platforms. matplotlib can be used in python scripts, interactively from the python shell (ala matlab or mathematica), in web application servers generating dynamic charts, or embedded in GTK or WX applications. http://matplotlib.sourceforge.net What's new WX python backend Jeremy O'Donoghue has done an amazing job implementing the backend for wxpython, with all the features such as interactive navigation that are supported in the GTk backend. matplotlib should not be available with a GUI anywhere wxpython, Numeric and python work, including linux and friends, win32, and Mac OS X. See http://matplotlib.sourceforge.net/matplotlib.backends.backend_wx.html for a summary of known issues. Pseudo color plots The pcolor command generates pseudo color plots. See http://matplotlib.sourceforge.net/screenshots.html#pcolor_demo and http://matplotlib.sourceforge.net/screenshots.html#mri_with_eeg for screenshots and example code New time-series plotting functions * psd - plots the power spectral density of a time series * csd - plots the cross spectral density of two time series * cohere - plots the coherence See the examples dir in the src distro: psd_demo.py and csd_demo.py Substantially improved layout The transform architecture was refactored, allowing much more precise layout. Lines, patches, text, etc... can now be placed and scaled in arbitrary units, relative axes units, or physical size. Applicaiton programmers who want to create lines, patches and text directly using the API should read the transform module docs for more info. See the text help for an example of how to specify text locations in axes coords (0,0 is lower left and 1,1 is upper right) Expanded legend capabilities The legend class is improved, with a more sophisticated layout engine and the ability to accept lines and rectangle patches as an optional first argument to specify which lines/patches make up the legend. There are also additional legend placement locations, like 'upper center'. See http://matplotlib.sourceforge.net/screenshots.html#legend_demo Expanded errorbar capabilities Gary Ruben contributed some code to support x and y errorbars, either symmetrix or asymettric, in one enhanced function 'errorbar'. See the errorbar_demo.py for examples of all the wild and wonderful errorbar styles. Bar charts can now also display errorbars; see http://matplotlib.sourceforge.net/screenshots.html#barchart_demo Figure size and DPI controllable from matlab interface The figure command now takes optional args figsize and dpi to set the figure size and DPI in the matlab interface. This change involved some changes in the way default sizes and resolutions were handled among the various backends, with the effect that figures generated by existing scripts may appear different, eg, in the relative size of text to the figure elements. The advantage is that the current implementation does a better job of computing true sizes with increased fidelity between backends. Apologies for any inconveniences! API changes There have been some minor changes to the API for those using matplotlib embedded in GTK applications. * If you instantiate an Axes of Subplot intace, the first arg to __init__ must be the figure that contains it. * If you instantiate any artists, eg, Line2D, Rectangle, or AxisTextGTk, you must initialize them with their dpi, bbox, and transforms. See the help for the transforms modules and the examples logo.py and mri_with_eeg.py, where the objects are explicity created using the new API. * The only change to the matlab interface is in the signature of the errorbar func, which breaks matlab compatibility for the enhanced ability to do x and y errorbars. * See matplotlib.axes.py for a complete list of API changes John Hunter From imbosol at aerojockey.invalid Sat Dec 20 01:56:07 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 06:56:07 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Rainer Deyke wrote: > Carl Banks wrote: >> Well, personally, I don't see much use for non-constant default >> arguments, as we have them now, wheras they would be useful if you >> could get a fresh copy. > > I disagree completely. If a function modifies one of its arguments, this is > a fundamental property of that function. If using a default value for that > argument causes the function to swallow the changes it performs, the > function no longer has consistent behavior. > > On the other hand, the following function has consistent, if silly, > behavior: > > > default_list = [] > > def append_5_to_a_list(which_list = default_list): > which_list.append(5) I said a non-constant default argument wasn't useful. As evidence against, you suggest that the function is "consistent." Now, do have any evidence that non-constant, default arguments (as they are now) are USEFUL? (I don't agree with your "consistent" theory, anyways. The function would be treating all arguments consistently: it's just that it'd get a fresh copy of the default arguments each call.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From tjreedy at udel.edu Sat Dec 13 17:23:31 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Dec 2003 17:23:31 -0500 Subject: install multiple versions of activepython References: Message-ID: "Hoang" wrote in message news:zgGCb.70866$MR4.49398 at newssvr25.news.prodigy.com... > Many modules which used to work with Python 2.2 now don't on 2.3. I am > using some 2.3 features but lots of programs that used to work, don't > anymore. This is especially true with modules that expose their libraries > as DLLs. Has backward compatibility been a nagging problem with Python? 99+% of Python code that works properly with 2.2 (without depending on a bug) should work with 2.3. There were very few (and mostly esoteric) semantic changes. New builtins and modules should be masked by existing items with the same name. Binary extension modules are a different matter, not because C has changed but because binary extensions have to be compiled to match a particular binary (at least for Windows, don't ask me why). *This* is a nagging problem, but not one with Python per se. Terry J. Reedy From newsgroups at jhrothjr.com Sun Dec 28 17:23:13 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Dec 2003 17:23:13 -0500 Subject: argument list References: Message-ID: "Phil Hornby" wrote in message news:mailman.146.1072646016.684.python-list at python.org... > Dear Python List, > > I am working on a solution embedding Python in an app that will looks for > specific string combination within the function names to determine if a > handler for an event exists; I have been able to extract the function names > and find all of the 'fields' of interest. What I am concerned about, > however, is that they could have the wrong argument profile, as specific > handlers will have specific function arguments - can I find out what > arguments a specific functions takes from the C-API? As I don't seem to be > able to find anything...but I could be just being blind... Look at the inspect module. That's the best you can do; exact type information simply isn't availible. The times I've actually needed this I've simply built a metadata dictionary into the affected classes using a fixed name. So far, I've only needed it twice, so I don't have a real good feel for the "best" structure for such a facility. John Roth > > Thanks... > > -- > Phil Hornby > > From hwlgw at hotmail.com Tue Dec 23 11:34:25 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 23 Dec 2003 08:34:25 -0800 Subject: creating EPS with Python Message-ID: > [Jamie] > Now all I need to do is create vector eps files. Can you tell me > where I should start for that? If you don't know yet how to create .eps manually, search Google for "Bluebook EPS". It has some nice examples. But from an earlier remark by you, something like "the eps spec being to detailed" I guess you are looking for a high level way of creating eps. I could not find such a thing to my liking, so at the moment I am working on a Python module for this, the idea is to use Python to create .eps files. What I have now is below, it is a Python module that sends test EPS to stdout when run standalone, if you call it pyps.py (like I do) and then do python pyps.py > test.eps you get an eps file that shows some things it can do. I am not a professional programmer so there are probably bugs etc., if a good Python programmer is reading this then contact me if you'd like to help with the project! ----- pyps.py ----- ''' This file (pyps.py) contains a Python module for generating .eps files (Postscript with a BoundingBox) that display diagrams. Programmer notes: ----------------- The AutoPicture is a container class, you create an instance, add figures to it and then you can call its epsText method that returns the eps code: it calculates an EPS BoundingBox. See the global test methods for example usage. The basic classes to inherit from to create figures are StrokeFill and TranslatedStrokeFill. Override their epsCode method with a method that returns the epscode for the figure you want. CLASSES AutoPicture StrokeFill Box GridBox Line TranslatedStrokeFill Arrow OpenArrow Circle Text Classes in pyps and children of classes in pyps are expected to have a method epsText() that returns Postscript code for a while figure, including code for (translations and) rotations and scaling. Classes should have a methods epsCode() that returns Postscript code for a figure without (translation,) rotation or scale code. The epsCode method is called by the epsText method in classes StrokeFill and TranslatedStrokeFill. Class StrokeFill does NOT do a Postscript translation. Used for Line and Box as parent class. Class TranslatedStrokeFill does do a Postscript translation to (self.x, self.y). Used for Circle and OpenArrow as parent class. ''' import math import string import sys goldenratio = math.sqrt(5)/5.0 # about 0.45 ## # Mostly here for debugging purposes. # Used in test() to show the size of the generated picture. ## def log(msg): sys.stderr.write('\n'+msg+'\n') ### # The Text class does not inherit from StrokeFill because it is # incompatible: sometimes text is printed with a Postscript "show" # command instead of a "fill" or "stroke". ### class Text: def __init__(self, x=20, y=20, gray=0, linewidth=1, linegray=0, angle=0.0, text='Spam spam spam', scalefont=6, font='Times-Roman', xscale=1, yscale=1, charpath=0): self.x = x self.y = y self.gray = gray self.linegray = linegray self.linewidth = linewidth self.angle = angle self.text = text self.scalefont = scalefont self.font = font self.xscale = xscale self.yscale = yscale self.charpath = charpath lw = scalefont * goldenratio # estimate of letterwidth textlength = len(text) * lw x2 = x + lw + math.cos(math.radians( angle)) * textlength * xscale y2 = y + scalefont + math.sin(math.radians( angle)) * textlength * yscale # elw for extra letterwidth (of first letter, because of # rotation) elw = lw * 2 * math.sin(math.radians(angle)) minX, minY = min(x, x2)-elw, min(y, y2)-lw*goldenratio maxX, maxY = max(x, x2), max(y+lw*2, y2) self.minx, self.miny = minX-linewidth, minY-linewidth self.maxx, self.maxy = maxX+linewidth, maxY+linewidth def epsText(self): # content pattern resultStr = ''' gsave ''' resultStr = resultStr + '''\ /%(font)s findfont %(scalefont)s scalefont setfont ''' if self.angle or ( int(self.xscale) != 1 or int(self.yscale) !=1 ): resultStr = resultStr + '''\ %(x)s %(y)s translate ''' if self.angle: resultStr = resultStr + '''\ %(angle)s rotate ''' if self.xscale != 1 or self.yscale !=1: resultStr = resultStr + '''\ %(xscale)s %(yscale)s scale ''' resultStr = resultStr + '''\ newpath 0 0 moveto ''' else: resultStr = resultStr + '''\ newpath %(x)s %(y)s moveto ''' if self.charpath: resultStr = resultStr + '''\ (%(text)s) true charpath ''' else: resultStr = resultStr + '''\ (%(text)s) show ''' if self.gray and self.linewidth: resultStr = resultStr + '''\ gsave %(gray)s setgray fill grestore ''' elif self.gray: resultStr = resultStr + '''%(gray)s setgray fill\n''' if self.linewidth: # This should not be executed when charpath!=0, because # then it will do a Postscript 'show' and it does not # need a stroke anymore. if self.charpath != 0: resultStr = resultStr + '%(linewidth)s' resultStr = resultStr + ' setlinewidth\n' if self.linegray: resultStr = resultStr + '%(linegray)s' resultStr = resultStr + ' setgray\n' resultStr = resultStr + 'stroke\n' resultStr = resultStr + 'grestore\n' return resultStr % self.__dict__ ## # This is an abstract class. # It is expected that epsCode will be overriden. # @param dash Tuple. Last element is offset. The other elements # are used in a Postscript setdash command for defining the pattern. ## class StrokeFill: def __init__(self, x=0, y=0, gray=0, linewidth=1, linegray=0, angle=0.0, xscale=1.0, yscale=1.0, dash=None): self.x = x self.y = y self.gray = gray self.linegray = linegray self.linewidth = linewidth self.angle = angle self.xscale = xscale self.yscale = yscale self.dash = dash # These should be overriden in children of StrokeFill! self.minx, self.miny = 1000000, 1000000 self.maxx, self.maxy = -1000000, -1000000 ## # Override this: return a string of Postscript code. # In that string you make use of attributes in self.__dict__ # like %(x)s def epsCode(self): return '\n' def epsText(self): # content pattern addSaveRestore = ( self.gray or self.angle or int(self.xscale != 1) or int(self.yscale != 1) or self.linegray ) resultStr = '\n' if addSaveRestore: resultStr = ''' gsave ''' if self.angle: resultStr = resultStr + '''\ %(angle)s rotate ''' if self.xscale != 1 or self.yscale !=1: resultStr = resultStr + '''\ %(xscale)s %(yscale)s scale ''' smallCode = self.epsCode() if smallCode: resultStr = resultStr + smallCode if self.gray: resultStr = resultStr + '''\ gsave %(gray)s setgray fill grestore ''' if self.linewidth: resultStr = resultStr + '%(linewidth)s' resultStr = resultStr + ' setlinewidth\n' if self.linegray: resultStr = resultStr + '%(linegray)s' resultStr = resultStr + ' setgray\n' if self.dash: dashParams = '[' i = 0 patternList = self.dash[:-1] for p in patternList: dashParams = dashParams + repr(p) if i < len(patternList)-1: dashParams = dashParams + ' ' i = i + 1 dashParams = dashParams + '] ' dashParams = dashParams + repr(self.dash[-1]) resultStr = resultStr + dashParams + ' setdash\n' resultStr = resultStr + 'stroke\n' if self.dash: resultStr = resultStr + '[] 0 setdash\n' if addSaveRestore: resultStr = resultStr + 'grestore\n' return resultStr % self.__dict__ ## # __init__ constructor parameters: # (x, y) where from # (x2, y2) where to # linegray color for lines # linewidth width of lines ## class Line(StrokeFill): def __init__(self, x=20, y=20, gray=0, linewidth=1, linegray=0, angle=0.0, x2=100, y2=100, dash=None): StrokeFill.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, dash=dash) self.x2, self.y2 = x2, y2 minX, minY = min(x, x2), min(y, y2) maxX, maxY = max(x, x2), max(y, y2) self.minx, self.miny = minX-linewidth, minY-linewidth self.maxx, self.maxy = maxX+linewidth, maxY+linewidth def epsCode(self): # Starting with a newline because there will not be a gsave # around a Line return ''' newpath %(x)s %(y)s moveto %(x2)s %(y2)s lineto ''' class Box(StrokeFill): ## # (x,y) is the lower left corner of the box, w is width, h is # height. # Parameters w and h have to be positive numbers. def __init__(self, x=0, y=0, linewidth=1, linegray=0, gray=0, angle=0.0, w=50, h=None, dash=None): StrokeFill.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, dash=dash) self.x = x self.y = y if not h: h = w * goldenratio self.w = w self.h = h self.x2 = x+w self.y2 = y+h # The -linewidth and +linewidth are sometimes a little too # much when a box is in a corner, but tested effect looks # good. self.minx, self.miny = x-linewidth, y-linewidth self.maxx, self.maxy = self.x2+linewidth, self.y2+linewidth def epsCode(self): return '''\ newpath %(x)s %(y)s moveto %(x2)s %(y)s lineto %(x2)s %(y2)s lineto %(x)s %(y2)s lineto closepath ''' class GridBox(Box): def __init__(self, x=0, y=0, linewidth=1, linegray=0, gray=0, angle=0.0, w=50, h=None, grid=10, glinewidth=1, ggray=0.9, dash=None): StrokeFill.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, dash=dash) if not h: h = w * goldenratio self.w = w self.h = h self.gray = 0 # ! gray is for the self.box ! self.box = Box(x=x, y=x, linewidth=linewidth, linegray=linegray, gray=gray, angle=angle, w=w, h=h) self.grid = grid self.glinewidth= glinewidth self.ggray = ggray self.x2 = x+w self.y2 = y+h self.minx, self.miny = x-linewidth, y-linewidth self.maxx, self.maxy = self.x2+linewidth, self.y2+linewidth def epsCode(self): resultStr = self.box.epsText() # Horizontal lines vpoints = [] for y in range(int(math.floor(self.miny)), int(math.ceil(self.maxy))): if y % self.grid == 0: vpoints.append(y) for y in vpoints: resultStr = resultStr + Line(x=self.minx, y=y, x2=self.maxx, y2=y, linegray=self.ggray, linewidth=self.glinewidth).epsText() # Vertical lines hpoints = [] for x in range(int(math.floor(self.minx)), int(math.ceil(self.maxx))): if x % self.grid == 0: hpoints.append(x) for x in hpoints: resultStr = resultStr + Line(x=x, y=self.miny, x2=x, y2=self.maxy, linegray=self.ggray, linewidth=self.glinewidth).epsText() return resultStr ### # Same as StrokeFill but with a Postscript translate instruction as # the first thing in the representation. ### class TranslatedStrokeFill(StrokeFill): def epsText(self): resultStr = ''' gsave %(x)s %(y)s translate ''' if self.angle: resultStr = resultStr + '''\ %(angle)s rotate ''' if self.xscale != 1 or self.yscale !=1: resultStr = resultStr + '''\ %(xscale)s %(yscale)s scale ''' smallCode = self.epsCode() if smallCode: resultStr = resultStr + smallCode if self.gray: resultStr = resultStr + '''\ gsave %(gray)s setgray fill grestore ''' if self.linewidth: resultStr = resultStr + '%(linewidth)s' resultStr = resultStr + ' setlinewidth\n' if self.linegray: resultStr = resultStr + '%(linegray)s' resultStr = resultStr + ' setgray\n' if self.dash: dashParams = '[' i = 0 patternList = self.dash[:-1] for p in patternList: dashParams = dashParams + repr(p) if i < len(patternList)-1: dashParams = dashParams + ' ' i = i + 1 dashParams = dashParams + '] ' dashParams = dashParams + repr(self.dash[-1]) resultStr = resultStr + dashParams + ' setdash\n' resultStr = resultStr + 'stroke\n' if self.dash: resultStr = resultStr + '[] 0 setdash\n' resultStr = resultStr + 'grestore\n' return resultStr % self.__dict__ ## # __init__ constructor parameters: # (x, y) centre of circle. # r radius. # start angle in degrees from where to start drawing # counterclockwise. # end angle where to stop drawing. # (xscale, yscale) X and Y scaling. Useful for (part of) ellipses. ## class Circle(TranslatedStrokeFill): def __init__(self, x=20, y=20, gray=0, linewidth=1, linegray=0, angle=0.0, r=40, start=0, end=360, xscale=1.0, yscale=1.0, dash=None): TranslatedStrokeFill.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, xscale=xscale, yscale=yscale, dash=dash) self.r = r self.start, self.end = start, end minX, maxX = x - r, x + r minY, maxY = y - r, y + r self.minx, self.miny = minX-linewidth, minY-linewidth self.maxx, self.maxy = maxX+linewidth, maxY+linewidth def epsCode(self): return '''\ newpath 0 0 %(r)s %(start)s %(end)s arc ''' ## # __init__ constructor parameters: # (x, y) where from # (x2, y2) where to # ahw width of the arrow head # ahl length of the arrow head # gray fill color for arrow head ## class Arrow(TranslatedStrokeFill): def __init__(self, x=20, y=20, gray=0, linewidth=1, linegray=0, angle=0.0, x2=100, y2=100, sw=4, ahw=None, ahl=None, dash=None, xscale=1.0, yscale=1.0): TranslatedStrokeFill.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, xscale=xscale, yscale=yscale, dash=dash) if not ahw: ahw = sw / goldenratio if not ahl: ahl = sw / goldenratio dx = (x2 - x) * 1.0 dy = (y2 - y) * 1.0 self.angle = math.degrees(math.atan2(dy, dx)) self.arrowlength = math.hypot(dx, dy) self.base = self.arrowlength - ahl self.halfthickness = sw / 2.0 self.halfheadthickness = ahw / 2.0 self.xvalues = [x, x2, x - self.halfthickness, x2 - self.halfthickness, x + self.halfthickness, x2 + self.halfthickness] self.yvalues = [y, y2, y - self.halfthickness, y2 - self.halfthickness, y + self.halfthickness, y2 + self.halfthickness] self.setminmax() def setminmax(self): self.minx = min(self.xvalues) - self.linewidth self.miny = min(self.yvalues) - self.linewidth self.maxx = max(self.xvalues) + self.linewidth self.maxy = max(self.yvalues) + self.linewidth def epsCode(self): return '''\ newpath 0 0 moveto %(arrowlength)s 0 lineto %(base)s %(halfheadthickness)s neg moveto %(arrowlength)s 0 lineto %(base)s %(halfheadthickness)s lineto ''' ## # __init__ constructor parameters: # (x, y) where from # (x2, y2) where to # sw width of the stem # ahw width of the arrow head # ahl length of the arrow head # gray fill color for whole arrow # linegray color for arrow outline # linewidth width of arrow outline ## class OpenArrow(Arrow): def __init__(self, x=20, y=20, gray=0, linewidth=1, linegray=0, angle=0.0, x2=100, y2=100, sw=4, ahw=None, ahl=None, dash=None, xscale=1.0, yscale=1.0): Arrow.__init__(self, x=x, y=y, gray=gray, linewidth=linewidth, linegray=linegray, angle=angle, x2=x2, y2=y2, sw=sw, ahw=ahw, ahl=ahl, xscale=xscale, yscale=yscale, dash=dash) def epsCode(self): return '''\ newpath 0 %(halfthickness)s neg moveto %(base)s %(halfthickness)s neg lineto %(base)s %(halfheadthickness)s neg lineto %(arrowlength)s 0 lineto %(base)s %(halfheadthickness)s lineto %(base)s %(halfthickness)s lineto 0 %(halfthickness)s lineto closepath ''' ## # A class that can determine the BoundingBox itself, but only if all # its elements have attributes minx, miny, maxx and maxy. ## class AutoPicture: def __init__(self): self._intro = r'''%! %%Creator: pyps.py ''' self._introBoxPat = '''\ %%%%BoundingBox: %(minx)s %(miny)s %(maxx)s %(maxy)s ''' self.elements = [] # silly inital min and max values self.minx, self.miny = 1000000, 1000000 self.maxx, self.maxy = -1000000, -1000000 def add(self, what): self.elements.append(what) def prepend(self, what): self.elements = [what] + self.elements ## # @return Tuple (minx, miny, maxx, maxy) ## def dimensions(self): for e in self.elements: floor, ceil = math.floor, math.ceil if e.minx < self.minx: self.minx = int(min(floor(e.minx), ceil(e.minx))) if e.miny < self.miny: self.miny = int(min(floor(e.miny), ceil(e.miny))) if e.maxx > self.maxx: self.maxx = int(max(floor(e.maxx), ceil(e.maxx))) if e.maxy > self.maxy: self.maxy = int(max(floor(e.maxy), ceil(e.maxy))) return (self.minx, self.miny, self.maxx, self.maxy) def epsText(self): self.minx, self.miny, self.maxx, self.maxy = self.dimensions() cList = [self._intro + self._introBoxPat % self.__dict__] for e in self.elements: cList.append(e.epsText()) return string.join(cList, '') ## # Return a string: the contents of a test .eps file. def test(): p = AutoPicture() # A smal box, filled, default width=50 height=50*goldenratio p.add(Box(x=20, y=40, gray=1)) # Lines p.add(Line(x=30, y=20, x2=50, y2=60)) p.add(Line(x=40, y=20, x2=60, y2=60, linegray=0.2, dash=(3,3,0))) p.add(Line(x=45, y=20, x2=65, y2=60, linegray=0.4)) p.add(Line(x=50, y=20, x2=70, y2=60, linegray=0.6, dash=(9,5,3))) p.add(Line(x=55, y=20, x2=75, y2=60, linegray=0.8)) # An open arrow p.add(OpenArrow(x=20, y=20, x2=40, y2=60, gray=0.4)) # A normal arrow p.add(Arrow(x=10, y=20, x2=30, y2=60)) # Text p.add(Text(x=4, y=5, font='Courier-New', text='Courier-New spam')) p.add(Text(x=100, y=5, font='Arial', text='Arial spam')) p.add(Text(x=65, y=20, angle=math.degrees(math.atan2(2,1)), font='Verdana', text='Verdana spam')) p.add(Text(x=24, y=80, angle=0, scalefont=32, charpath=1, gray=0.7, text="Spam, ham and eggs")) # # Circles p.add(Circle(x=14, y=30, r=6)) p.add(Circle(x=100, y=30, r=6, start=90, end=180, dash=(2,2,0))) p.add(Circle(x=120, y=30, r=6, start=0, end=180, yscale=2.0, linegray=0.5, gray=0.4)) p.add(Circle(x=160, y=30, r=6, start=0, end=180, xscale=1.5, linewidth=0, gray=0.6)) # This one is rotated p.add(Circle(x=140, y=30, r=6, start=0, end=180, xscale=0.5, angle=30.0)) # # Now calculate the dimensions of the picture d = p.dimensions() log('BoundingBox of the generated picture: '+ repr(d)) # PREPEND a background with the max dimensions #p.prepend(Box(x=d[0], y=d[1], w=d[2]-d[0], h=d[3]-d[1], # linewidth=0, gray=0.95)) p.prepend(GridBox(x=d[0], y=d[1], w=d[2]-d[0], h=d[3]-d[1], linewidth=0, gray=0.95, grid=10, glinewidth=0.5, ggray=0.8)) return p.epsText() if __name__ == '__main__': print test() From rmunn at pobox.com Fri Dec 26 18:07:55 2003 From: rmunn at pobox.com (Robin Munn) Date: Fri, 26 Dec 2003 23:07:55 GMT Subject: Identifying File type by reading files References: <93f5c5e9.0312261056.22365aa7@posting.google.com> Message-ID: hokiegal99 wrote: > Are there certain sets of binary data that are unique to files that > would be a better way of identifying them? For example, on the N line > of a MS doc file begining at position X a binary string that is L > digits in lentgh that begins with B and ends with E will *ALWAYS* be > present... some one tell me that I'm not dreaming and that something > like the above example exists??? > > A few of my string searches today: > > doc = string.find(file(os.path.join(root,fname), 'rb').read(), > 'Word.Document.') > xls = string.find(file(os.path.join(root,fname), 'rb').read(), > 'Excel.Sheet.') > pdf = string.find(file(os.path.join(root,fname), 'rb').read(), > 'PDF-1.') > jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') > > Any suggestions or information that better describes how to positively > ID files w/o the possibiliy of mistake would be very helpful to me. As > of now, some of my files, though not many (~ 2%) will be given the > wrong extension, but the logic of the functions is such that they > append any extension that probably applies to the file so at that > point it is a simple process of elimination to determine which > extension is actually the correct one. Normally, I never have more > than 2 unique extensions attached to the same file. Glutton for punishment, aren't you? :-) Seriously, that is a non-trivial problem. If that's what you're trying to do, though, the file format documentation at http://www.wotsit.org/ may be useful to you. Good luck! -- Robin Munn rmunn at pobox.com From vincent at visualtrans.de Tue Dec 2 01:46:34 2003 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 2 Dec 2003 07:46:34 +0100 Subject: python on handhelds devices (IPAQs) References: Message-ID: "Alessio Pace" schrieb im Newsbeitrag news:ZDMyb.658$5o6.317 at tornado.fastwebnet.it... | Hi, python is without any doubt my first choice for common tasks on the | desktop side, but now I have to develop something on an PDA: an HP IPAQ. | | I wonder if python can be also the preferable choice on this kind of | platform, rather than the other J2ME/Jeode/JsomeThingElse non-free stuff | out there. | | I have Familiar Linux installed on the IPAQ, I can flash OPIE or GPE, no | problems. My needs are to use libraries for db connectivity, xml, tcp/ip | and some GUI (so, specific binding to GTK or QT). Google for "pypaq". HTH Vincent Wehren | | Has anyone tried something in this same way and could give me some advices | suggestions/hints/.. ? | | Thanks a lot. | | -- | bye | Alessio Pace From erno-news at erno.iki.fi Wed Dec 24 16:29:26 2003 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 24 Dec 2003 23:29:26 +0200 Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: Michael Hudson writes: > I don't know if the various linkers around are smart enough to > not load debugging information until it's asked for... afaik the dynamic linker (or kernel) never loads the debugging info, that' be the job of the debugger. the debugging info gets put in a separate section in the binary. -- erno From birdiepageANTI at SPAMciudad.FILTERcom.ar Sun Dec 7 13:57:11 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Sun, 07 Dec 2003 15:57:11 -0300 Subject: Newbie question: Any way to improve this code? In-Reply-To: References: Message-ID: Allright, this is just to thank you guys, you helped me dig some methods I hadn't used, and helped me get some better code, now and for the future. That's completely priceless. I love this newsgroup :) From r.s at XXmindspring.com Mon Dec 1 17:14:37 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Mon, 01 Dec 2003 22:14:37 GMT Subject: NumTut corrupted Message-ID: No matter which site I download it from, NumTut.tgz appears to be corrupted. Anyone else having this problem? Thanks. -- r.e.s. From newsgroups at jhrothjr.com Sun Dec 21 17:52:43 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 17:52:43 -0500 Subject: dynamic typing questions References: <8765g9olwz.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:8765g9olwz.fsf at pobox.com... > "John Roth" writes: > > > "Robert Brewer" wrote in message > > news:mailman.378.1071946544.9307.python-list at python.org... > [...] > > When I started in '65, we had one system where we were > > lucky to get one turnaround a week. That wasn't usual, > > most of the systems had one turnaround per day. Planning > > beats flailing around in the debugger any day. > > :-) > > I found it interesting to hear a few years back that Linus Torvalds > didn't like using a kernel debugger. Debugging that kind of low-level > code without a debugger sounds scary to me, but it appears he knows > what he's doing... Not putting the defects into the code in the first place does have a certain amount of attractiveness. Projects like Linux and Python succeed because the core developers are people that know how to write clean code the first time without having to massage it with a sledgehammer to make it behave. John Roth > > > John From doveclaw at users.sourceforge.net Sat Dec 20 20:40:24 2003 From: doveclaw at users.sourceforge.net (Doveclaw) Date: Sat, 20 Dec 2003 20:40:24 -0500 Subject: Is anyone using Python for .NET? In-Reply-To: <02e201c3c758$f7707e20$2c00a8c0@eden> References: <02e201c3c758$f7707e20$2c00a8c0@eden> Message-ID: <1071970823.6102.31.camel@localhost.localdomain> On Sat, 2003-12-20 at 19:25, Mark Hammond wrote: > > Just wondering, because this discussion peaked my > > interest.. but why do > > you disagree.. I understand your opinion that the market right now for > > this product are "average" programmer's who happily except > > being dumbed > > down.. but why (if you do) do you disagree with his statement > > about .NET > > support being advantageous to *nix. > > I wasn't clear. I believe it will be advantageous to *nix, but not > necessarily in terms of directly reusing code originally written "for > Windows". > > It is just that the biggest market now in Windows is for these large > insurance companies writing "business logic" etc, and that I doubt any of > *that* code will end up running on Linux. > > > I don't believe he's saying that. What I think he's saying is that > > Microsoft developed it to basically make there Operating System's that > > much more tasty, and advantageous.. because when developing with .NET > > they will not be hindered with incompatible legacy > > applications. Whether > > this is true or not I do not know, I haven't yet looked into .NET as a > > solution. > > Right - if he was simply stating "MS continue to innovate in order to > continue selling OSs", I agree. Let's not forget programs like Office > though too - .NET could help these products at the *expense* of their OS > division, assuming things ever got good enough to run a .NET forms based app > on *nix. If programs are written to .NET, the OS no longer matters. In > theory of course :) So it's not that you don't believe a program developed w/ .NET in Windows could "technically" run on *nix with proper .NET support but that there wouldn't be a good enough incentive or.. any real want for these insurance companies to begin running their applications on alternative platforms.. so in effect, this option will just be largely unused and go to waste. Drawing from my experience, I can agree with that. One question, since I do not know much about .NET or it's reason to exist.. How does it handle the gui/widgets? Through its own libraries or must you rely on what is made available to you by your chosen programming language? I'm not sure how "open" .NET is intended to be, but assuming that any provided libraries would be windows based.. that would make a *nix clone annoyingly more involved (along w/ often overly-debated decisions, such as which library/widget set(s) to support.) The alternative, through what was already provided by the programming language would seemingly cut severely into attempts to be open and portable since a good many systems for example, may not have wxWindows, tk, or other popular alternatives in Python's case. -- Doveclaw From fredrik at pythonware.com Wed Dec 3 13:35:52 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Dec 2003 19:35:52 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> Message-ID: Enrique wrote: > running a script that works fine in python 22 in python 23 i find something > like: > > unicodedecodeerror: "ascii" codec dan+t decode byte 0xed in position > 37:ordinal not in range (128) > > Usually major versions of python were courteus with the previous versions... 0xED has never been a valid 7-bit ASCII character. you've probably used a modified 2.2 interpreter; most likely, someone has hacked the site.py or sitecustomize.py files to make Python use a non-standard default encoding. you should either fix your program, or figure out how 2.2 was modified, and modify 2.3 in the same way. From news at grauer-online.de Fri Dec 12 05:47:25 2003 From: news at grauer-online.de (Uwe Grauer) Date: Fri, 12 Dec 2003 11:47:25 +0100 Subject: Reading and writing Mozilla-mail in python In-Reply-To: <86ekvcad9o.fsf@stronzo.brainbot.com> References: <86ekvcad9o.fsf@stronzo.brainbot.com> Message-ID: Ralf Schmitt wrote: > Uwe Grauer writes: > > >>Now i tried it under Linux (Suse 8.2) + self compiled python 2.3.2. >>It works!! >>So, what the hell is going on with my stupid win2000? > > > maybe opening the file in binary mode helps (i.e. open(infile, "rb")) ? > > Indeed, you are right. Thanks Uwe From ugly_411 at sympatico.ca Mon Dec 29 08:05:07 2003 From: ugly_411 at sympatico.ca (Wesley Fraser) Date: Mon, 29 Dec 2003 08:05:07 -0500 Subject: Quicktime in python Message-ID: Hey everyone. Does anyone know if there has been a basic, ornot so basic implimentation of quicktime in python? If not, is there a reasonably straight forward way of accessing quicktime from python? Thanks Ugly From piir at earthlink.net Wed Dec 10 01:31:28 2003 From: piir at earthlink.net (Todd Gardner) Date: 9 Dec 2003 22:31:28 -0800 Subject: What is the "self" name always referring to...? Message-ID: <9b849915.0312092231.1a843c02@posting.google.com> Pardon my extremely ignorant newbie questions. Where can I go to find more information about the "self" argument? Is there something special about the word "self" or did Mr. Guido van Rossum just decide to us the word arbitrarily? More precisely it seems that most all classes have "self" as the first parameter. This may be directly obvious but is the word "self" always referring to the class or the function it is used in? Is it a reserved word? Thank you in advance, Todd From claird at lairds.com Thu Dec 11 10:01:11 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 15:01:11 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xekvb1koc.fsf@ruckus.brouhaha.com> Message-ID: In article <7xekvb1koc.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >claird at lairds.com (Cameron Laird) writes: >> Paul, I certainly can understand your dismissal of Tkinter >> as it's commonly employed. Are you aware, though, of > http://tcl.projectforum.com/tk/Home > and > http://mini.net/tcl/10424 >? Tkinter might, in fact, best >> meet your requirements. > >No I'm not. I wrote one tkinter application just to try it out and >while it was nice for putting up a quick and dirty gui, it looked very >crude and the API was also quite inflexible. I clicked the first of >those two url's and it seems to be an in-progress discussion about how >to rework tcl to fix its limitations, but I don't want to rely on >something that's not yet already working. Thanks though. I persist at this out of concern that I'm not making things clear. My stake, incidentally, is that you be successful, not that you use any particular toolkit. The second URL gives working code that you can use immediately in your own applications to improve their appearance. This is not an extension or anything at all difficult or constraining; it's just a little prologue that refines the standard Tkinter appearance. It *is* in use, right now, in several applications that must have professional appearances. The first URL is about committee work, essentially, that will fold the enhancements of the second URL back into the standard Tk distribution. -- Cameron Laird Business: http://www.Phaseit.net From pinard at iro.umontreal.ca Sun Dec 21 22:25:50 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 21 Dec 2003 22:25:50 -0500 Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> <20031221235511.GA11803@titan.progiciels-bpi.ca> Message-ID: <20031222032550.GA15674@titan.progiciels-bpi.ca> [John J Lee] > how do your fingers like vi? Mine have never been completely happy > with the standard emacs keys, but I don't like to change them. Emacs and Vim key-bindings are pretty different, down to the logical organisation and structure of commands. One thing which has been difficult for me is to learn to shift the right hand one position left on the `HJKL' keys and unshift it on `JKL;' depending on what I want to do, this detail often slowed me down initially. I'm not as speedy in Vim that I was in Emacs. More it goes, easier it gets. I expect and accept that it will require a few more months before the spinal chord adapts. :-) I think Vim key-bindings are a bit softer on the hand and fingers than Emacs, because most usual commands use simple lower case letters, others use upper case letters, and only rarely you have to resort to the control key. However, the Escape key is often needed, and a bit remote. This advantage somewhat vanishes when I type French text, as the `cf' keyboard uses a mix of dead keys (some shifted). Other combinations require a full repositioning of the right hand, Python brackets and braces in particular. Another thing I observed is that Vim often invites me into using the mouse (efficiently), while I traditionally dislike it. Strange. > I keep meaning to give the vi keys a chance, but it's almost like > learning to type again... Granted! :-) > I use [Gnus] for news (apart from now, since I got this as email, not > news). Does it do good disconnected IMAP, I wonder? I have about no experiences with IMAP, so I do not know. > - offline and disconnected-mode support is poor to non-existent (bad if > you use a modem) Here at home, `fetchmail' is automatically called each time a modem connection is established, and it takes care of transferring all my email over into the local machine spool. I use POP3 because I prefer the format of the logs it creates, but IMAP is available as well and works. One or the other does not make much difference. Then a Python script analyses the received email and pre-sorts it in many mail-group folders. That script interprets splitting rule trees which I adapted to Python out of my original "fancy splitting" setup in Gnus. It then repeatedly calls Mutt on each mail-group having received new mail, allowing me to read it, reply to it, or do more fine splitting and saving. At saving time, another Python script tremendously help me at quickly selecting the proper folder (among more than 4000) for long term filing, this selection script was also adapted out of a bit complex setup, originally all written in Emacs Lisp. I make little use of `procmail' in all this, besides suppression of some bold, blatant SPAM. Python is much more versatile, legible, and likely speedier as well. I also avoid many locking problems this way. > With Barry Warsaw's email module being used by Mailman (Barry again, > of course), I suppose that takes care of *some* of the mess, but far > from all. Spambayes also uses some forgiving tricks over Barry's `email', which I recycled in my own things. I often use one of my own script to somehow "repair" mis-formatted folders, or transform Babyl folders. I had to touch this script recently, as surprisingly, Mutt does not always properly guarantee proper line termination when it saves a message. Of course, I adjusted the saving procedure when I realised this, but for everywhere I priorly saved email after having adopted Mutt, reparation might be needed. It's quite demanding on message agents to be at the same time competent and forgiving. :-) > > it. In my case at least, the big move is now part of the past, the main > > suffering is behind. > You talk like an ex-drug addict ;-) Editors are addictive. That's why so many people have quasi-religious feeling about them. They feel threatened very deeply whenever they see criticism. Salvaging their editor is akin to salvaging themselves. :-) > python-mode has quirks Vim file type for Python has quirks as well. And the other way around too, I saw nice ideas in Python mode which Vim did not support, and vice-versa. It seems there is a wall between both universes! :-) > If Mark Hammonds Windows editor does it, I don't see why Emacs and vi > shouldn't. I know, for having worked at a Python code reformatter (in Python, of course!), that proper presentation of Python source may be tricky. If all involved people were able to agree on the same presentation principles, it would be nice seeking a common solution for many editors. Could even become part of the standard library, who knows! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From hong.jiang at acm.org Wed Dec 24 03:57:12 2003 From: hong.jiang at acm.org (Hong Jiang) Date: Wed, 24 Dec 2003 03:57:12 -0500 Subject: help, function to get variable type In-Reply-To: References: Message-ID: > What is the function to check the varible type, for example, below is like > in my clipper language: > > x = valtype(m) > > x will be "N", "C", "A", etc... > x=type(m) x will be str, int, tuple, dict ... etc. From mwh at python.net Tue Dec 9 10:43:37 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 9 Dec 2003 15:43:37 GMT Subject: Turning builtin functions into methods. References: Message-ID: Jacek Generowicz writes: > Jacek Generowicz writes: > > > Functions defined in Python have type types.FunctionType, and are > > descriptors whose __get__ method turns them into bound or unbound > > methods. Functions defined in extension modules have type > > types.BuiltinFunctionType, and have no __get__ method. Adding them as > > attributes to classes and calling them through an instance of the > > class does not result in them being called as methods: self is lost. > > > > What's the simplest way of getting around this ? > > By trial and error, I seem to have found that passing None as the > second argument (the instance) to new.instancemethod, does the trick. PyDescr_NewMethod from C maybe? > The library reference manual confirms that it is actually supposed to > work this way. It's a pity that the builtin documentation does not: The patch manager is over there ---> Cheers, mwh -- > With Python you can start a thread, but you can't stop it. Sorry. > You'll have to wait until reaches the end of execution. So, just the same as c.l.py, then? -- Cliff Wells & Steve Holden, comp.lang.python From dw-google.com at botanicus.net Sat Dec 27 08:14:28 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 27 Dec 2003 05:14:28 -0800 Subject: Adding newusers to Unix system from mysql data (Better Approach) References: Message-ID: <99dce321.0312270514.53ebf23d@posting.google.com> "Amy G" wrote... > My problem is this... It writes the data file without problem. But, the > os.system... does not necessarily work to add a new user. By 'not > necessarily' I mean that it works some of the time, but not all of the time. > If I run the program and it does not work, I can simple type 'adduser -f > ' at the command line and it works no problem. Any ideas what > could be causing this. Have you tested adduser seperately? I can't see any problem with your code, suggesting it may be adduser. > for line in c: > userid, password, name = line You can do inline tuple unpack: for userid, password, name in c: > aList.append("%s::20::::%s::sh:%s" %(userid, name, password)) > > f1=open('/home/sean/bin/users.test', 'w') > for line in range(len(aList)): > f1.write(str(aList[line]) + "\n") Just in case you hadn't noticed the shortcut here: for userid, password, name in c: f1.write("%s::20::::%s::sh:%s\n" %(userid, name, password)) > f1.close Ahah! Where are the parenthesis? :) Your file is probably not getting flushed to disk: f1.close() David. From bokr at oz.net Tue Dec 2 00:01:15 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Dec 2003 05:01:15 GMT Subject: Equivalence of dictionary keys? References: Message-ID: On Mon, 1 Dec 2003 22:50:04 -0500, "Tim Peters" wrote: >[Blair Hall] >> I would like to determine whether two dictionaries have the >> same set of keys. Can anyone tell me if I HAVE to sort >> the key sequences as in this code snippet: > >Yes, you do. > >> # d1, d2 already created >> k1 = d1.keys() >> k1.sort() >> k2 = d2.keys() >> k2.sort() >> >> # are the keys the same? >> same = (k1 == k2) >> >> I am guessing that two dictionaries with the same keys >> will sort them in the same order but is this true? > >Not necessarily. The order is an implementation accident, and especially in >the presence of hash collisions *will* differ between two dicts with the >same keys if they were inserted in a different order. > >If you can afford the memory, a slicker trick is to compare two derived >dicts with the same keys and known to have equal values. In 2.3, > > same = dict.fromkeys(d1) == dict.fromkeys(d2) > >is enough. This doesn't sort under the covers, either. Another trick, >which should work with any modern Python version: > > if len(d1) == len(d2): > temp = d1.copy() > temp.update(d2) > same = len(temp) == len(d1) > else: > same = False > It is interesting to note that "same keys" means "same" in the sense of ==, not "same" in the sense some might expect. I.e., >>> class Foo(object): ... def __hash__(self): return 1 ... def __cmp__(self,other): return cmp(1, other) ... >>> foobj = Foo() >>> {1:'one'}[foobj] 'one' >>> {1:'a'}.keys()=={1.0:'b'}.keys()=={1L:'c'}.keys()=={True:'d'}.keys()=={foobj:'e'}.keys() True (Skipped the trivial sorts ;-) Regards, Bengt Richter From francisgavila at yahoo.com Wed Dec 24 04:32:34 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 24 Dec 2003 04:32:34 -0500 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: Moosebumps wrote in message >I've googled all over for this but can't find an answer... > >I'm fairly new to Python, and wondering if you can just list a bunch of >objects as data. For example, in C you would just do something like this: > >struct >{ > int a; > float b; >} mystruct; > >mystruct x = { 3, 5.0f }; >mystruct y = { 5, 15.0f }; > >These are just "data". Obviously in python you could just write an init >function like this: > >x.a = 3; >x.b = 5; > >y.a = 5; >y.b = 15; Obviously? I have no idea what the above snippet is supposed to correspond to in Python. A class is like (using like in a very, very loose sense here) a struct, not like an instance of a struct. I'm really streching the C analogy in every possible way, but that much is at least sorta true. The equivalent Python to your C code is: class mystruct(object): def __init__(self, a, b): self.a = a self.b = b x = mystruct(3, 5.0) y = mystruct(5, 15.0) Is this what you consider inelegant? If it's too over-engineered (!) for you, use a more basic data type, like a dict (as you suggest later). Or you can simply bypass init and assign directly: x = object() x.a = 3 x.b = 5.0 But since you *know* the struct's structure, you might as well use __init__ to formalize it. And you're still executing object's __init__, anyway. >And that would work fine, but the programmer in me says that that's a pretty >inelegant way to do it. Why execute code when all you need is to put data >in the program? The programmer in you is optimizing prematurely and/or trying to turn Python into C. :) The point of classes are to package data and a set of operations proper to that data. C doesn't have classes (although similar concepts can be emulated with structs and function pointers). Python uses them liberally. However, one would rarely have such a bare class that's simply holding two attributes; it would also implement methods that operated on the data it held. If all you want to do are hold two numbers efficiently, use a list/tuple or somesuch, and access them by index instead of name (if the name doesn't matter). Or see below. >A thought that occured to me is that classes are implemented as dictionaries >(correct?). So you could have a dictionary like this: No. Classes are objects. Dictionaries implement attribute access to objects (i.e. namespaces). >x = {'a': 3, 'b': 5} >y = {'a': 5, 'b': 15} > >This would be the __dict__ attribute of an object I suppose. But I don't >see anyway to assign it to a variable so you could access them like x.a and >y.a. I don't know if this would be a "nice" way to do it or not. What you're asking for is a "bunch". It's a common cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) Use it like x = object() above, except you can preinitialize name/value pairs: x = Bunch(a=3, b=5.0) print x.a # 3 x.z = 'new attribute' Be careful not to clobber attribute names (object only has __*__ special names, so you don't need to worry too much). The moral of this story is that your question is too abstract. What your data structure should look like depends on what purpose it has, how it is used, and what requirements it must fulfill. Python can produce *much* richer data structures than C, what with OO and all, so there are many more possibilities than simply a C struct. Further, C is radically different from Python, so it's not healthy to try and make Python conform to your C expectations. For one, C is a compiled language, whereas Python is bytecode interpreted. In C, struct only exists to the compiler and to you--it is an entirely logical construct used to make coding easier; it, variable names, etc, *cease to exist* when they are turned into code. This makes C very tight and efficient. But in Python, even down to the bytecode, name lookups are done, classes and functions are *real things*, etc. This makes Python very powerful and far easier to use, but you give up speed. However, you rarely *need* the speed, and there are always ways of getting alot of it back. >Question 2: > >If "subfolder" is a folder under "basefolder", and basefolder contains >"base.py", and subfolder contains "sub.py", how do I import sub.py into >base.py? From what I can tell so far it only works if the files are in the >same directory. I need to be able to do this without modifying any >environment variables or anything. Because the scripts will be run on many >different machines and I have no way of automatically configuring them. Any directory which contains a file called __init__.py is a package. If you create such a file in subfolder, you can import sub from base.py as subfolder.sub. import subfolder.sub as sub from subfolder import sub will both put sub into the current namespace. See the bottom of the page on the import statement in the Python Language Reference. -- Francis Avila From bokr at oz.net Sun Dec 14 13:50:07 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 18:50:07 GMT Subject: Python Cookbook question re 5.6 References: <3fdcaf2d$1@nntp0.pdx.net> Message-ID: On Mon, 15 Dec 2003 08:51:07 -0800, Scott David Daniels wrote: >Joe wrote: >> The recipe in question is "Implementing Static Methods". It shows how to >> use staticmethod(). This sentence in the Discussion section isn't clear to >> me: "An attribute of a class object that starts out as a Python function >> implicitly mutates into an unbound method." I'm not sure what this means, >> exactly. Can anyone elaborate? >> >> Thanks, >> Chris > >First, you might cite the actual recipe here, so people can go look: > > >The way a class is constructed consists of: > 1) open a scope at the point where the class definition starts. > 2) Collect each definition in the scope (value an name). At this > point (during the collection), you are building "normal" > functions with def. > 3) When the end of the class definition is found, all of the > definitions collected in (2), along with the class name and > superclasses are used to build the actual class. This is the > moment when the normal functions created in step 2 are used > to build "unbound methods" -- the magic used to make objects > work. UIAM that is not quite accurate. The defined "normal functions" you mention remain so until dynamically accessed as attributes of the relevant class. If you bypass the getattr mechanism (e.g., looking in the class dict), you find that the functions are still "normal": >>> class C(object): ... def meth(*args): print 'meth args:', args ... >>> c = C() >>> C.meth >>> c.meth > but this way you see the plain old function: >>> C.__dict__['meth'] if you use getattr, you can see the attribute magic: >>> getattr(C,'meth') and via an instance: >>> getattr(c,'meth') > calling the plain function: >>> C.__dict__['meth'](1,2,3) meth args: (1, 2, 3) trying the same as class attribute, which gets you the unbound method: >>> getattr(C,'meth')(1,2,3) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method meth() must be called with C instance as first argument (got int insta nce instead) you can pass the instance explicitly: >>> getattr(C,'meth')(c,1,2,3) meth args: (<__main__.C object at 0x00902410>, 1, 2, 3) you can make a global binding to the plain function: >>> gm = C.__dict__['meth'] >>> gm(1,2,3) meth args: (1, 2, 3) you can add a method dynamically to the class: >>> C.m2 = lambda *args:args and the getattr magic will do its thing: >>> C.m2 > >>> c.m2 of <__main__.C object at 0x00902410>> >>> c.m2(1,2,3) (<__main__.C object at 0x00902410>, 1, 2, 3) >>> C.m2(1,2,3) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method () must be called with C instance as first argument (got int i nstance instead) >>> C.m2(c,1,2,3) (<__main__.C object at 0x00902410>, 1, 2, 3) You can also define descriptors that will intercept the getattr magic and alter the behavior, if you want to. Regards, Bengt Richter From cjw at sympatico.ca Thu Dec 11 09:25:02 2003 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 11 Dec 2003 09:25:02 -0500 Subject: numarray doesn't work on win2k In-Reply-To: <3fd82588$0$18044$3b214f66@aconews.univie.ac.at> References: <3fd82588$0$18044$3b214f66@aconews.univie.ac.at> Message-ID: <3FD87E3E.3010906@sympatico.ca> Alexander Schwaigkofler wrote: > Hi! > > I have the following problem with numarray. I read the install.txt manual, > but it doesn't already work. > OS: Microsoft Windows 2000 [Version 5.00.2195] > python: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on > win32 > numarray: Version 0.7 > the output from the installation (by hand) you can see below: > > The other possibility to install numarray on a win32 platform is to run the > self-installing executable. If I tried it that way, I can't test the > numarray package. I'm puzzled by this. There is a test module with numarray. In any event, you could compose your own. I've used the self-installing package with an XP, all went smoothly. Version 0.8 is expected to resolve some problems when it is released. One of the things it addresses is that the addons will be included in the main package. Colin W. [snip] From jjl at pobox.com Tue Dec 9 11:45:14 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Dec 2003 16:45:14 +0000 Subject: python com wrappers References: Message-ID: <87k756szxh.fsf@pobox.com> Paul Rudin writes: [...] > seems to solve the problem, although perhaps this breaks something > else? Try posting what you just wrote to the python-win32 list. John From eric.brunel at N0SP4M.com Mon Dec 1 04:24:29 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 01 Dec 2003 10:24:29 +0100 Subject: SGMLParser eats ä etc References: Message-ID: Anders Eriksson wrote: > Hello! > > I'm using smgllib (ActivePython 2.3.2, build 230) and I have some trouble > with letters that has been coded, e.g. the letter ? is coded å ? is > coded ä and ? is coded ö all according to the html standard. > > I use the SGMLParser and when I feed method all the coded letter will be > stripped/eaten. > > Why? > How do I fix this? The &something; "coding" for accented characters is called an entity in SGML. These entities are all defined in the underlying DTD for your document. HTML defines the "standard" entities you describe, like å, ä, etc... But if the DTD for the document you're parsing does not include these entity definitions, there's no reason why the parser should do anything with them, even if silently ignoring them seems strange to me (I'd have expected a parsing error). So there are two solutions: - either your document is HTML, and you should use an HTML parser as it was already suggested - or your document is not HTML, and you should define all entities you may use in your DTD. This is done for example with: (if you use the iso8859-1 encoding) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From eaglehawk777 at aol.com Thu Dec 11 04:11:55 2003 From: eaglehawk777 at aol.com (EAGLEHAWK777) Date: 11 Dec 2003 09:11:55 GMT Subject: HOT OPPORTUNITY Message-ID: <20031211041155.26239.00000681@mb-m06.aol.com> JUST CHECK OUT MY WEBSITE http://www.webspawner.com/users/hawkk/index.html From just at xs4all.nl Wed Dec 10 20:03:04 2003 From: just at xs4all.nl (Just) Date: Thu, 11 Dec 2003 02:03:04 +0100 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> Message-ID: In article , Andrew Bennetts wrote: > On Wed, Dec 10, 2003 at 11:11:40PM +0100, Just wrote: > > > > This ties nicely into the xsdb + stackless discussion: > > > > - threads + blocking sockets is attractive since the code can be > > written in a natural style, yet cause overhead and > > synchronization headaches. > > > > - async sockets are attractive because they avoid threads and > > therefore avoid overhead and synchronization issues. Yet it > > is often a bit harder to code, since you need to turn your > > code inside out, using callbacks. > > > > But there is a "perfect" solution: co-routines. With co-routines you can > > both write the code in a "natural" style, but still using an even-driven > > core. This is a very pleasant model to work with, so I totally > > understand that some people (eg. Aaron) choose to use Stackless to make > > this possible. > > co-routines miss one of the features of the threading model, though, which > is preemptive concurrency. I prefer the async way of working too, but I can > see that co-routines don't provide the best of both worlds... True, that is an important difference. However, I believe that people often pick threads over events not because they need preemptive concurrency, but because threading appears to be "easier" -- which it is, at least if you discount synchronization issues. Co-routines largely fix that particular problem. Just From bokr at oz.net Mon Dec 15 13:14:12 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Dec 2003 18:14:12 GMT Subject: cPickle from 2.2 to 2.1 References: <3fdd9fa4$0$210$e4fe514c@news.xs4all.nl> <7xekv6l00f.fsf@ruckus.brouhaha.com> Message-ID: On 15 Dec 2003 04:48:48 -0800, Paul Rubin wrote: >"remco" writes: >> These drawbacks (backward/forward incompatibilities) occur nearly >> everywhere. I've used the Berkley db module, when it got updated, i had to >> deinstall Python, reinstall an old version, check out all my data to >> another format, deinstall the older python, and reinstall the latest >> version. Next i had to create a new Berkley database and put the data back >> in. > >That one got me too and it's a peeve of mine. I think the Python lib >should include a dbm implementation that it sticks to unless the user >specifically requests a different one. And perhaps a migration tool that runs under the new version and makes conversions easy? Regards, Bengt Richter From vivek at cs.unipune.ernet.in Sun Dec 7 05:26:38 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Sun, 7 Dec 2003 15:56:38 +0530 Subject: Some problems for exercises Message-ID: <20031207155638.A29575@cs.unipune.ernet.in> Hi all, Here we are conducting a QIP program for teachers in other colleges. I am assigned the job of taking lectures in Python. Although there will be not much time (exactly speaking : 4 hours) for me to tell them each and everything in python, I am trying to cover as much as I can. Here are the areas which I am planning to cover : 1. Basic Language facilities : (Data structures, control structures, input/output, object oriented programming etc.) 2. A brief (rather very brief) Introduction to GUI programming with Tkinter 3. CGI programming in Python 4. Database programming with PostgreSQL Although I have prepared the presentation slides etc. I was unable to think of some good problems for exercises, which can cover the above mentioned topics well and also by solving them they can learn Python in an easy and fast way. So, as usual I have turned to you u people for help :). Please suggest me some such problems and where to look for it. TIA, Vivek Kumar From mwh at python.net Sun Dec 14 09:35:54 2003 From: mwh at python.net (Michael Hudson) Date: Sun, 14 Dec 2003 14:35:54 GMT Subject: ossaudiodev References: Message-ID: Tyler Eaves writes: > The docs list the module as being available on FreeBSD, yet neither 2.2 > (built from ports) I don't think it was in 2.2. > or 2.3.2 (built by hand from canonical sources) have it. Well, then it's up to you to investigate why it wasn't built (look in setup.py at first, I guess). The source certainly should be there. Cheers, mwh -- Every now and then, Google doesn't throw up what I need so I start checking Altavista, Yahoo, etc. In almost every single case, I am brutally reminded why I use Google in the first place. -- John Riddoch, asr From paska at kios.sk Tue Dec 9 02:50:23 2003 From: paska at kios.sk (Stano Paska) Date: Tue, 09 Dec 2003 08:50:23 +0100 Subject: sorting slovak utf In-Reply-To: <3FD45B2C.1080107@kios.sk> References: <3FD45B2C.1080107@kios.sk> Message-ID: <3FD57EBF.4070000@kios.sk> I had an imagination, that there is some easy way to work with slovak, russian, english and german text in one application. I only change locale from sk_SK.utf-8 to ru_RU.utf-8, ... and system works. Input and output are in utf-8. Is this a fantasy? Stano. From cartermark46 at ukmail.com Tue Dec 30 08:35:34 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 30 Dec 2003 05:35:34 -0800 Subject: Programming language from python References: Message-ID: "Alejandro Lombardo" wrote in message > I need to create a programming language. Why? Why not just use Python as-is? > Can this be done with the > latest version of python? Yes, given some extra modules. But like it says in a Star Trek movie: "Just because a thing can be done, does not mean that it should be done". > Is python the best computer programming > language development tool in the entire universe? No. From birdiepageANTI at SPAMciudad.FILTERcom.ar Wed Dec 17 00:35:32 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Wed, 17 Dec 2003 02:35:32 -0300 Subject: I see advice on how to debug a python module that hangs up the process In-Reply-To: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: I'm still newbie at Python, but not at programing, so this is just a wild guess. Have you checked that you are not using a reserved word as function or parameter name? If the function hangs when it's invoked, are you using some Object as part of the call? Have you checked that object? Gedece From Mike at DeleteThis.Geary.com Wed Dec 31 14:16:46 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 31 Dec 2003 11:16:46 -0800 Subject: Maybe a stupid idea References: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: Hi Sebb, Your idea is not stupid at all, and your English is very good. :-) I don't know how much luck you would have getting this built into the core language, but fortunately you don't really need to. It is very easy to add it yourself. Here are a couple of ways you could do it. The easiest would be something like this, a function that returns a list containing your cycle of values. Note that "first" is the first and last value in the list, and "limit" is one more than the largest value in the list. I did it this way to be consistent with Python's range function. def cycle( first, limit ): "Return list of values from first up to limit-1 and down to first." return range( first, limit ) + range( limit - 2, first - 1, -1 ) print cycle( 1, 5 ) # print the list itself for b in cycle( 1, 5 ): print "*" * b Another approach would use a generator (a function that returns a series of values by using a yield statement): def cycle( first, limit ): "Return series of values from first up to limit-1 and down to first." for value in xrange( first, limit ): yield value for value in xrange( limit - 2, first - 1, -1 ): yield value for b in cycle( 1, 5 ): print "*" * b This approach doesn't construct and return the actual list of values as the first one does (that's why I didn't put the "print cycle( 1, 5 )" statement in this test). It calculates and returns the values on the fly. This would use less memory for a very long cycle, but it's not quite as simple as the first approach. Both techniques are useful to know about. Hope that helps! -Mike sebb wrote: > I'm kind of newbie to programming, but I thought of > something and I want some opinions on that. > > It's about a new instruction block to do some cycles. > > I thought about that because it's not very easy to > program a cycle. Here is a simple example : > > b=0 > > while b < 50: > b+=1 > print "*" * b > > while b > 0: > b-= 1 > print "*" * b > > It takes two while blocks to do a cycle. > > I know that cycles is not a structure of any programming > language, but I want some opinions the know if my idea > is stupid or not. > > If the idea is not so stupid, python may be the first language > to have a completely new structure block :-) > > Note : English is not my mother tongue so the message can > have mistakes. From davecook at nowhere.net Sat Dec 20 08:45:55 2003 From: davecook at nowhere.net (David M. Cook) Date: Sat, 20 Dec 2003 13:45:55 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: In article , John Roth wrote: > to Python. Maybe the fact that such industry heavy hitters as Robert > Martin, David Thomas, and any number of others have switched > shouldn't count. In fact, the head of this thread should really be a I think this has a lot to do with Ruby's greater similarity to Smalltalk. Dave Cook From mnations at airmail.net Fri Dec 19 20:34:03 2003 From: mnations at airmail.net (Marc) Date: 19 Dec 2003 17:34:03 -0800 Subject: Hiding console with program compiled in PY2EXE References: Message-ID: <4378fa6f.0312191734.6aa47784@posting.google.com> Update! Silly me. I had a problem further upstream that was causing it to fail. It has nothing to do with the COM interaction. Works perfect now! Thanks again, Marc From sombDELETE at pobox.ru Sun Dec 21 06:36:08 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 21 Dec 2003 14:36:08 +0300 Subject: Unicode from Web to MySQL References: Message-ID: >>Quick scanning of mysql-python docs reveals that you should also >>call connect with unicode='utf-8' parameter. Have you done that? >> > I added that now, but it doesn't seem to make much difference > (I think it's more for returning data from MySQL, not storing it, > but that will still be useful) It's for storing too. If you pass str to .execute it will take the string and just pass it to MySQL as you created it. But if you use args parameter of .execute method it will take care of convertions and escaping. In fact you should pass even ascii strings via args parameter, if you don't want to deal with escaping yourself. > I did a test where I grabbed the URL using the same routines and > dumped the thing to a file, and then edited out all the English and > various HTML, and the SQL insert works at that point. It probably contained illegal characters from SQL point of view. > It seems the mixed language is throwing stuff off, which wouldn't > bother me if my re.search for only the Vietnamese text were working > properly, but it isn't. Why? re.search works fine for my Russian unicode characters. -- Serge. From BrenBarn at aol.com Mon Dec 29 21:13:32 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 30 Dec 2003 02:13:32 GMT Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Peter Otten wrote: >> Then, for AL runs, you need to replace European numerals with >> Arabic numerals (but keeping the LTR order). > > I always thought of numbers as most significant digit first. But > the above suggests that they are least significant digit first, > preserving the original RTL directionality. In Arab countries which use the Indian numerals (not the "Arabic" ones that we use in the west), the numbers are written with the most significant digit at the left. This is indeed "last" with respect to the normal right-to-left direction of Arabic. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From km at mrna.tn.nic.in Thu Dec 18 08:07:43 2003 From: km at mrna.tn.nic.in (km) Date: Thu, 18 Dec 2003 18:37:43 +0530 Subject: documentation In-Reply-To: <20031218120515.GA2564@nl.linux.org> References: <20031218091118.GA3296@mrna.tn.nic.in> <20031218120515.GA2564@nl.linux.org> Message-ID: <20031218130743.GA3646@mrna.tn.nic.in> Hi all, unfortunately none of these works. do i have to set the PYTHONDOCS variable ? what should it be set to ? i have a 2.3 version of Python running on my RHL box. kindly enlighten, thanks, KM ----------------------------------------------------------------------- On Thu, Dec 18, 2003 at 01:05:16PM +0100, Gerrit Holl wrote: > km wrote: > > i am coming from a Perl background. i am now learning python. > > suppose in Perl, to look at the perdocumentation page for variables in perl one can get the info by invoking perldoc perlvar. how to search for same in Python ? > > pydoc pyvar :) > > Or, interactive: > help(pyvar) > > Gerrit. > > -- > 61. If the gardener has not completed the planting of the field, > leaving one part unused, this shall be assigned to him as his. > -- 1780 BC, Hammurabi, Code of Law > -- > Asperger's Syndrome - a personal approach: > http://people.nl.linux.org/~gerrit/english/ -- From mwilson at the-wire.com Fri Dec 12 11:52:01 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 12 Dec 2003 11:52:01 -0500 Subject: optimization pointers? References: <3fd9cdf1$0$6970$7a628cd7@news.club-internet.fr> Message-ID: In article <3fd9cdf1$0$6970$7a628cd7 at news.club-internet.fr>, "Anthony McDonald" wrote: >Heres my contribution, removing the string append in favour of slices. Buys >a little speed thanks to xrange. > >def lz_comp_mine(text): > voc = {} > st = 0 > for cur in xrange(1,len(text)+1): > if not voc.get(text[st:cur], False): > voc[text[st:cur]] = True > st = cur > return len(voc) Nice touch! I tried slices and took a huge performance hit (almost 3x the list version) but I didn't use `for ... in xrange ...`. It must have all been in the while-loop test and index incrementing. Regards. Mel. From gerrit at nl.linux.org Thu Dec 18 07:05:16 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 18 Dec 2003 13:05:16 +0100 Subject: documentation In-Reply-To: <20031218091118.GA3296@mrna.tn.nic.in> References: <20031218091118.GA3296@mrna.tn.nic.in> Message-ID: <20031218120515.GA2564@nl.linux.org> km wrote: > i am coming from a Perl background. i am now learning python. > suppose in Perl, to look at the perdocumentation page for variables in perl one can get the info by invoking perldoc perlvar. how to search for same in Python ? pydoc pyvar :) Or, interactive: help(pyvar) Gerrit. -- 61. If the gardener has not completed the planting of the field, leaving one part unused, this shall be assigned to him as his. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From briandee at mail.weber.edu Mon Dec 15 15:28:18 2003 From: briandee at mail.weber.edu (Brian Dee) Date: Mon, 15 Dec 2003 13:28:18 -0700 Subject: intro to python books References: Message-ID: Another GREAT on-line book/tutorial is http://diveintopython.org/ From kmneilso at yahoo.com Mon Dec 15 10:57:47 2003 From: kmneilso at yahoo.com (Kerry Neilson) Date: 15 Dec 2003 07:57:47 -0800 Subject: Idle won't start References: Message-ID: Michael Hudson wrote in message news:... > kmneilso at yahoo.com (Kerry Neilson) writes: > > > For the past couple of months, Idle won't start when I invoke it. I > > am at a complete loss for why this is. When this happens, they python > > command line still starts, and python works fine otherwise. > > Most interesting to me is that a reboot won't fix the problem. But if > > I just try it again sometime later it will work. Anyone have any > > ideas? I'm running python 2.3 on windows 2000 professional. > > Do you have any firewall type software? Some Windows firewalls > apparently believe trying to open a socket to 127.0.0.1 is a dastardly > attempt to compromise your privacy... > > Cheers, > mwh No firewall. From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 06:00:52 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 12:00:52 +0100 Subject: canonical file access pattern? References: Message-ID: Hans-Joachim Widmaier: >Then I've seen OSError as well as IOError raised occassionaly. The documentation says only IOError can be raised. Is there a bug? "When a file operation fails for an I/O-related reason, the exception IOError is raised." http://www.python.org/doc/current/lib/bltin-file-objects.html >Seems like I have do this, then: > >try: > f = file(filename, op) >except (OSError, IOError), e: > # Handle open() error >else: > try: > # read/write to the file > f.close() # flushes write buffers, so can fail, too > except (OSError, IOError), e: > # Handle read/write errors This is not correct, since the file is not closed when an exception is thrown by read or write. If we assume the following: 1. A file that is opened should be closed in all cases 2. Every exception raised by read, write or close should be caught and handled Then this would need to be the algorithm: try: f = file("spam.txt", "w") except IOError, e: # Handle open() error pass else: try: try: # read/write to the file pass except IOError, e: # Handle read/write errors pass finally: try: f.close() except IOError, e: # Handle close error pass Not very pretty, but I can't think of a simplification that does not violate one of the assumptions. -- Ren? Pijlman From stephan.diehlNOSPAM at gmx.net Sat Dec 27 11:36:46 2003 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Sat, 27 Dec 2003 17:36:46 +0100 Subject: Some optimization tale Message-ID: A while ago, I've posted a recipie about finding a common prefix to a list of strings. While the recipie itself is quite bad (I have to admit) and I didn't know at that time that this problem was solved already in the os.path module. The interesting part can be found in the commentaries, as this turned out to be a quest for the most efficient algorithm to solve this particular problem. All of this can be found at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252177 What I was most surprised at was the inefficency of the trivial solutions (and that the right algorithm makes indeed a difference). If you have read that far, you might be interested in the actual algorithms. (If you are interested in the one-liner versions, please have a look at the recipie) Here they are: -- os.path.commonprefix -------------------------------------------------- def f1(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix --------------------------------------------------------------------------- The problem with this algorithm is the copying of all those small strings. This can be easily fixed --- optimized os.path.commonprefix ---------------------------------------- def f2(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' if len(m) == 1: return m[0] prefix = m[0] for i in xrange(len(prefix)): for item in m[1:]: if prefix[i] != item[i]: return prefix[:i] return prefix[:i] --------------------------------------------------------------------------- Now it gets interesting. It turns out that the above algorithms doesn't scale well. Some anonymous submitter suggested the following ---- by anonymous --------------------------------------------------------- def f3(seq): if not seq:return "" seq.sort() s1, s2 = seq[0], seq[-1] l = min(len(s1), len(s2)) if l == 0 : return "" for i in xrange(l) : if s1[i] != s2[i] : return s1[0:i] return s1[0:l] --------------------------------------------------------------------------- It is just not nessesary to compare all strings in the list. It is enough to sort the list first and then compare the first and the last element. Even though the 'sort' algorithm is coded in C and is therefore quite fast, the order of runtime has changed. Michael Dyck then pointed out that instead of using 'sort', 'min' and 'max' should be used. While tests suggest that this is true, I have no idea why that should be, since finding a minimum or maximum uses some sorting anyway (if we don't have some quantum computer at our hands), so, my reasoning would be that sorting once should be faster than computing both, maximum and minimum. You might have realized that the optimization so far was done one the number of strings. There is still another dimension to optimize in and that is the actual string comparing. Raymond Hettinger suggests using a binary search: --------------------------------------------------------------------------- def f4(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' a, b = min(m), max(m) lo, hi = 0, min(len(a), len(b)) while lo < hi: mid = (lo+hi)//2 + 1 if a[lo:mid] == b[lo:mid]: lo = mid else: hi = mid - 1 return a[:hi] ---------------------------------------------------------------------------- To give you some ideas about the running times: f1 f3 f4 # of strings ['0.131058', '0.021471', '0.012050'] 2 ['0.214896', '0.041648', '0.012963'] 4 ['0.401236', '0.020444', '0.014707'] 8 ['0.841738', '0.026415', '0.018589'] 16 ['1.670606', '0.039348', '0.029020'] 32 ['3.184446', '0.065657', '0.044247'] 64 ['6.257635', '0.123510', '0.072568'] 128 Every calculation was done 200 times. Furthermore, the testset consists of only two different strings, so the binary search part of Raymonds solution comes only in as a static factor. Anyway, the fastest solution is up to a 100 times faster than the trivial one. Cheers Stephan From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 05:27:19 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 11:27:19 +0100 Subject: Programming language from python References: Message-ID: <8fk2vvg18hgvocrmm09b86epekpdnuc02t@4ax.com> Alejandro Lombardo: >I need to create a programming language. Can this be done with the >latest version of python? Yes. >Is python the best computer programming language development tool in >the entire universe? No. >If it isn?t could you please tell me the name of the best computer >programming language development tool Eiffel. http://docs.eiffel.com/general/guided_tour/language/invitation-00.html >in the entire universe? The lander defense system of the Martians is also quite good. -- Ren? Pijlman From hokiegal99 at hotmail.com Wed Dec 24 10:33:45 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Wed, 24 Dec 2003 10:33:45 -0500 Subject: file opening and closing Message-ID: jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') Should this file be closed after reading? If so, how would one close it? What's the downside to not closing it? From yan at NsOeSiPnAeMr.com Thu Dec 4 15:15:49 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Thu, 04 Dec 2003 15:15:49 -0500 Subject: Newbie data structes question References: Message-ID: On Thu, 04 Dec 2003 15:34:27 +0100, Peter Otten wrote: > Seriously, most work is done with Python's powerful list/dictionary > implementations. Thanks for all the help from everyone. I've done programming (tons and tons) in C, some in lisp, and gobs years ago in FORTRAN and SNOBOL. It's always interesting to come across new ideas; I'm going to have to chew on the little snippets of code pasted here until I can digest them. Those new ideas hurt until they are assimilated.... :-) -Kamus From nessus at mit.edu Tue Dec 9 10:45:38 2003 From: nessus at mit.edu (Douglas Alan) Date: Tue, 09 Dec 2003 10:45:38 -0500 Subject: Lists and Tuples References: Message-ID: "Tim Peters" writes: > [Fredrik Lundh] >> ... >> I expect an apology. > > No you didn't . But, in the Holiday Spirit, I'm terribly sorry, and > while I don't expect you to forgive me, I promise I'll do my best to see > that it never happens again. > > if-only-an-apologetic-spirit-were-contagious-ly y'rs - tim I accept your apology. Tim, you are a scholar and a gentleman. |>oug From doeringm at gmx.de Mon Dec 1 05:30:20 2003 From: doeringm at gmx.de (Martin Doering) Date: Mon, 01 Dec 2003 11:30:20 +0100 Subject: un-tuple (newbie) Message-ID: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> Hi! I want to use Jython to fetch exactly one value from a database query, like here: # execute a query def query(db, sql): c = db.cursor() c.execute(sql) for line in c.fetchall(): val = line print val c.close() return val I could find out, how to create a tuple with just one member, but I can not find out how to get a value from a tuple with just one member. It will be an easy answer, I think. Sorry, it all is totally new for me. :-) -- Martin Doering From usenet at soraia.com Fri Dec 5 10:15:20 2003 From: usenet at soraia.com (Joe Francia) Date: Fri, 05 Dec 2003 15:15:20 GMT Subject: How to call a python function in visual c++ In-Reply-To: References: Message-ID: Pande wrote: > Hello everyone! > I have defined a function in python, now I must call this function in visual > c++. > I have tried with PyObject_CallFunction. but my program is crashed. > > can someone tell where the problem is? > It may have something to do with this: http://www.catb.org/~esr/faqs/smart-questions.html From inyeol.lee at siimage.com Mon Dec 8 23:43:52 2003 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Mon, 8 Dec 2003 20:43:52 -0800 Subject: need help on sublcass and scope Message-ID: <20031209044352.GG3998@siliconimage.com> I'm an OOP newbie, and needs help on subclassing from different module. I made a base module a.py which contains two classes C1 and C2; ## start of a.py class C1(object): def m(self): print "method m in class C1 in module a" class C2(object): def __init__(self): print "class C2 in module a" self.a = C1() self.a.m() ## end of of a.py Then, I made another module b.py which extends this base module; ## start of b.py import a class C1(a.C1): def m(self): print "method m in class C1 in module b" a.C1.m(self) class C2(a.C2): def __init__(self): print "class C2 in module b" a.C2.__init__(self) ## end of of b.py When I instantiate C2, I get; >>> import b >>> i = b.C2() class C2 in module b class C2 in module a method m in class C1 in module a >>> It doesn't use class C1 in module 'b', but uses C1 in module 'a' because the last line in b.py 'a.c2.__init__(self)' runs with module scope a. So I tweaked the C1 instantiation line in a.py from self.a = C1() to import sys self.a = sys.modules[self.__module__].C1() and got the result I expected; >>> import b >>> i = b.C2() class C2 in module b class C2 in module a method m in class C1 in module b method m in class C1 in module a >>> but it looks like an ugly hack to me. If there's common OOP idiom to handle this kind of problem, give me some pointer. Thanks, Inyeol From email9898989 at yahoo.com Thu Dec 11 13:44:11 2003 From: email9898989 at yahoo.com (email9898989 at yahoo.com) Date: 11 Dec 2003 10:44:11 -0800 Subject: python vs php for web programming References: <425cc8d1.0312110636.56be9ecf@posting.google.com> Message-ID: mir4uu at yahoo.com (mir nazim) wrote in message news:<425cc8d1.0312110636.56be9ecf at posting.google.com>... > i m currently using PHP with Apache (a.k.a 'mod_php') for my web > development work. i came to know that python can also be used to do > web programming using 'mod_python' for Apache. i wanted to know the > difference between th two 'mod_php' and 'mod_python' in terms of: > > 1. speed of execution. > 2. productivity > 3. maintainance > (i know python is most productive and maintainable language in the > world, but is it same for web programming with Apache). > 4. availability of features e.g, cookies and session hadling, > databases, protocols, etc. I can't really give you "the answer" if there is one, but here are some resources I've found helpful: http://colorstudy.com/docs/shootout.html http://www.python.org/cgi-bin/moinmoin/WebProgramming If you want something similar to PHP, see Spyce. If you want to do most of your coding in pure python, see Quixote or the cgi module. If you want to use templates (like PHP with Smarty), then see Cheetah, Albatross, etc. There are dozens of options now, but no one real front runner popularity-wise (except maybe Cheetah for templates). Realize though most web hosts out there though don't provide modpython (or java for that matter), so try it out on your own computer first or go with a python-friendly web host (some are also listed at the wiki). From billSneddonNoSpam at comcast.com Mon Dec 22 21:37:17 2003 From: billSneddonNoSpam at comcast.com (Bill Sneddon) Date: Mon, 22 Dec 2003 21:37:17 -0500 Subject: any one used googles api? In-Reply-To: References: Message-ID: Thanks to all. I was able to make pyGoogle work quite easily. I did try looking at the source but was getting tangled up in the enheritance. I guess building a general soap parser is non-trival. I was looking for more of low-brow approach. F. Lundh's site: http://effbot.org/zone/element-google.htm some of the examples there were helpful. I think I need to learn more about parsing xml and xml.sax.handler.ContentHandler. Thanks again for your input I am learning how be it slowly. Bill From deets_noospaam at web.de Tue Dec 9 12:21:05 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 18:21:05 +0100 Subject: regex confusion References: <3FD5FB97.CB8118FB@engcorp.com> Message-ID: > Hmm. But when thats true, what does ".??" then mean - the first ? is not > greedy, so it is nothing matched at all. The same is true for ".*?", and > ".+?" is then equal to "." So what makes this useful? The regex in > question definitely didn't work with it. Ok - I just found out - it makes sense when taking into account what follows in the regex, as that will be matched earlier. Neat - didn't know that such things existed. Diez From berteun at NO_SPAMdds.nl Wed Dec 17 07:51:48 2003 From: berteun at NO_SPAMdds.nl (Berteun Damman) Date: Wed, 17 Dec 2003 12:51:48 +0000 (UTC) Subject: Own C-extension module causes SIGABRT when imported. Message-ID: Hello, First I was trying to get PyOSD, but as soon as I did `import pyosd' Python received a SIGABRT. Then I wrote my own module, which looks like: #include static PyMethodDef testmod_methods[] = { {NULL, NULL} }; void initmymod(void) { Py_InitModule("mymod", testmod_methods); } So, nothing fancy here. When I just compile it, it can be imported, and it works (i.e. I can do print mymod.__name__). But as soon as I only link the module to libxosd, it causes an SIGABRT, linking it to, say, libkhtml or libxmltok doesn't cause any problems. Therefore I suspect the problem lies with libxosd (version 2.2.5). Furthermore, the problem both occurs with Python 2.3.2 and Python 2.2.3. I've compiled both with debugging information, and gdb shows the following stacktraces (I do gdb python2.3 and then r -c 'import mymod'). Python 2.3.2 stacktrace: Program received signal SIGABRT, Aborted. 0x4821390b in kill () from /usr/lib/libc.so.12 (gdb) bt #0 0x4821390b in kill () from /usr/lib/libc.so.12 #1 0x48215cf6 in __libc_mutex_unlock () from /usr/lib/libc.so.12 #2 0x48292916 in __flockfile_internal () from /usr/lib/libc.so.12 #3 0x48280803 in fclose () from /usr/lib/libc.so.12 #4 0x48101669 in import_submodule (mod=0x4813fb28, subname=0xbfbfee90 "mymod", fullname=0xbfbfee90 "mymod") at Python/import.c:2293 #5 0x48100f30 in load_next (mod=0x4813fb28, altmod=0x4813fb28, p_name=0xbfbff2b0, buf=0xbfbfee90 "mymod", p_buflen=0xbfbfee8c) at Python/import.c:2111 #6 0x4810097d in import_module_ex (name=0x0, globals=0x806a79c, locals=0x806a79c, fromlist=0x4813fb28) at Python/import.c:1957 #7 0x48100b9a in PyImport_ImportModuleEx (name=0x80f0114 "mymod", globals=0x806a79c, locals=0x806a79c, fromlist=0x4813fb28) at Python/import.c:1998 #8 0x480d94dd in builtin___import__ (self=0x0, args=0x80726bc) at Python/bltinmodule.c:45 #9 0x480aade7 in PyCFunction_Call (func=0x805abec, arg=0x80726bc, kw=0x0) at Objects/methodobject.c:73 #10 0x48083169 in PyObject_Call (func=0x805abec, arg=0x80726bc, kw=0x0) at Objects/abstract.c:1755 #11 0x480e7825 in PyEval_CallObjectWithKeywords (func=0x805abec, arg=0x80726bc, kw=0x0) at Python/ceval.c:3346 #12 0x480e4cfb in eval_frame (f=0x809540c) at Python/ceval.c:1996 #13 0x480e6548 in PyEval_EvalCodeEx (co=0x80e91a0, globals=0x806a79c, locals=0x806a79c, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #14 0x480e1a6b in PyEval_EvalCode (co=0x80e91a0, globals=0x806a79c, locals=0x806a79c) at Python/ceval.c:537 #15 0x48109ac5 in run_node (n=0x8052350, filename=0x48135c4b "", globals=0x806a79c, locals=0x806a79c, flags=0xbfbff634) at Python/pythonrun.c:1239 #16 0x48109a5c in run_err_node (n=0x8052350, filename=0x48135c4b "", globals=0x806a79c, locals=0x806a79c, flags=0xbfbff634) at Python/pythonrun.c:1226 #17 0x48109935 in PyRun_StringFlags (str=0x804f030 "import mymod\n", start=257, globals=0x806a79c, locals=0x806a79c, flags=0xbfbff634) at Python/pythonrun.c:1196 #18 0x48108a52 in PyRun_SimpleStringFlags (command=0x804f030 "import mymod\n", flags=0xbfbff634) at Python/pythonrun.c:863 #19 0x4810f9d1 in Py_Main (argc=3, argv=0xbfbff6dc) at Modules/main.c:399 #20 0x08049042 in main () #21 0x08048d2a in ___start () Lines 2292-2293 of import.c are: 2292 if (fp) 2293 fclose(fp); With Python 2.2.3 gdb gives this stacktrace: Program received signal SIGABRT, Aborted. 0x481d490b in kill () from /usr/lib/libc.so.12 (gdb) bt #0 0x481d490b in kill () from /usr/lib/libc.so.12 #1 0x481d6cf6 in __libc_mutex_unlock () from /usr/lib/libc.so.12 #2 0x48254f6f in malloc () from /usr/lib/libc.so.12 #3 0x080597de in PyString_FromString (str=0x48276856 "mymod") at Objects/stringobject.c:135 #4 0x080ea9d7 in PyDict_GetItemString (v=0x812f60c, key=0x48276856 "mymod") at Objects/dictobject.c:1866 #5 0x080a1e1f in PyImport_AddModule (name=0x48276856 "mymod") at Python/import.c:480 #6 0x080a8cc2 in Py_InitModule4TraceRefs (name=0x48276856 "mymod", methods=0x482779c4, doc=0x0, passthrough=0x0, module_api_version=1011) at Python/modsupport.c:56 #7 0x48276826 in initmymod () at mymod.c:5 #8 0x080a5d48 in _PyImport_LoadDynamicModule (name=0xbfbfeeb0 "mymod", pathname=0xbfbfea10 "mymod.so", fp=0x4826f460) at Python/importdl.c:53 #9 0x080a3301 in load_module (name=0xbfbfeeb0 "mymod", fp=0x4826f460, buf=0xbfbfea10 "mymod.so", type=3) at Python/import.c:1410 #10 0x080a484d in import_submodule (mod=0x810c284, subname=0xbfbfeeb0 "mymod", fullname=0xbfbfeeb0 "mymod") at Python/import.c:1947 #11 0x080a408d in load_next (mod=0x810c284, altmod=0x810c284, p_name=0xbfbff2d0, buf=0xbfbfeeb0 "mymod", p_buflen=0xbfbfeeac) at Python/import.c:1803 #12 0x080a3a34 in import_module_ex (name=0x0, globals=0x8142c0c, locals=0x8142c0c, fromlist=0x810c284) at Python/import.c:1649 #13 0x080a3d46 in PyImport_ImportModuleEx (name=0x815051c "mymod", globals=0x8142c0c, locals=0x8142c0c, fromlist=0x810c284) at Python/import.c:1690 #14 0x080ed1bc in builtin___import__ (self=0x0, args=0x813a84c) at Python/bltinmodule.c:40 #15 0x080eafdc in PyCFunction_Call (func=0x812b200, arg=0x813a84c, kw=0x0) at Objects/methodobject.c:79 #16 0x080c62e1 in PyObject_Call (func=0x812b200, arg=0x813a84c, kw=0x0) at Objects/abstract.c:1688 #17 0x0808bf4f in PyEval_CallObjectWithKeywords (func=0x812b200, arg=0x813a84c, kw=0x0) at Python/ceval.c:3058 #18 0x08087c89 in eval_frame (f=0x8132c0c) at Python/ceval.c:1843 #19 0x0808a828 in PyEval_EvalCodeEx (co=0x814bb00, globals=0x8142c0c, locals=0x8142c0c, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2595 #20 0x08080787 in PyEval_EvalCode (co=0x814bb00, globals=0x8142c0c, locals=0x8142c0c) at Python/ceval.c:481 #21 0x080aced5 in run_node (n=0x817e480, filename=0x8101ecd "", globals=0x8142c0c, locals=0x8142c0c, flags=0xbfbff63c) at Python/pythonrun.c:1067 #22 0x080ace7f in run_err_node (n=0x817e480, filename=0x8101ecd "", globals=0x8142c0c, locals=0x8142c0c, flags=0xbfbff63c) at Python/pythonrun.c:1054 #23 0x080acdb8 in PyRun_StringFlags (str=0x812c030 "import mymod\n", start=257, globals=0x8142c0c, locals=0x8142c0c, flags=0xbfbff63c) at Python/pythonrun.c:1021 #24 0x080abd05 in PyRun_SimpleStringFlags (command=0x812c030 "import mymod\n", flags=0xbfbff63c) at Python/pythonrun.c:700 #25 0x08052f8b in Py_Main (argc=3, argv=0xbfbff6dc) at Modules/main.c:351 #26 0x08052852 in main (argc=3, argv=0xbfbff6dc) at Modules/python.c:10 #27 0x0805254a in ___start () stringobject has on the lines 135-136: 135 op = (PyStringObject *) 136 PyObject_MALLOC(sizeof(PyStringObject) + size * sizeof(char)); Well, I really don't understand why this only goes wrong when linking to xosd (and not even using any kind of its functionality). The osd_cat program provided with libxosd works. The system I'm working on is NetBSD-current (1.6ZG, compiled yesterday). Perhaps it has nothing to do with Python, but more with libxosd, but it the end it's Python that causes the error. :) Berteun Damman From alanmk at hotmail.com Sun Dec 7 11:37:18 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 07 Dec 2003 16:37:18 +0000 Subject: Best structure for (binary) trees? References: Message-ID: <3FD3573E.D6FF7EFF@hotmail.com> [Rasmus] > As partly novice in python I would like a piece of advise of how to > implement (binary) trees the best way? The original Python Enhancement Proposal (PEP) for Generators (a recently introduced feature of the python language), PEP-255, contains a nice example of building and navigating binary trees. http://www.python.org/peps/pep-0255.html Search for the text "binary tree class" on that page. That should give you sufficient sample code to play with. If you're able to follow the generator/yield -based examples, I'd be so bold as to say that that is "the best way". regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From anthony at ekit-inc.com Mon Dec 1 01:59:26 2003 From: anthony at ekit-inc.com (Anthony Baxter) Date: Mon, 01 Dec 2003 17:59:26 +1100 Subject: Ques From CS Grad Student In-Reply-To: Message from martin@v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) of "01 Dec 2003 07:43:21 BST." Message-ID: <200312010659.hB16xQVO020012@maxim.off.ekorp.com> >>> Martin v. =?iso-8859-15?q?L=F6wis?= wrote > You could also count the people that ever made a release, which would > be a number below 10 (although I don't know myself what the number > would be). Then you could count people that ever reported a bug, which > would be larger than the number of people in Misc/ACKS. Starting from PEP 0006, I'd say that the number is between 7 and 10. Anthony Baxter: 2.1.2, 2.1.3, 2.3.1, 2.3.2. Barry Warsaw: 2.2(?) 2.3(?) 2.2.3. Guido van Rossum: many, including 2.2.2. Michael Hudson: 2.2.1. Thomas Wouters: 2.1.1. Moshe Zadka: 2.0.1. The only other names I can think of that might have done a (major) release would be Jeremy, Tim or Fred. Of course, if you count people that have done "some" of the release, you'd have to add Tim and Thomas Heller (windows installers), Jack Jansen (Mac installers), Fred (Doc packages) and Sean R. (RPM installers). -- Anthony Baxter It's never to late to have a happy childhood. From tjreedy at udel.edu Mon Dec 8 12:20:21 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Dec 2003 12:20:21 -0500 Subject: Base conversion method or module References: <20031207234517.22983.00000297@mb-m27.aol.com> <0b88tvo38l9ca8fhc3127mskqegdpfocn7@4ax.com> Message-ID: "Jeff Wagner" wrote in message news:0b88tvo38l9ca8fhc3127mskqegdpfocn7 at 4ax.com... > So I decide to go and try out this GMPY and download the win32 binaries. It consists of two files, > gmpy.pyd and pysymbolicext.pyd ... what do I do with them, just copy them to the lib folder? Specifically, Pythonx.y/Libs/site-packages (at least on my system) >>>import sys; sys.path should have site-packages dir near beginning. > Then it says I need GMP-4.x so I get that, too. It's like nothing I've ever seen before. How can I > install that on my WinXP box? no idea. sorry. .so is unix version of .dll. try gmp site for windows .dll binary tjr From vivek at cs.unipune.ernet.in Sun Dec 7 23:12:11 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Mon, 8 Dec 2003 09:42:11 +0530 Subject: Some problems for exercises In-Reply-To: ; from wlfraed@ix.netcom.com on Sun, Dec 07, 2003 at 09:37:20PM +0000 References: Message-ID: <20031208094211.B15490@cs.unipune.ernet.in> On Sun, Dec 07, 2003 at 09:37:20PM +0000, Dennis Lee Bieber wrote: > vivek at cs.unipune.ernet.in fed this fish to the penguins on Sunday 07 > December 2003 02:26 am: > > > > > 4. Database programming with PostgreSQL > > > OUCH! > > Without knowing their backgrounds I could easily fill four hours on > just relational database THEORY (normal forms, etc.) without even > getting down to any particular RDBM software. The looseness of MySQL > might be a touch easier to work with, since it doesn't enforce > referential integrity (try explaining that to newbies). As I mentioned in my post they are Computer Science Teachers in other colleges. So we can safely assume that they atleast know these basic things. At least they have some familiarity with these concepts. And also they have just attended the classes in RDBMS. There were lectures on Oracle DBA. So, I think that it will not be a problem with them. Also our main focus will be on Python. > > > Although I have prepared the presentation slides etc. I was unable to > > think of some good problems for exercises, which can cover the above > > mentioned topics well and also by solving them they can learn Python > > in an easy and fast way. > > > In four hours? > That means four hours of theory lectures and four hours of practical sessions. > Let's see, a local Tkinter front-end for adding/modifying records in > the database, with a CGI back-end to an HTML "on-line ordering form" > accessing the same database. I suspect you'd have to predefine the > database schema -- if they have to do that analysis along with > designing applications for it > Thanks, Vivek Kumar > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > > -- > http://mail.python.org/mailman/listinfo/python-list From crawley.storm at IveGotEnoughSpamAsItIS.com Mon Dec 22 18:09:27 2003 From: crawley.storm at IveGotEnoughSpamAsItIS.com (Rich) Date: Mon, 22 Dec 2003 23:09:27 +0000 Subject: Python re repetative matching Message-ID: Im new to regex's and cant quite figure out how to get them to work, what I want is a tuple of all the matches from the regex. Ive simplified my actual problem and still cant get it to work Ive so far got this: print re.findall( r'(@\d+)|(\w+)', "@5489 heel all and thumb toe" ) This dose exactly what I want, except it matches both matches each time, so I end up with a list full tuples each with blank elements.... so close I also tried my orginal idea a = re.match( r'(@\d+)\s+(\w+)', "@5489 heel all and thumb toe" ) print a.groups() This matches the number and the first word, so I thought the following should rematch after the first word and give me what I wanted... but it dosent for some reason a = re.match( r'(@\d+)\s+(?:(\w+)\s*)', "@5489 heel all and thumb toe" ) print a.groups() This is my next iteration, still gives me the number (first group) and only the word (the second match). So I extend it to ... a = re.match( r'(@\d+)\s+(?:(\w+)\s*)*', "@5489 heel all and thumb toe" ) print a.groups() Now this gives me the number and the last but one word ? WHY! My logic suggests that this should do what I want... what am I missing, Ive spent all night trying to figure this out. Cheers Rich From dw-google.com at botanicus.net Wed Dec 31 14:51:58 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 31 Dec 2003 11:51:58 -0800 Subject: ishexdigit() References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <4l05vvs0ril5a2lr35pp52vq98n990jmef@4ax.com> Message-ID: <99dce321.0312311151.61b8b1c9@posting.google.com> Uwe Schmitt wrote... > better/faster/more pythonic: > > return reduce(lambda a,b: a and ishexdigit(b), strng, True) How is it better, or faster, or more Pythonic? The only thing I can see here that is 'more Pythonic' is blatant iterator abuse, which does nothing for the readability or efficiency of the code. :) What happened to good old fashioned functions, eh? def is_hex(s, (z,n,a,f) = map(ord, '09af')): for c in s: o = ord(c) | 32 # OR lowercase bit. if not (( o >= z and o <= n ) or ( o >= a and o <= f )): return False return True This could of course be improved upon too. For: profile.run("[ func('CAFEBABEAAAABBBBCCCCDDDDEEEEFFFF') \ for x in xrange(500000) ]") profile.run("[ func('CAFEBABEAAAABBBBCCCCDDDDEEEEFXFF') \ for x in xrange(100000) ]") profile.run("[ func('CAFEXABEAAAABBBBCCCCDDDDEEEEFXFF') \ for x in xrange(100000) ]") The iterative version looked like this: 32500002 function calls in 227.260 CPU seconds 6300002 function calls in 42.990 CPU seconds 3800002 function calls in 26.700 CPU seconds The 'grass roots' version looked like this: 500002 function calls in 21.090 CPU seconds 100002 function calls in 3.810 CPU seconds 100002 function calls in 1.770 CPU seconds Sometimes I really wonder as to whether Python gets it poorly performing name from it's implementation or it's 'standard' idioms. :) > Greetings, Uwe Happy new year, if you aren't already there. Speaking of which, Taxi! David. From hatespam at fakeemail.com Thu Dec 25 18:08:51 2003 From: hatespam at fakeemail.com (Dan Olson) Date: Thu, 25 Dec 2003 17:08:51 -0600 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: On Thu, 25 Dec 2003 14:12:12 -0800, Brandon J. Van Every wrote: > C is not a good language for anything but portable assembly. This will be fun, the same flamewar we had last month... but with Python fans involved! From janeaustine50 at hotmail.com Tue Dec 2 07:37:29 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 2 Dec 2003 04:37:29 -0800 Subject: python's threading has no "interrupt"? References: Message-ID: > > > > > >>As far as I know python's threading module models after Java's. > >>However, I can't find something equivalent to Java's interrupt and > >>isInterrupted methods, along with InterruptedException. > >>"somethread.interrupt()" will wake somethread up when it's in > >>sleeping/waiting state. > >> > >>Is there any way of doing this with python's thread? I suppose thread > >>interrupt is a very primitive functionality for stopping a blocked > >>thread. > >> > >> > >Well, I haven't got any answer since I posted it. Meanwhile, I have > >been searching for it myself. Something new has been added in 2.3 in > >thread module. That's interrupt_main. But, unfortunately, it is the > >opposite of what I expected; It interrupts the main thread. > > > >After all this, I am a bit disappointed about Python. (it's sad) > > > > > Did you try condition objects? threading.Condition > > Example from the library reference: > > # Consume one item > cv.acquire() > while not an_item_is_available(): > cv.wait() > get_an_available_item() > cv.release() > > # Produce one item > cv.acquire() > make_an_item_available() > cv.notify() > cv.release() > > > You can block a thread with a condition object by calling its 'wait()' > method. You can > call the 'notify()' method from another thread and that will 'interrupt' > the blocked thread. > > It is not the very same thing, but I suspect you can use it for the same > purposes. > > Cheers, > > Laci 1.0 Thanks, but it doesn't give a solution. The problem is that there can be multiple condition variables and I have to interrupt the thread no matter what condition variable is waiting. From jzgoda at gazeta.usun.pl Wed Dec 10 16:47:33 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 10 Dec 2003 21:47:33 +0000 (UTC) Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> Message-ID: Lawrence Oluyede pisze: >> Think about that last just a bit more. Asyncore is SUCH an >> upgrade over what most of the world is doing. > > Can you explain "over what most of the world is doing" a bit more? Most of the world still blocks execution with synchronous sockets. Event driven programming is not a wholly accepted idea. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From lkcl at lkcl.net Thu Dec 18 04:29:22 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Thu, 18 Dec 2003 09:29:22 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> <20031216212312.GL17021@lkcl.net> Message-ID: <20031218092922.GF6324@lkcl.net> On Wed, Dec 17, 2003 at 10:30:23PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > all i can do is recommend a framework and some guidelines on what > > conventions could be fitted over that framework. > martin, to clarify: "all i can do" is the wrong preamble phrase. "i would like to" is better. i was trying to be ... self-denigrating, over-careful, something like that. > originally provided. To prove that, I would need a complete proposal > how precisely what ACLs are set on what objects, and how exactly I > invoke code for restricted execution (i.e. what API do I call in what > order). what api, in what order, what code is invoked in (inside the python executable), _how_ ACLs are set on what objects, yes. _what_ acls are set on what objects is conditional on whether i receive funding to do so, or whether some other people can be of significant assistance. why? because there's a lot of them. what i was trying to say above, "all i can do is recommend a framework" is build up to an idea of adding in a framework, similar to Exceptions, by which ANY generically-defined restriction system can be plugged in to the python language. the idea being that if no such a system is not plugged in, the performance penalty on python is insignificant, and no user-code is restricted. however, this may all turn out to be unnecessary [quote from greg ewing]: > The spirit behind my suggestion was to start thinking about > ways in which functionality could be separated out so that > this kind of special-casing for security purposes isn't > needed. so, with the correct codebase reordering, a simple capabilities based system can be added, the problem goes away. yes? l. From cliechti at gmx.net Thu Dec 4 18:23:08 2003 From: cliechti at gmx.net (Chris Liechti) Date: Thu, 4 Dec 2003 23:23:08 +0000 (UTC) Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: "Rene Olsthoorn" wrote in news:3fcf581e$0$200$e4fe514c at news.xs4all.nl: > py2exe has a problem including libxml2. Not at building time, but at > runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has > the problem? (and can you drop me your setup.py scipt, please). i have no project using that lib, so i cant tell from experience. but did you check if the lib is copied to the dist dir? if its not copied, you may need to use the data_files option altough the dependecies for taht lib have to be tracked manually or the --packages or --force-imports option may help, if you load the xml module in advance you should probably mention which python and py2exe version you used as well as the module you import that does not work. the 0.5 version has a slightly different output than the older ones. chris -- Chris From gerrit at nl.linux.org Mon Dec 15 09:37:11 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 15 Dec 2003 15:37:11 +0100 Subject: execl difficulty In-Reply-To: References: Message-ID: <20031215143710.GA4348@nl.linux.org> Fredrik Lundh wrote: > "python newbie" wrote: > > Can anyone tell me why this would cause "Invalid Number of Parameters" while > > trying to compile (or interpret or whatever) > > > > import os > > os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Main > > Web/dp") > > > > Here's what the Python reference says: > > execl(path,arg0, arg1, ...) > (are you sure you want os.exec, btw? os.system or os.spawn* might > be a better choice...) Or shutil.copytree? Gerrit. -- 166. If a man take wives for his son, but take no wife for his minor son, and if then he die: if the sons divide the estate, they shall set aside besides his portion the money for the "purchase price" for the minor brother who had taken no wife as yet, and secure a wife for him. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From claird at lairds.com Wed Dec 10 15:21:40 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 10 Dec 2003 20:21:40 -0000 Subject: ANN: Twisted 1.1.1 References: Message-ID: In article , Jarek Zgoda wrote: . [thoroughly deserved praise for Twisted] . . >Writing one more asyncore/asynchat application pisses me off. Hate it. >Love it. Thanks God, it's Python, not Rexx, even not Java. . . . Think about that last just a bit more. Asyncore is SUCH an upgrade over what most of the world is doing. -- Cameron Laird Business: http://www.Phaseit.net From oren-py-l at hishome.net Sun Dec 14 04:10:40 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 14 Dec 2003 04:10:40 -0500 Subject: Shell quoting as part of the standard library? In-Reply-To: <99dce321.0312131439.1612dee2@posting.google.com> References: <99dce321.0312131439.1612dee2@posting.google.com> Message-ID: <20031214091040.GA16862@hishome.net> On Sat, Dec 13, 2003 at 02:39:52PM -0800, David M. Wilson wrote: > Hello fellow users! > > I've been using Python in a couple of different environments for a few > years now. I have quite often found that I have needed to deal with > filenames which may contain characters that confuse the UNIX shell > (space and double quote in particular). The best solution is often to bypass the shell (os.system) and execute the external command you want directly with os.spawnv. In this case the arguments are passed as a list of strings rather than a space-separated string and therefore need no quoting. Oren From fredrik at pythonware.com Fri Dec 5 07:41:35 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 Dec 2003 13:41:35 +0100 Subject: regexp question References: Message-ID: "python_charmer2000" wrote: > I want to match several regexps against a large body of text. What I > have so far is similar to this: > > re1 = > re2 = > re3 = > > big_re = re.compile(re1 + '|' + re2 + '|' + re3) > > matches = big_re.finditer(file_list) > for match in matches: > span = match.span() > print "matched text =", file_list[span[0]:span[1]] > print "matched re =", match.re.pattern > > Now the "match.re.pattern" is the entire regexp, big_re. But I want > to print out the portion of the big re that was matched -- was it re1? > re2? or re3? Is it possible to determine this, or do I have to make > a second pass through the collection of re's and compare them against > the "matched text" in order to determine which part of the big_re was > matched? you could put each expression inside parentheses, and use the lastindex attribute to find the subexpression: import re, string res = [ "(a+)", "(b+)", "(c+)" ] big_re = re.compile(string.join(res, "|")) matches = big_re.finditer("abba") for match in matches: span = match.span() print "matched text =", match.group() print "matched re =", res[match.lastindex-1] prints matched text = a matched re = (a+) matched text = bb matched re = (b+) matched text = a matched re = (a+) From skip at pobox.com Fri Dec 19 16:08:12 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Dec 2003 15:08:12 -0600 Subject: Simple Recursive Generator Question In-Reply-To: <92c59a2c.0312191113.569724ca@posting.google.com> References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: <16355.26812.694392.436723@montanaro.dyndns.org> jcb> This is what I have, but it does not work. jcb> def bitIndexGenerator(mask, index=0): jcb> if mask == 0: return jcb> elif mask & 0x1: yield index jcb> bitIndexGenerator(mask >> 1, index+1) Try: def bitIndexGenerator(mask, index=0): if mask == 0: return elif mask & 0x1: yield index for index in bitIndexGenerator(mask >> 1, index+1): yield index Skip From peter at engcorp.com Mon Dec 1 13:16:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Dec 2003 13:16:40 -0500 Subject: SGMLParser eats ä etc References: <87he0mn0c7.fsf@pobox.com> <19cbe1rfd2rx$.dlg@amez.homeip.net> Message-ID: <3FCB8588.F6FDB885@engcorp.com> Anders Eriksson wrote: > > On 30 Nov 2003 00:53:28 +0000, John J. Lee wrote: > > > You probably want to use HTMLParser.HTMLParser instead (NOT the same > > thing as htmllib.HTMLParser, note). It knows about XHTML, sgmllib & > > htmllib don't. > å etc isn't XHTML, is it? AFAIK it is defined in HTML 4. > > the strange thing is that the Character entity (i.e. å) is stripped > from the text. I don't want to change it since I'm feeding the output to a > browser. > > I will try the HTMLParser instead but it seems to me that there is a bug in > SMGLParser... If it's anything like the expat parser, it munches any undefined character entity references (i.e. if there's a DTD but no definitions) unless you plug in an appropriate entity reference subparser. -Peter From __peter__ at web.de Mon Dec 22 04:34:10 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Dec 2003 10:34:10 +0100 Subject: How do I really delete an imported module? References: <20031221142407.3044616b.wtrenker@shaw.ca> Message-ID: Jp Calderone wrote: > On Sun, Dec 21, 2003 at 02:24:07PM +0000, William Trenker wrote: >> I've been googling around trying to figure out how to delete an imported >> module and free up the memory it was using. One point of confusion, for >> me, is that if I "del" a module the virtual memory used by the process >> doesn't decrease. Using Python 2.3.2 on Linux, here is a simple test [...] > One important thing to realize is that "import re" does not just create > one reference to the "re" module. It also creates a reference at > sys.modules['re'], and possibly in many other places as well. Each of the > modules listed in the output above also is referenced from sys.modules, so > there is no possibility of them being garbage collected until that > reference is removed. You can use sys.getrefcount() to find out the actual number of references. >>> import sys, empty, os >>> sys.getrefcount(sys) 9 >>> sys.getrefcount(os) 6 >>> sys.getrefcount(empty) 3 Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after >>> del sys.modules["empty"] >>> del empty as the third reference is an artifact of the getrefcount() function. >> What is the pythonic way to completely delete a module and get it's >> memory garbage collected? The pythonic way is probably not to bother :-) Peter From fowlertrainer at anonym.hu Thu Dec 4 04:01:08 2003 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Thu, 4 Dec 2003 10:01:08 +0100 Subject: How to I get the exception message as string in GUI Message-ID: <905257750.20031204100108@anonym.hu> Hello , I want to get the exception error msg in string, but I don't want to save to file, or print. I want to show it in memo. How to I do it ? gd=GTMain.GameDatas s=self.Msg log="Log:\nStart loading" s.SetLabel(log) try: gd.LoadGamesDatas() log=log+"\nGame datas succesfully loaded." except: import traceback traceback.print_exc() <--------- what I must write ? log=log+"\An error occured while loading !" s.SetLabel(log) Thanx. -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From wtrenker at shaw.ca Thu Dec 18 08:29:10 2003 From: wtrenker at shaw.ca (William Trenker) Date: Thu, 18 Dec 2003 13:29:10 +0000 Subject: Spell checking and Python In-Reply-To: References: Message-ID: <20031218132910.677835c5.wtrenker@shaw.ca> Jarek Zgoda wrote: > Maybe myspell-python? > > http://www.zgoda.biz/dnld/myspell-python-1.0-minimal.tar.gz > > This is repackaged original library by Karl W. MacMillan. I finally > found a maitainer for this piece of code and I hope it will be actively > developed. Might want to apply the following patch to __init__.py so that the dictionary files are located relative to the installation directory. When I first tried running myspell-python (Linux Python 2.3.2) I got a traceback -- the dictionary path was wrong compared with where setup.py actually installed the dictionaries. After the fix, myspell-python worked very well. The list of suggested spellings for a given word is quite good. Bill --- __init__.py-original Wed Jun 11 13:41:23 2003 +++ __init__.py Thu Dec 18 13:18:24 2003 @@ -39,7 +39,7 @@ # break on other platforms. self.dicts_path = sys.prefix + "/myspell-dicts/" if sys.platform != 'win32': - self.dicts_path = "/usr/share/myspell-dicts/" + self.dicts_path = sys.prefix + "/share/myspell-dicts/" core.MySpellBase.__init__(self, self.dicts_path + "en_US.aff", self.dicts_path + "en_US.dic") From pascal.parent at free.fr Wed Dec 3 10:05:38 2003 From: pascal.parent at free.fr (Pascal) Date: 3 Dec 2003 07:05:38 -0800 Subject: Extract double in binary file References: Message-ID: Thanks a lot! From deets_noospaam at web.de Wed Dec 3 15:50:10 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 03 Dec 2003 21:50:10 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Hi, > However, I did not succeed in turning the old os.path.walk(), i. e. a > function taking a callback, into a generator. Is there a general way to do > it without having to store all intermediate results first? This works for me: import os.path def path_gen(start): res = [] def cb(r, dir, names): for n in names: r.append(n) os.path.walk(start, cb, res) for n in res: yield n g = path_gen("/etc") for n in g: print n Diez From francisgavila at yahoo.com Mon Dec 22 22:29:07 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 22:29:07 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: Fernando Perez wrote in message ... Anyway, in my code I have tons of cases where I critically need to distinguish between using a 'naked' function and calling it, and I find it always a pleasure that in python, simply using () or not allows me to, unambiguously, handle both cases. Perhaps there is an alternative which I haven't seen or understood, but I'm genuinely interested in how you'd approach this issue if the () were optional. I'm also curious about how it is handled in the Ruby world, which as I said I'm not familiar with. ### I knew nothing about Ruby until a few minutes ago. It seems that the paradigm is different: Ruby uses messages to methods (which attached to objects), and methods themselves are not first-class, so there's no ambiguity. http://onestepback.org/index.cgi/Tech/Ruby/PythonAndRuby.rdoc I can't understand the syntax in the example code that shows how you'd get a Method object. Of course, the typical Ruby accusation against Python is that it (Ruby) is "purer OO". I don't know what they mean by "purer". If they mean the fundamental types not being subclassable, that's an old wart that's very nearly gone. Otherwise, I don't know what they could possibly mean, considering absolutely everything in Python is an objects upon objects upon objects. A class is an object, the methods of an instantiated class are objects, the function a method wraps is an objects, the code of the function is an object.... I think about the only thing that is not an object in Python is a name, and I can't think how *that* would work. If by "purer", all they mean is "more like SmallTalk", well, that's just empty value judgment. ;) -- Francis Avila From google12 at mail.apol.com.tw Sun Dec 14 04:50:31 2003 From: google12 at mail.apol.com.tw (google12) Date: Sun, 14 Dec 2003 17:50:31 +0800 Subject: Is there a lib which support .jpeg file with "RGBA" mode? Message-ID: hi, May anyone help me? I need a lib which support .jpeg file with RGBA mode. PIL seems to support RGB and CMYK mode only... Thanks for your help. From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 10 17:08:27 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 10 Dec 2003 23:08:27 +0100 Subject: offtopic: asyncore tutorial (was: Re: ANN: Twisted 1.1.1) In-Reply-To: References: <8765gowgp7.fsf@mobile.foo> <3fd788bd$0$204$e4fe514c@news.xs4all.nl> Message-ID: <3fd7995b$0$208$e4fe514c@news.xs4all.nl> Jarek Zgoda wrote: > Frederik Lundh has excellent chapter on network protocols with many > examples for asynchronous servers and clients in his "Python Standard > Library" book, available online at > http://effbot.org/zone/librarybook-index.htm Thanks for the link, I'll go and read it! And kudos to Fredrik for putting this stuff online. --Irmen. From mike at nospam.com Thu Dec 4 11:40:25 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 4 Dec 2003 08:40:25 -0800 Subject: Python Embedding in C++ References: Message-ID: Message"Raphael Drai" wrote: >Does it is possible to have a Python embedded C++ sample that invokes a Python method by http://www.boost.org/libs/python/doc/tutorial/doc/embedding.html migth help. Mike From nathan at visi.com Fri Dec 26 11:50:57 2003 From: nathan at visi.com (Nathan Mates) Date: 26 Dec 2003 16:50:57 GMT Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: <3fec66f1$0$967$a1866201@newsreader.visi.com> In article , Brandon J. Van Every wrote: >But this discussion would only (properly) be about the appropriateness of >various languages for prototyping Game Designs. I say Python is >appropriate, and C isn't. Prototyping != implementing. Nathan Mates -- <*> Nathan Mates - personal webpage http://www.visi.com/~nathan/ # Programmer at Pandemic Studios -- http://www.pandemicstudios.com/ # NOT speaking for Pandemic Studios. "Care not what the neighbors # think. What are the facts, and to how many decimal places?" -R.A. Heinlein From h.goebel at crazy-compilers.com Sat Dec 20 07:22:33 2003 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Sat, 20 Dec 2003 13:22:33 +0100 Subject: How to use a 5 or 6 bit integer in Python? In-Reply-To: References: <3FE2FB4C.5020909@users.ch> Message-ID: <3FE43F09.10307@crazy-compilers.com> Hi, Glen Wheeler wrote: > Component ints will either be 0-63 or 0-31. In a single run of the > program, this will not change throughout. > The key tuples range in length from 1-64, depending on at what stage > the program is currently at. Every tuple will have the same length at > some point; the greatest possible distance in length from any two > tuples is 1. I'm afraid, I'll mix up some of your data-structure, but here are my thoughts: - pack the key-tuples into a string using pack; you may even pack 4 intergers into one byte since the values range from 1-64 (which is equivalent to 0-63). - if you need easy access to eg. the last emlement of the tuple, keep it seperate. Eg: key = ('xdef', 12) - As far as I remeber, you wrote something about max. 64 entries. What about using an array/list here? Array may need a lot less memory (depending on the muber of elements of course). Only my 2 cents. -- Regards Hartmut Goebel | Hartmut Goebel | We build the crazy compilers | | h.goebel at crazy-compilers.com | Compiler Manufacturer | From http Thu Dec 11 16:44:48 2003 From: http (Paul Rubin) Date: 11 Dec 2003 13:44:48 -0800 Subject: What GUI toolkit looks the best? References: Message-ID: <7xllpj81wv.fsf@ruckus.brouhaha.com> "John Benson" writes: > I've seen some pretty knockout, artistic GUIs in John Grayson's "Python and > Tkinter Programming" book; you just have to look in the second half of the > book for artsy and ray-traced interfaces. I'm not at all concerned about artsy or ray-traced interfaces. I need UI widgets that are responsive and look crisp and act like the native widgets for the underlying OS. From luc.saffre at gmx.net Mon Dec 15 10:07:51 2003 From: luc.saffre at gmx.net (Luc Saffre) Date: Mon, 15 Dec 2003 17:07:51 +0200 Subject: "Bad file descriptor" after py2exe or Installer In-Reply-To: References: <3FD8B25A.7080103@gmx.net> <3FD97E83.2000703@gmx.net> Message-ID: <3FDDCE47.2000708@gmx.net> On 12.12.2003 15:41, Thomas Heller wrote: > py2exe seems to pick up cygwin binaries. The reason could be that > either you have cygwin extensions somewhere in your pythonpath, or parts > of the PATH env variable points into the cygwin directories, or > something like that. You should look at the output above carefully, and > make sure that it is what one would expect. That's it! Thank you, Thomas, your hint helped. I had the Cygwin tcltk package installed. After removing this package (using cygwin's setup.exe), I can use again the original PIL/Image.py and everything works fine. My PATH contains the cygwin bin directories: PATH=u:\CYGWIN\BIN; c:\python23\Scripts;c:\python23; ... u:\CYGWIN\USR\BIN;u:\CYGWIN\USR\LOCAL\BIN;... Another workaround is to remove the cygwin directories from PATH: I reinstalled the cygwin tcltk and the problem reappeared, moving the first cygwin directory to come after the python directory did not help. Then I removed those directories completely from PATH (during the build) and the problem disappeared again. I would consider this as a bug (in both py2exe and Installer) since they decide to pick some cygwin tcl/tk dll's who happen to hang around while the Python runtime won't... Luc From duncan at NOSPAMrcp.co.uk Thu Dec 4 10:50:45 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 4 Dec 2003 15:50:45 +0000 (UTC) Subject: Simple newbie question References: Message-ID: Angelo Secchi wrote in news:mailman.107.1070547952.16879.python-list at python.org: > The code i'm using is the following: > > for line in lista: > if sum(line == 0) > 0: > lista.remove(line) > > > The problem is that the loop stops at the first line with zeros and it > doesn't remove the other lines with zeros (at least if I do not re-run > the loop). Probably I do not understand how the loop works. The loop will assign the first element of lista to line, then the second, then the third, and so on. The problem is that, if you remove an element everything after it shifts up one place. Say you are looking at the first element and remove it, what was the second element now becomes the first element, but the next time round the loop you will look at the new second element and the one that was originally second (and is now first) will be skipped. The solution is never to work on the list you are modifying. Just make a copy of the list and iterate over the copy, that means you can safely modify the original. To copy a list, use the 'list' builtin. for line in list(lista): if condition: lista.remove(line) Alternatively turn your brain around and instead of deleting specific elements from the list just build a new list with the elements you want to keep. In this case you could do that using a list comprehension: lista = [ line for line in lista if not condition ] (Obviously in both these cases replace condition with the correct expression, which as Gerhard pointed out may not be the condition in your original posting.) The list comprehension rebinds the lista variable, whereas your original attempt was modifying the list inplace. This might be significant if there are other references to the same list elsewhere in your code. If it does matter, then you can still use a list comprehension to mutate the original list: lista[:] = [ line for line in lista if not condition ] Unlike the original 'for' loop, this works by building a complete replacement list then mutating the original list in one go. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From a.schmolck at gmx.net Tue Dec 30 21:27:16 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 31 Dec 2003 02:27:16 +0000 Subject: selecting a random item from a set References: <7xsmj1dgox.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Alexander Schmolck writes: > > for dummy, randomElement in zip(range(randrange(len(s)+1)), s): pass > > # possibly followed by > > s.remove(randomElement) > > > > Is there a better way? If not, how about something like Set.randompop()? > > The classic way to do it goes something like this: > > for n, randomElement in enumerate(s): > if random() < (1.0 / (n+1)): > e = randomElement > # possibly followed by > s.remove(randomElement) > > Note that you don't need to know the size of the set in advance. Nice algorithm, but maybe *only* if you don't know the size in advance (have constant time len) -- as far as I can see it does more than twice the work of my original solution. 'as From eugine_kosenko at ukr.net Tue Dec 9 17:11:31 2003 From: eugine_kosenko at ukr.net (=?windows-1251?b?xeLj5e3o6SDK7vHl7eru?=) Date: Wed, 10 Dec 2003 00:11:31 +0200 Subject: What are the errors in a simpliest Tix application? Message-ID: <200312100011.31777.eugine_kosenko@ukr.net> Hi! I make my first steps in Tkinter/Tix programming. The next program is work well (really, _almost_ well): import Tkinter root = Tkinter.Tk() widget = Tkinter.Button(root) Really, this is not an application, it is only the minimal non-problematic piece of application code. As the Python Library manual says, the only thing I need to use Tix is to replace Tkinter in the last program to Tk: import Tix root = Tix.Tk() widget = Tix.Button(root) However, I have got the next exception tracelist: Traceback (most recent call last): File "tix.py", line 4, in ? widget = Tix.Button(root) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1906, in __init__ Widget.__init__(self, master, 'button', cnf, kw) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1835, in __init__ self.tk.call( _tkinter.TclError: expected integer but got "-" I'm sure that the Tix platform -- I saw demos succesfully. It seems like an error inside the Tix package. Maybe, something wrong in my code pattern, but I may not understand, where is my mistake. Who can help me? When I use an integer parameter in the program: widget = Tix.Button(root, 10) the exception tracelist is different: Traceback (most recent call last): File "tix.py", line 4, in ? widget = Tix.Button(root, 10) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1906, in __init__ Widget.__init__(self, master, 'button', cnf, kw) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1829, in __init__ BaseWidget._setup(self, master, cnf) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1809, in _setup if cnf.has_key('name'): AttributeError: 'int' object has no attribute 'has_key' Originally, I need the ComboBox widget from Tix, and for it I got the next tracelist: Traceback (most recent call last): File "tix.py", line 4, in ? widget = Tix.ComboBox(root, 10) File "/usr/lib/python2.3/lib-tk/Tix.py", line 576, in __init__ cnf, kw) File "/usr/lib/python2.3/lib-tk/Tix.py", line 284, in __init__ cnf = _cnfmerge(cnf) File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 85, in _cnfmerge for c in _flatten(cnfs): TypeError: len() of unsized object From claird at lairds.com Thu Dec 11 09:17:06 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 14:17:06 -0000 Subject: OT: Peter Hansen needs to use some humility (was Re: Python&Expect) References: <3FD876B8.74E1ABE1@engcorp.com> Message-ID: In article <3FD876B8.74E1ABE1 at engcorp.com>, Peter Hansen wrote: >Fredrik Lundh wrote: >> >> Cameron Laird wrote: >> >> > Long term, the latter might be a greater benefit. I know how >> > much it means to me when someone helps me learn how to use >> > resources better. >> >> who has time to learn? wasn't the internet supposed to >> eliminate all that? > >http://www.google.com/search?q=how+to+use+resources+better > >;-) , back at you. -- Cameron Laird Business: http://www.Phaseit.net From mwood at stpo.com Sat Dec 6 17:52:59 2003 From: mwood at stpo.com (Michael Wood) Date: Sat, 06 Dec 2003 14:52:59 -0800 Subject: Accessing Python script with ColdFusion Message-ID: <6.0.0.22.2.20031206145251.052fc5c8@mail.stpo.com> We're using mailman (python based) to do mailing lists. I'd like to write a ColdFusion interface to the command line scripts for managing list membership but there's a problem. I can run the scripts from the Linux command line with no problem. But when I run the scripts via the CFExecute tag in ColdFusion there isn't any output returned. That isn't entirely true, if I use the -h argument the help screen displays okay but any other sort of output never turns up. And it doesn't return an error so it seems as though the script is executing or starts to execute but the output buffer never flushes to the standard output or something like that... I'd really like to make this work. Does anyone have any ideas on how to do so? Michael Wood From miki.tebeka at zoran.com Tue Dec 23 05:01:34 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 23 Dec 2003 02:01:34 -0800 Subject: Flat file database References: Message-ID: <4f0a9fdb.0312230201.2dd9f8fd@posting.google.com> Hello Art, > Is there any Python module designed to simplify the use of a plain text file > as a flat file database? You might want to take a loot at metakit (http://www.equi4.com/metakit/python.html) HTH. Miki From deets_noospaam at web.de Tue Dec 9 10:06:40 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 16:06:40 +0100 Subject: parsing equations References: Message-ID: > Be aware that this is powerful: > >>>> eval("cleanMyHarddisk()") > 'done' > > Just to make sure the OP is aware of the inherent danger of the > unsuspecting "arbitrary python expression"... Yup - should have mentioned that. Diez From niemeyer at conectiva.com Sat Dec 13 01:05:39 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 13 Dec 2003 04:05:39 -0200 Subject: ANN: lunatic-python 0.1 Message-ID: <20031213060539.GA6538@burma.localdomain> What is it? ----------- Lunatic Python is a two-way bridge between Python and Lua, allowing these languages to intercommunicate. Being two-way means that it allows Lua inside Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua inside Python, and so on. Where to get it? ---------------- Documentation, examples, and downloads are available at: https://moin.conectiva.com.br/LunaticPython -- Gustavo Niemeyer http://niemeyer.net From kylotan at hotmail.com Fri Dec 26 20:52:32 2003 From: kylotan at hotmail.com (Kylotan) Date: 26 Dec 2003 17:52:32 -0800 Subject: Building Py2Exe from source Message-ID: <153fa67.0312261752.44f3e977@posting.google.com> I need to be able to build Py2Exe from the source code as I am making a Windows executable where I wish to preprocess the modules before importing them.It looks like I can do this by adding lines to Load_Module() in py2exe's start.c. However problem I have is that I can't build Py2Exe using the instructions provided. Using the designated command of "python setup.py install" I get this error: Traceback (most recent call last): File "setup.py", line 340, in ? raise RuntimeError, msg RuntimeError: PYWIN32DIR invalid. To build py2exe from source, you must either: - Download and build Mark Hammond's pywin32 source code from http://starship.python.net/crew/mhammond, and set the PYWIN32DIR variable to point to this directory - or change this setup script to not build run_svc target, then you will not be able to build Windows NT services with py2exe. The main problem I encountered is that the 2nd option appears misleading: removing run_svc from the list of targets does no good as it still attempts to find some sort of "win32" directory before it even gets that far. Or maybe I'm missing something. If option 1 requires following these arduous-looking instructions: then I'd rather bypass that if at all possible. :) I only need to build standard executables, not DLLs, NT services, or anything to do with COM. Any help getting around this problem would be much appreciated. (Platform: Win98SE, Python 2.3.3.) -- Ben Sizer From martin at v.loewis.de Mon Dec 15 09:48:04 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Dec 2003 15:48:04 +0100 Subject: codecs latin1 unicode standard output file References: Message-ID: "Marko Faldix" writes: > print "My umlauts are ?, ?, ?" > > without any encoding-assignment to use for standard output on console AND > redirecting to file. In latter case, it looks nice with e.g. notepad, just > strange on console, so settings for console are to adjust and not python > code. Right? Wrong. On your operating system, notepad.exe and the console use *different* encodings. If you think this is stupid, please complain to Microsoft. If you print byte strings, it will come out wrong either in the terminal, or in notepad - there is *no way* to have the same byte string show correctly in both encodings. If you want to output to a file, you should open the file in locale.getpreferredencoding(). If you want to output to a terminal, Python should automatically find out what the terminal's encoding is (to make things worse, the user can override the terminal encoding on Windows, on a per-terminal basis, using chcp.exe). Regards, Martin From allenabethea at aol.com Wed Dec 10 18:20:52 2003 From: allenabethea at aol.com (Allenabethea) Date: 10 Dec 2003 23:20:52 GMT Subject: Upgrage openoffice to 2.3.3? Message-ID: <20031210182052.26181.00000472@mb-m15.aol.com> Is there any advantage to upgrading the python distribution which is part of OpenOffice to 2.3.3? I notice it is version 2.2.2 Are the bug fixes crucial? allen From fredrik at pythonware.com Tue Dec 9 02:35:29 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 08:35:29 +0100 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> <20031208190240.5ff11e93.johnlr@despammed.com> Message-ID: Greg Ewing wrote: > > Hmmm..Sep 31? Should I file a bug report? ;o) > > You're failing to take into account the (highly controversial) > International Calendar Reform of 2006, which gave all months > the same number of days. Python was, of course, the first > language to have its datetime module updated to conform with > the new standard. > > (Microsoft Java++#.NET was updated too, but in a subtly > incompatible way -- all their months were given 30 > days instead.) it's well known (at least to insiders) that the bug in MSJPCS.NET was the reason for the reform. a "32 days is better for computers" alternative was brought forward by the usual suspects (IBM, Sun, etc, plus a bunch of bloggers hellbent on teaching Dave Winer a lesson), but was, as usual, largely ignored by everyone else. 31 might be due to a EU translation error, but I'm not sure. I also hear that the french edition of the standard uses 13 days. From fredrik at pythonware.com Sun Dec 14 18:18:32 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Dec 2003 00:18:32 +0100 Subject: execl difficulty References: Message-ID: "python newbie" wrote: > Can anyone tell me why this would cause "Invalid Number of Parameters" while > trying to compile (or interpret or whatever) > > import os > os.execl("C:/WINDOWS/system32/xcopy.exe","E:/MainWeb/dreampics/*.*","E:/Main > Web/dp") > > Here's what the Python reference says: > execl(path,arg0, arg1, ...) first, fix the slashes. xcopy wants backward slashes in the filenames, not forward slashes. next, fix the number of arguments. at the top of the reference page you refer to, there's a paragraph explaining how the exec arguments work: The various exec*() functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program's main(). For example, "os.execv('/bin/echo', ['foo', 'bar'])" will only print "bar" on standard output; "foo" will seem to be ignored. (from http://www.python.org/doc/current/lib/os-process.html ) in other words, you need to pass in the program name twice, to make sure xcopy sees the filenames as argument 1 and 2. (are you sure you want os.exec, btw? os.system or os.spawn* might be a better choice...) From edreamleo at charter.net Fri Dec 12 15:10:33 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 12 Dec 2003 14:10:33 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: > if not FUD, it was inaccurate in the _general sense_ > as many applications are built upon wxWindows/wxPython and do not have > problems. Yeah, as I think about this more, I am tending to agree with you. Perhaps I was just being too grumpy or pessimistic. I owe the wxWindows people an apology. Consider it given. For sure wxPython is pretty easy to use. Looking back, I was letting earlier trauma color my thinking too much. Also, the wxSTC control might well solve the problems with the plain wxText control... Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tismer at tismer.com Thu Dec 11 13:41:06 2003 From: tismer at tismer.com (Christian Tismer) Date: Thu, 11 Dec 2003 19:41:06 +0100 Subject: [Zope-dev] Preview of a Stackless Zope Application In-Reply-To: <1071162154.3711.5.camel@localhost> References: <3FD7E99D.70108@tismer.com> <1071162154.3711.5.camel@localhost> Message-ID: <3FD8BA42.1030901@tismer.com> Leonardo Rochael Almeida wrote: > On Thu, 2003-12-11 at 01:50, Christian Tismer wrote: [Stackless Zope App] >>The key to this surprizing solution is >>tasklets, channels, and thread pickling. >> >>Let me know your thoughts... >> >>http://www.centera.de/tismer/stackless/zope_demo > > > This is very impressive. Can we get the rest of the source code? like, > what is the definition of "channel_send()"? Well, this is all still a little ugly, and I didn't want to spoil the nice effect by such details. Actually, there are restrictions on what I can use from Stackless, since I'm writing in Restricted python. Without further additions to Stackless (which I din't understand, yet), Zope doesn't allow me to call methods on tasklets and channels, so I had to put things into external methods, which do these calls for me. channel_send(ch, data) is just a wrapper and actually does ch.send(data) same here: stackless_tasklet(prog) is a wrapper that calls stackless.tasklet(prog) since I cannot import my module. Furthermore, these channels are not the builtin Stackless channels, but a fake Python class, which implements channels in Python. The reason was that Stackless channels don't have pickling support, yet. Also a reason why I call this a "preview". Anyway, it works and is not cheating. You might be interested in the "driver" code, which is a Python script as well (the "other side" that reads form the channel): runDemo script: """ # Example code: # Import a standard function, and get the HTML request and response objects. from Products.PythonScripts.standard import html_quote request = container.REQUEST RESPONSE = request.RESPONSE # see whether we have a channel stored in the session chname ='demo_channel' session = request.SESSION if not session.has_key(chname): ch = container.stackless_channel() t = container.stackless_tasklet(container.program) t(ch) # bind parameter del t session[chname] = ch ch = session[chname] data = container.channel_receive(ch) last = 0 if data is None: del session[chname] last = 1 return container.index_html(value=data, show_source=last) """ I will put some more work into this if I get more feedback, and add more infos to the website. An interesting version would be to not use the session at all, but send the pickle together with the web page. That means to pickle by hand and to use encryption of course. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From aahz at pythoncraft.com Sat Dec 20 00:22:30 2003 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2003 00:22:30 -0500 Subject: semi-OT: DNS issues for python.org References: Message-ID: In article , Ben McGinnes wrote: > >Yalumba believes python.org's nameservers are ns53.worldnic.com & >ns54.worldnic.com. While tracking back from UltraDNS points to >ns.xs4all.nl & ns2.xs4all.nl. > >So does anyone know if there are currently any registration or >delegation issues with python.org or if they are seeing similar things >elsewhere? Yalumba is wrong. python.org has just been transferred, and xs4all is now correct. Tell Yalumba to do a DNS reload and everything will be fine. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From sillyman71 at hotmail.com Thu Dec 11 18:57:43 2003 From: sillyman71 at hotmail.com (Scott Silliman) Date: 11 Dec 2003 15:57:43 -0800 Subject: ImportError on _socketmodule.so when running a frozen program Message-ID: <1c03f108.0312111557.7a183f4@posting.google.com> I'm getting the following when I run my executable: File "/usr/lib/python2.2/socket.py", line 41, in ? from _socket import * ImportError: /usr/lib/python2.2/lib-dynload/_socketmodule.so: undefined symbol: PyInt_FromLong However, if I run 'nm' on the executable, I get the following output: 0807cf90 T PyInt_FromLong doesn't this mean that PyInt_FromLong() is staticly linked into the executable (got it when it staticly linked in /usr/lib/python2.2/config/libpython2.2.a )? Any ideas as to why it doesn't think this symbol is defined? -Scott From tjreedy at udel.edu Fri Dec 26 00:25:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Dec 2003 00:25:23 -0500 Subject: How does "delegation" work as per the FAQ? References: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> Message-ID: <3vOdnQ54rKreW3ai4p2dnA@comcast.com> "Rene Pijlman" wrote in message news:10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3 at 4ax.com... > Ville Vainio: > >Rene Pijlman: > >> __getattr__: "Called when an attribute lookup has not found the attribute > >> in the usual places". There is no mention of method calls. > > > >A method is an attribute. > > I see. But how are the arguments of a method call passed on, when > delegation is implemented this way? The delegation is done before the call, in order to find the (delegated-to method) object on which to make the call. The alternative is to write a wrapper method for each method delegated to and explicitly pass the args on with *args and ** args. But doing the delegation before the call in the method lookup make this not necessary and is much easier. Terry J. Reedy From kamuelaf at verizon.net Thu Dec 25 05:46:02 2003 From: kamuelaf at verizon.net (Kamuela Franco) Date: Thu, 25 Dec 2003 10:46:02 GMT Subject: Socket Programming Message-ID: Can someone give me some general information on socket programming in Python. trainee From michele.simionato at poste.it Tue Dec 9 14:19:22 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 9 Dec 2003 11:19:22 -0800 Subject: Understanding and working with __metaclass__ References: <99dce321.0312081149.2a32575d@posting.google.com> Message-ID: <95aa1afa.0312091119.13eab640@posting.google.com> dw-google.com at botanicus.net (David M. Wilson) wrote in message news:<99dce321.0312081149.2a32575d at posting.google.com>... > Hi there, > > I've been sitting on the __metaclass__ feature for about 2 weeks now, > and haven't really got that far with it. It looks like a very powerful > tool, and I think I have even already identified places in my code > where I could use it quite effectively, but I can't quite tell what it > is /meant/ to be used for, or indeed what it is popularly used for. > > Is there a page, posting, or other place I can turn to to get a > developer's run-down on the practical uses of __metaclass__? The > Python documentation states very clearly what it does, but I fear that > journeying off on my own with it will lead to some terrible habit > formation, and I already have enough of those to deal with. :) (:set > ts=3 ;) > > Thanks for your time, > > > David. Uhm ... this question has been asked here many times and I am beginning to think it should be in the FAQ. Any volunteer for a tentative FAQ entry? I must say that I don't have a precise opinion on the subject yet, since in most cases you can avoid metaclasses without loosing any essential functionality. Metaclasses are somewhat elegant, but you pay the elegance with impliciteness and we all know that "esplicit is better than implicit". A typical use case for metaclasses is when you have a hierarchy written to do X, and you want it to do Y. Instead of rewriting all the classes, a quick and dirty metaclass can give you the desired functionality with a little effort. Also, you can use metaclasses to debug classes. Metaclasses allow to implement Aspect Oriented Programming for Python, and there are already modules doing that. With metaclasses you can modify the semantics of the language. For instance, you could design a declarative language on top of Python. Nevertheless, IMO these tricks don't fit well with the spirit of the language, so even if you can do that, I am not convinced you should do that. A reasonable application of metaclasses is in the writing of plugins: you may import at runtime the same module but with different metaclasses, changing its behaviour according to the external conditions. See for instance http://www-106.ibm.com/developerworks/library/l-pymeta.html for more on this idea. Google for "Guido metaclasses a.k.a. the killer joke" for additional motivations. The standard distributions contains various examples of metaclasses. My advice: use a lot of metaclasses for experimental purposes and playing, very little (better zero) for production code. The fact that you can correct your design mistakes with metaclasses does not mean that you should not correct them by rewriting you classes from scratch ;) Michele From imbosol at aerojockey.invalid Sat Dec 20 01:35:06 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 06:35:06 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> <7xekv0b0cf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Carl Banks writes: >> The only thing is, I very much doubt I'd be willing to take the >> performance hit for it. > > If you don't like performance hits, you're using the wrong language :). > > Seriously, this hasn't been an issue in Common Lisp, which in general > pays far more attention to performance issues than Python ever has. Well, if you're right, I'm all for it. But I hope the reason you want this is because it's less surprising, more intuitive, more useful, or whatnot, and not just because Common Lisp did it that way. Because people who can't see the side of any computer programming argument except in the context of Common Lisp are just pathetic. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From grey at despair.dmiyu.org Sat Dec 20 16:21:28 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 20 Dec 2003 21:21:28 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On 2003-12-20, Roy Smith wrote: > Ville Vainio wrote: >> If the extra features [...] were really >> worthwhile, they would be added to Python > Down that path lies madness (i.e. Perl). Nono, that's not the quote! YODA: Code! Yes. A programmer's strength flows from code maintainability. But beware of Perl. Terse syntax... more than one way to do it...default variables. The dark side of code maintainability are they. Easily they flow, quick to join you when code you write. If once you start down the dark path, forever will it dominate your destiny, consume you it will. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From jjl at pobox.com Thu Dec 11 10:44:07 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 15:44:07 +0000 Subject: Pyrex problem - Py_NoneStruct References: <878ylkydx9.fsf@pobox.com> Message-ID: <8765gnmkag.fsf@pobox.com> "Gary Stephenson" writes: [...] > > Try posting some Pyrex code (the pyrex list is probably a better place > > than here). > > I have attempted to post this message along with the .pyx file to the pyrex > list, but it would appear there is something wrong with my subscription as > I have received neither my own message not anybody else's since subscribing > :-( [...] Your message appeared on the list: http://lists.copyleft.no/pipermail/pyrex/2003-December/thread.html John From theller at python.net Fri Dec 12 08:41:10 2003 From: theller at python.net (Thomas Heller) Date: Fri, 12 Dec 2003 14:41:10 +0100 Subject: "Bad file descriptor" after py2exe or Installer References: <3FD8B25A.7080103@gmx.net> <3FD97E83.2000703@gmx.net> Message-ID: Luc Saffre writes: > On 11/12/2003 23:11, Thomas Heller wrote: > > It seems I cannot reproduce this with py2exe 0.5. > > Can you? > > Yes: I use py2exe 0.5.0a5. > > Here is in more detailed, how I reproduce the problem: > > I used the following installers: > Python-2.3.3c1.exe > PIL-1.1.4.win32-py2.3.exe > py2exe-0.5.0a5.win32-py2.3.exe > I installed these three to a clean installation (except for my windows > registry where I don't know how to verify cleaness) > > I place the test.py as described into a separate directory, together > with a file setup.py: > > from distutils.core import setup > import py2exe > setup( console=["test.py"] ) > > and then I type "setup py2exe" at the command line. > Here is the output of that command: [...] > *** copy extensions *** > copying C:\PYTHON23\DLLs\_sre.pyd -> > T:\data\luc\release\lino\tests\py2exe\dist > copying C:\PYTHON23\lib\site-packages\PIL\_imaging.pyd -> > T:\data\luc\release\lino\tests\py2exe\dist > copying C:\PYTHON23\DLLs\_tkinter.pyd -> > T:\data\luc\release\lino\tests\py2exe\dist > copying C:\PYTHON23\lib\site-packages\PIL\_imagingtk.pyd -> > T:\data\luc\release\lino\tests\py2exe\dist > *** copy dlls *** I guess the problem is here: > copying u:\CYGWIN\BIN\cygwin1.dll -> > T:\data\luc\release\lino\tests\py2exe\dist > copying u:\CYGWIN\BIN\tk84.dll -> T:\data\luc\release\lino\tests\py2exe\dist > copying C:\WINNT\System32\python23.dll -> > T:\data\luc\release\lino\tests\py2exe\dist > copying C:\PYTHON23\DLLs\tcl84.dll -> > T:\data\luc\release\lino\tests\py2exe\dist > copying u:\CYGWIN\BIN\tcl84.dll -> > T:\data\luc\release\lino\tests\py2exe\dist > copying C:\PYTHON23\lib\site-packages\py2exe\run.exe -> > T:\data\luc\release\lino\tests\py2exe\dist\test.exe > copying C:\PYTHON23\lib\site-packages\py2exe\run_w.exe -> > T:\data\luc\release\lino\tests\py2exe\dist\tkhello.exe py2exe seems to pick up cygwin binaries. The reason could be that either you have cygwin extensions somewhere in your pythonpath, or parts of the PATH env variable points into the cygwin directories, or something like that. You should look at the output above carefully, and make sure that it is what one would expect. HTH, Thomas From alanmk at hotmail.com Fri Dec 5 05:49:43 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 05 Dec 2003 10:49:43 +0000 Subject: xml.dom.minidom -> nextElement ? References: <3fcfdfdf$1_2@news.bluewin.ch> Message-ID: <3FD062C7.D79ADB74@hotmail.com> [Alexandre] > Could someone explain to me why there is no nextElement in minidom ? > > if i execute this : > *************************************** > import xml.dom.minidom > doc = """\ > > content1 > content2 > """ > dom = xml.dom.minidom.parseString(doc) > firstItem = dom.getElementsByTagName("item")[0] > nextItem = firstItem.nextSibling > print nextItem > *************************************** > the result is : > "> You're possibly being confused by the fact that the element has *5* children, not 2. There are the 2 obvious children, s 1 and 2. However, the whitespace o between and o between and o between and also create text nodes, which only contain whitespace. Note also that the nextSibling of the first is *not* the second , it is the whitespace text node in between them. Which explains the result printed by your code. > so if i want the next element i could use "firstItem.nextSibling.nextSibling" > > or write my own nextElement : > *************************************** > def nextElement(current): > pointer = current.nextSibling > if pointer.nodeType == pointer.ELEMENT_NODE: > return pointer > elif pointer == None: > return None > else: return getNextElement(pointer) > *************************************** Well, you could 1. Navigate over your tree deleting whitespace nodes, before doing your processing. 2. Write your own nav function which skips whitespace text nodes (as you have done above). 3. Use Xpath to find nodes in trees. > But i'm wondering if i am not missing something obvious ? > Thx in advance for your help. HTH, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From bokr at oz.net Tue Dec 2 14:08:45 2003 From: bokr at oz.net (Bengt Richter) Date: 2 Dec 2003 19:08:45 GMT Subject: Shared Memory Modules References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> <3fcbd6b8$1@nntp0.pdx.net> <3fcbd24f$0$1502$e4fe514c@news.xs4all.nl> <3fcc5a0b$0$1491$e4fe514c@news.xs4all.nl> <8ylv1r5g.fsf@python.net> Message-ID: On Tue, 02 Dec 2003 10:54:19 +0100, Thomas Heller wrote: >Irmen de Jong writes: > >> Bengt Richter wrote: >>> What's that first zero argument? >> [...] >>> Does that mean you are trying to use stdin as the open file handle? >> >> No it doesn't, according to Thomas Heller's post in this thread. >> Thomas said 0 means "not associated with a file" on windows... > >mmapmodule.c internally uses INVALID_HANDLE_VALUE of a file handle of 0 >is used. Wouldn't passing None be more pythonic for a python interface? > >As I said, read the source (and MSDN). And then submit a documentation >patch . > How does one do that? (being lazy, I guess I could find out via www.python.org) Regards, Bengt Richter From tomas.bouda at systinet.com Wed Dec 3 12:53:38 2003 From: tomas.bouda at systinet.com (tomas.bouda at systinet.com) Date: Wed, 03 Dec 2003 18:53:38 +0100 Subject: Python mem leaks? In-Reply-To: <200312031415.hB3EFjdt019818@se-126.se.wtb.tue.nl> References: <200312031415.hB3EFjdt019818@se-126.se.wtb.tue.nl> Message-ID: <20031203175338.11300.qmail@mailcz.in.systinet.com> Hi, you're right, my objects were held in Python backtrace. That was what I thought but I was a bit confused 'cause PyErr_Clear() didn't clear the backtrace, just set the exception flag. Now, I'm calling { PyErr_SetNone(PyExc_Exception); PyErr_Clear(); } which clears memory. Probably a hack but works fine. Thanks a lot for your help. Best Regards, Tobbi A.T.Hofkamp writes: > In comp.lang.python, you wrote: >> >> def do_smth2(panel): >> raise Exception() >> >> Calling do_smth1() will cause returning of Py_None, the PyCObject is >> freed and the C finalizer (mentioned in no.2) is called. >> Calling do_smth2() will case returning NULL a is not freed nor >> finalizer is called. At this point I get a leak! > > What happens if you handle the exception? > > My guess is that in the stack backtrace, there is a reference to panel. > Since handling the exception may mean printing the stack, Python still > needs the object. > If you handle the exception, I would expect Python to release the stack > trace information, and thus the object. > > > Albert > -- > Unlike popular belief, the .doc format is not an open publically available format. > From Spam_Sucks at rr.com Wed Dec 10 15:39:07 2003 From: Spam_Sucks at rr.com (Luther Barnum) Date: Wed, 10 Dec 2003 20:39:07 GMT Subject: Python & Expect References: <3FD7263E.110F9CC4@engcorp.com> Message-ID: Instead of being the newsgroup cop, maybe you should use a little humility and actually read the post. It's guys like you that scare newbies from newsgroups. I'll bet you didn't know everything when you posted your last question. Luther "Peter Hansen" wrote in message news:3FD7263E.110F9CC4 at engcorp.com... > Jeff Wagner wrote: > > > > Is there an Expect-like module for Python that is cross platform and, for the most part, does what > > Expect does? A number of years ago, I wrote some Tcl scripts using Expect for automation. I am > > trying to convince my good friend who I worked with at the time to try Python. He said, "what about > > Expect?" > > > > I have heard of a Pexpect but was told that it didn't run on win32 and he needs win32 and Linux > > support both. > > Hmmm... let's see what Google brings up... (typing) > > http://www.google.com/search?q=python+expect > > Wow! Look at that! Pexpect is the first hit. Let's try accessing that > page and see what it says. (click) Ah, there's a "Requirements" link: (click) > > -------------------------------------------- > Python > Pexpect was written and tested with Python 2.1. It should work on earlier versions > that have the pty module. ... > > pty module > Any POSIX system (UNIX) with a working pty module should be able to run Pexpect. > The pty module is part of the Standard Python Library, so if you are running on > a POSIX system you should have it. The pty module does not run as well on all platforms. > I have taken effort to try to smooth the wrinkles out the different platforms. To > learn more about the wrinkles see Bugs and Testing. > > Pexpect does not currently work on the standard Windows Python(see the pty requirement); > however, it seems to work fine using Cygwin. ... > > -------------------------------------------- > > Okay, Jeff, consider your wrist slapped for not even trying... :-) > > -Peter > From missive at frontiernet.net Mon Dec 22 16:09:17 2003 From: missive at frontiernet.net (Lee Harr) Date: Mon, 22 Dec 2003 21:09:17 GMT Subject: Some pygame issues References: Message-ID: On 2003-12-22, Ryan Spencer wrote: > Hello everyone, > > I recently started up with pygame and after some general playing around > in it, I started writing a small pong game within it. It's practically > functional; it loads up a 640x480 window, plays some music, allows the > user to move his paddle up or down, and has a moving dot. Although, here's > the issue I've come to find. I wanted to get the dot simply moving back > and forth on the x-axis - once it collides with x position of the right or > left paddle, it reverses it's direction. Although, with the current setup, > it moves, hit's the right paddle, and simply gets locked at that position. > I use absolute value to make sure the ball goes the right way. http://staff.easthighschool.net/lee/computers/book/chapter04/ From bokr at oz.net Mon Dec 1 17:10:05 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Dec 2003 22:10:05 GMT Subject: notes on compilation Python with MinGW gcc References: Message-ID: On Mon, 1 Dec 2003 21:33:47 +0100, "Ames Andreas (MPA/DF)" wrote: >Hi Oleg, > >usenet at xmlhack.ru (Oleg A. Paraschenko) writes: > >> recently I compiled Python with MinGW gcc under Windows. >> If there are some interest, you can look at log of process at >>=20 >> http://uucode.com/texts/python-mingw/python-mingw.html >>=20 >> In short, about compiling with MinGW gcc: >>=20 >> * it is possible; >> * result works; >> * you must not do it unless you know for sure that you must do it; >> * you must have a good knowledge of C and of debugging; >> * in most cases all you need is to compile an extension module. > >I've recently taken a slitely different way to accomplish a native >mingw32 build. You can get a patch from > >https://sourceforge.net/tracker/?func=3Ddetail&aid=3D841454&group_id=3D54= >70&at >id=3D305470 All I get from the above (after s/3D//g) is "An error occured[sic] in the logger." Can you post another recipe for getting there? Regards, Bengt Richter From piir at earthlink.net Wed Dec 24 13:28:24 2003 From: piir at earthlink.net (Todd Gardner) Date: 24 Dec 2003 10:28:24 -0800 Subject: TypeError: while constructing argument 4: Message-ID: <9b849915.0312241028.61c14f2b@posting.google.com> Hello all, I need to ask for some of your expertise. How to define the variable so that I can pass it as an array of 16 bit integers? ... ni = windll.nidaq32 buffer = c_int * 100 status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) >>> Traceback (most recent call last): File "", line 1, in ? File "C:\Documents and Settings\tnt\My Documents\pc\ctypes\DAQ_Op1.py", line 21, in ? status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) TypeError: while constructing argument 4: Don't know how to convert parameter 4 >>> """ BEGIN DEFINITION of the variable array {buffer} buffer [i16] contains the acquired data buffer is an integer array. buffer has a length equal to or greater than count. When DAQ_Op returns with an error number equal to zero, buffer contains the acquired data. The buffer must be aligned on a 4-byte boundary. If the buffer is allocated as an array of i32s, it must be typecast to an i16 pointer when passing its address to DAQ_Op. If the buffer is allocated as a double-sized array of i16s, the user must check that the buffer is aligned on a 4-byte boundary before passing the buffer to DAQ_Op. END DEFINITION of the variable array {buffer} """ Thank you SO much for any information, Todd -- P.S. Sorry if this is a repost for you. I am resending this post because I believe that the people that follow the ctypes and tutor lists are different that the people that follow this group. From reply.in.the.newsgroup at my.address.is.invalid Sat Dec 27 07:16:55 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 27 Dec 2003 13:16:55 +0100 Subject: Project dream References: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Message-ID: <4ttquv8nogq30jbn8d52ht95pdaaiguk2c@4ax.com> Will Stuyvesant: >I wonder how healty it is: their wiki is empty, the Mitch Kapor blog >is stopped, there is not much recent news. Well, they hired someone only 11 days ago. http://www.osafoundation.org/ -- Ren? Pijlman From noemail at noemail4u.com Thu Dec 18 13:44:42 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 18 Dec 2003 18:44:42 GMT Subject: do this with list comp? References: Message-ID: On Fri, 12 Dec 2003 10:46:58 -0600, John Hunter wrote: > >I want to replace all empty fields in a CSV line with 'NULL'. > >Here is a brute force way > > def fixline(line): > ret = [] > for s in line.split(','): > if not len(s): ret.append('NULL') > else: ret.append(s) > return ret > > line = 'John,Bill,,,Fred' > print fixline(line) > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > >I am wondering if there is a way to do it with list comprehensions. I >know how I would do it with a ternary operator..... > >John Hunter I'd go with Dave Brueck's answer: [x or 'NULL' for x in line.split(',')] The "trick" here is the "hidden" ternary operator. By saying "x or 'NULL' ", you are expressing the equivalent of what would look in C, et al, like: x ? x : 'NULL' In other words, if x is not null/None/empty/nil/false, evaluate to x. Otherwise, evaluate to 'NULL'. --dang From parki at whatevernot.com Tue Dec 30 15:05:14 2003 From: parki at whatevernot.com (Brian Parkinson) Date: 30 Dec 2003 12:05:14 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: <7ba1cb43.0312301205.30156acf@posting.google.com> I have tried to get Tkinter working on my Mac (OS X 10.3). I installed MacPython 2.3 and the TclTkAquaBI-8.4.2.0.dmg. When I type: import Tkinter r = Tkinter.Tk() I get a window all right, but clicking on the window causes the following error: SetFrontProcess failed,-606 the window can't properly get focus. Had same problem when I tried the example Tk application that comes with nltk (Natural Language Toolkit). Any ideas? rstephens at vectron.com (Ron Stephens) wrote in message news:... > "Russell E. Owen" wrote in message news: > > > > Well, I'm not sure how serious the problem actually is. I may have > > overstated it. Hoping to hear soon. > ... ... > > Summary: both aqua and X11 versions of Python are working well for me. > > > > -- Russell > > Well, to summarize my experience, I have never had a Python problem on > Mac OS X that wasn't related to a GUI in one way or another; and I > have less of those issues on Panther (10.3) than on previous versions; > and none of the issues was ever serious enough to make me regret for a > moment using Mac OS X. Having the Unix command line shell available > along with the nice Aqua user interface is really a treat, and most of > my Python use is for command line stuff anyway. Now that I have both > wxPython and Tkinter working acceptabley on Panther, I am happy > indeed. ;-))) > > Ron Stephens From jjl at pobox.com Thu Dec 11 18:45:31 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 23:45:31 +0000 Subject: Python and Flash References: <3FD7191E.2F2FBDC7@hotmail.com> Message-ID: <87n09y2a1w.fsf@pobox.com> Alan Kennedy writes: > [Mars Spider] > > Is there a way to embed a Flash Animation (es: a menu) into a Python > > aaplication for desktop? > > There was a thread about doing this on Windows, using COM, a few > months back. > > http://groups.google.com/groups?selm=RvPFa.37%24zx6.1430%40news.optus.net.au > > I don't know how one would approach the problem on other platforms. I think I remember discussion of ways to do stuff with Flash on other platforms, but I can't be bothered to google for you, Mars Spider (keywords: ActionScript, SWF). John From http Wed Dec 17 18:07:12 2003 From: http (Paul Rubin) Date: 17 Dec 2003 15:07:12 -0800 Subject: Using python with SSH? References: <3fe0dfd7$1@clarion.carno.net.au> Message-ID: <7xn09rhwm7.fsf@ruckus.brouhaha.com> Steve writes: > ssh -l user host "/path/to/program" > > prompts for a password and I don't know how to supply one via a python > script. Is there an easy way out? Can I log onto to the other machine > via ssh somehow? Does a python script support this? Thanks! The simplest way is to set up ssh at both ends with RSA authentication and have a private key on the local machine. That gets rid of the need for a password, while still keeping the connection secure, as long as the local machine is secure. From grey at despair.dmiyu.org Tue Dec 16 14:48:00 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Tue, 16 Dec 2003 19:48:00 -0000 Subject: HalfLife/Cstrike monitorring References: <3fd84154$0$251$4d4ebb8e@news.nl.uu.net> <3FD8C79C.D7166008@alcyone.com> Message-ID: On 2003-12-11, Erik Max Francis wrote: > It sounds like you just want a server statistics package, of which there > are many available. See Google; a good one is PsychoStats. There's > really no need for you to reinvent the wheel here. Not true. Psycho stats does not, for example, take the details given by the connection and translate it into something MRTG or LRRD can parse for a general graph of players per time unit. Furthremore Psycho works on the logs not on the udp interface. With that said I'd recommend the person just sit down with a good Python book and hammer at it. Took me about 10m to get my script working to query just what he was asking for and translate the results into information I needed. Prior to that I had never worked with network code in any language. The major boon was being able to play with code interactively. :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From max at alcyone.com Thu Dec 11 14:38:04 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 11 Dec 2003 11:38:04 -0800 Subject: HalfLife/Cstrike monitorring References: <3fd84154$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: <3FD8C79C.D7166008@alcyone.com> "Guyon Mor?e" wrote: > I want to write a HalfLife/CStrike monitor, to make some nice > statistics for > an upcoming LAN-party. I've found some pointers on how to use the > protocol, > but now I have to do the following: > > 1. make an UDP connection > 2. send a string(?) like '\xFF\xFF\xFF\xFFdetails\x00' > 3. translate the response into bytes and strings :-s > > for more details on this protocol see: > http://dev.kquery.com/index.php?article=31 > > I hope someone can help me with at least the first 2 steps. It sounds like you just want a server statistics package, of which there are many available. See Google; a good one is PsychoStats. There's really no need for you to reinvent the wheel here. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Dead men have no victory. -- Euripides From skip at pobox.com Sun Dec 28 19:29:26 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 28 Dec 2003 18:29:26 -0600 Subject: Unicode from Web to MySQL In-Reply-To: <3FEF195F.1020501@rfa.org> References: <3FEF195F.1020501@rfa.org> Message-ID: <16367.30054.194523.552647@montanaro.dyndns.org> >> That's because you're trying to create SQL statements manually. Bill> As opposed to what? Let MySQLdb do the data escaping for you: conn = MySQLdb.Connection(host=..., etc) curs = conn.cursor() curs.execte("insert into sometable" " (field1, field2)" " values" " (%s, %s)", (val1, val2)) Val1 and val2 can be utf-8-encoded strings. MySQLdb will do the right thing for you... Skip From Samwatson at yahoo.com Tue Dec 9 23:13:00 2003 From: Samwatson at yahoo.com (Sam Watson) Date: Tue, 09 Dec 2003 23:13:00 -0500 Subject: Building a new app in python and need some architecture advice. References: <3fd51ecb$0$210$e4fe514c@news.xs4all.nl> <2v7atvkja4e7gd54sualt1d1jjprh9v0sg@4ax.com> <3fd52443$0$210$e4fe514c@news.xs4all.nl> Message-ID: Thanks guys for the help. I think I will be using pyro for the project. From jjl at pobox.com Sun Dec 21 17:17:48 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Dec 2003 22:17:48 +0000 Subject: dynamic typing questions References: Message-ID: <8765g9olwz.fsf@pobox.com> "John Roth" writes: > "Robert Brewer" wrote in message > news:mailman.378.1071946544.9307.python-list at python.org... [...] > When I started in '65, we had one system where we were > lucky to get one turnaround a week. That wasn't usual, > most of the systems had one turnaround per day. Planning > beats flailing around in the debugger any day. :-) I found it interesting to hear a few years back that Linus Torvalds didn't like using a kernel debugger. Debugging that kind of low-level code without a debugger sounds scary to me, but it appears he knows what he's doing... John From c.hodapp at softhome.net Tue Dec 16 23:02:22 2003 From: c.hodapp at softhome.net (Chris Hodapp) Date: 16 Dec 2003 20:02:22 -0800 Subject: SWIG problems - "ImportError: dynamic module does not define......." References: <6e4c7e29.0312152000.229a9d3a@posting.google.com> Message-ID: <6e4c7e29.0312162002.f724ff7@posting.google.com> rbsharp at gmx.de (Richard Sharp) wrote in message news:... > Hello, > I am not at my home office at the moment but you will probably find the > following link helpful: > > http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&oe=utf- > 8&threadm=mailman.999029862.20314.python- > list%40python.org&rnum=7&prev=/groups%3Fhl%3Dde%26ie%3DUTF-8%26oe%3Dutf- > 8%26q%3Dpython%2Bdistutils%2Bexport%26sa%3DN%26tab%3Dwg > > > Richard Sharp > Thank you. That information, along with GCC's manual pages, helped me to get everything working. What eventually worked was 'gcc example.c example_wrap.c -I/usr/include/python-2.3 -Xlinker -export-dynamic -shared -o _example.c'. -Chris From __peter__ at web.de Tue Dec 9 11:19:09 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 17:19:09 +0100 Subject: cell object dereferencing References: <3FD5FD4A.9060406@jandecaluwe.com> Message-ID: Jan Decaluwe wrote: > Is there a way to dereference a cell object (that is, get > the object that it references to) in Python? > > Regards, Jan > I appreciate messages from the future, cryptic as they may be. So: what cell in what prison? Sorry, couldn't resist... Peter From ahmedmo at wanadoo.fr Thu Dec 25 08:03:41 2003 From: ahmedmo at wanadoo.fr (Ahmed MOHAMED ALI) Date: Thu, 25 Dec 2003 14:03:41 +0100 Subject: Threaded server: what's wrong with this code? References: Message-ID: Hi, Sorry for my bad english because i am French-speaking. The problem is in JMSocketThread.handle .When this function terminates its execution flow,the parameter "self.request" is not longer valid. So the thread work with an invalid socket.For this reason,you got the 'Bad file descriptor' error. To correct the problem here's the modified code. #---Modified JMHandler class class JMHandler (SocketServer.BaseRequestHandler): def handle (self): print 'Client connected...' threadEvent = Event() # create an event to wait for the thread JMSocketThread(self.request,threadEvent ).start() # don't forget to pass the event parameter here print 'Request handed off to a thread.' threadEvent.wait() #---Modified JMSocketThread class class JMSocketThread (threading.Thread): def __init__ (self, theSocket): threading.Thread.__init__(self,target=self._myRun,args=[theSocket,theEvent]) # don't forget to pass the event here def _myRun (self,theSocket,theEvent): #don't forget to pass the event here too global THREAD_COUNT THREAD_COUNT+=1 print 'Threaded request started (%d)...'%THREAD_COUNT input='' while 1: input += theSocket.recv(1024) if len(input) and input[-1]=='\n': break input=input.strip() print 'Got input: \'%s\''%input if input=='Is it you?': theSocket.sendall('Yes honey.\n') print 'Threaded request finished.' THREAD_COUNT-=1 theEvent.set() # set the event here to tell the handler to exit Best regards, Ahmed "Fortepianissimo" wrote in message news:ef08387c.0312241345.26a1430d at posting.google.com... > Below are three simple scripts: jmSocketLib.py contains library code > for socket server and client, server.py instantiates a server binding > to port 50000+ (grab the first available port), and client.py > simulates 1000 consecutive connection requests to the server (stress > test). The client searches from port 50000 for the server, and sends a > challenge "JM?" and expects to get a response "0_87" - otherwise > anything that happens to own a port 50000+ would be mistaken to be the > real server. > > The code: > > ---------- jmSocketLib.py ---------- > #!/usr/bin/env python > > import SocketServer,socket,threading > > PORT_MIN=50000 > PORT_MAX=50005 > > THREAD_COUNT=0 > > class JMSocketThread (threading.Thread): > def __init__ (self, theSocket): > threading.Thread.__init__(self,target=self._myRun,args=[theSocket]) > def _myRun (self,theSocket): > global THREAD_COUNT > THREAD_COUNT+=1 > print 'Threaded request started (%d)...'%THREAD_COUNT > input='' > while 1: > input += theSocket.recv(1024) > if len(input) and input[-1]=='\n': break > input=input.strip() > > print 'Got input: \'%s\''%input > if input=='Is it you?': > theSocket.sendall('Yes honey.\n') > > print 'Threaded request finished.' > THREAD_COUNT-=1 > > > class JMHandler (SocketServer.BaseRequestHandler): > def handle (self): > print 'Client connected...' > JMSocketThread(self.request).start() > print 'Request handed off to a thread.' > > > class JMServer (SocketServer.TCPServer): > def __init__ (self): > port=PORT_MIN > while port try: > SocketServer.TCPServer.__init__(self,('',port),JMHandler) > print 'Bound port %d'%port > break > except: > port+=1 > > class JMClient: > def __init__ (self): > port=PORT_MIN > > while port<=PORT_MAX: > try: > self.socket=socket.socket(socket.AF_INET, > socket.SOCK_STREAM) > self.socket.connect(('',port)) > self.socket.sendall('Is it you?\n') > print 'Query sent...' > reply='' > while 1: > reply += self.socket.recv(1024) > if len(reply) and reply[-1]=='\n': break > reply=reply.strip() > > print 'Got reply: \'%s\''%reply > > if reply == 'Yes honey.': > print 'Found the server at port %d'%port > break > else: raise None > except: > self.socket.close() > port+=1 > > > ---------- server.py ---------- > #!/usr/bin/env python > > from jmSocketLib import * > > if __name__ == '__main__': > jmServer=JMServer() > jmServer.serve_forever() > > ---------- client.py ---------- > #!/usr/bin/env python > > from jmSocketLib import * > > if __name__ == '__main__': > # stress test > for i in range(1000): > print i > JMClient() > > > > > Now the problem is, every now and then I got this error from the > server side: > > ---- ERROR on server side ---- > Client connected... > Threaded request started (1)... > Request handed off to a thread. > Got input: 'Is it you?' > Exception in thread Thread-125: > Traceback (most recent call last): > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > line 436, in __bootstrap > self.run() > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > line 416, in run > self.__target(*self.__args, **self.__kwargs) > File "/Users/ben/temp/jmSocketLib.py", line 25, in _myRun > theSocket.sendall('0_87\n') > File "", line 1, in sendall > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/socket.py", > line 143, in _dummy > raise error(EBADF, 'Bad file descriptor') > error: (9, 'Bad file descriptor') > -------------------------- > > Of course the client then freezes: > > > ---- Client output ---- > 124 > Query sent... > (and freezes) > > > Does anyone have an explanation why this didn't work? Thanks a lot! From hokiegal99 at hotmail.com Mon Dec 15 16:28:01 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 15 Dec 2003 13:28:01 -0800 Subject: Stop popup cmd window Message-ID: <93f5c5e9.0312151328.1dbbd585@posting.google.com> How can I make this script run w/o seeing a cmd popup window on the screen? The script works well, but each hour (when the task scheduler runs it) a brief cmd window appears and then goes away. It's only on the screen for a second or two, but it's noticable. u = "User Name" f = "from address" t = "to address" fp = os.popen("ipconfig /all", "r") msg = MIMEText(fp.read()) fp.close() msg["Subject"] = "%s's IPconfig Report" % u msg["From"] = f msg["To"] = t h = "smtp.vt.edu" s = smtplib.SMTP(h) s.sendmail(f, t, msg.as_string()) s.quit() From deets_noospaam at web.de Thu Dec 4 09:21:56 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 04 Dec 2003 15:21:56 +0100 Subject: Newbie data structes question References: Message-ID: > What data structures and flow controls are most appropriate? Any neat > flow control in python? This should do the counting and sorting def cmp(m1, m2): if m1[1] < m2[1]: return -1 elif m1[1] > m2[1]: return 1 return 0 # you can create your own file here in_file = sys.stdin lines = in_file.realines() # sorts the lines in place lines.sort() res = {} for line in lines: if res.has_key(line): res[line] += 1 else: res[line] = 1 res = res.items() res.sort(cmp) res now has this form: [('brazil', 20), ('cross roads', 0)] Thats it. In python, you have basically three data structures - tuples (1,2,3), lists [1,2,3] and dicts {'key' : 'value', 'key2', 3} You don't have to declare any of them :) Regards, Diez From http Tue Dec 30 18:59:49 2003 From: http (Paul Rubin) Date: 30 Dec 2003 15:59:49 -0800 Subject: Newbie: sort list of dictionaries References: <7xy8su7a1k.fsf@ruckus.brouhaha.com> <5b4785ee.0312301539.461467e7@posting.google.com> Message-ID: <7xbrppdfgq.fsf@ruckus.brouhaha.com> wade at lightlink.com (Wade Leftwich) writes: > D'oh! That sortlist() function was needlessly clever. This is nicer: > > >>> def sortlist(L, decorator=None): > ... if decorator is None: > ... L.sort() > ... return > ... newL = [(decorator(x), x) for x in L] > ... newL.sort() > ... L[:] = [y for (x,y) in newL] Ugh! And don't forget that you still have to write the parametrized decorator function which is missing there. It's simpler in this example to use use a tailored comparison function than to mess with that DSU approach. From Mike at DeleteThis.Geary.com Sat Dec 27 21:01:18 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 27 Dec 2003 18:01:18 -0800 Subject: Project dream References: Message-ID: John J Lee wrote: > ... I looked at the web site (www.thebrain.com), and decided that > life is too short to decode marketing hype <0.5 wink> I'm with you there. :-) But if you have Java enabled in your browser, you're actually getting a test run of their software right there at the top of the page. That's "The Brain" running up there. Go to Demos and then WebBrain for a more comprehensive demo. BTW, that twirling thingamajig in the middle is an important feature--it has to do with releasing your intuition or something like that. It's interesting, but all the swoopy zoomy stuff is not really to my taste. I guess I like my information plain and simple. -Mike From garabik-news-2002-02 at kassiopeia.juls.savba.sk Tue Dec 16 02:56:48 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 16 Dec 2003 07:56:48 GMT Subject: downloading long files References: <95aa1afa.0312152351.7b6143be@posting.google.com> Message-ID: Michele Simionato wrote: > I have a connection which is not 100% rock solid, so if I try > to download a large file (i.e. a Linux ISO image) chances are > that the connection will break. Is there a way to check periodically > if the connection is open, reopen it if needed, and continue the > download without restarting from the beginning? yes, use wget http://www.gnu.org/directory/wget.html or are you looking for a pure python solution? -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From ramen at lackingtalent.com Wed Dec 10 17:43:45 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 10 Dec 2003 22:43:45 -0000 Subject: PATCH: sets.py for Jython 2.1 Message-ID: Hola, I made a backport of sets.py that will run on Jython 2.1. Here is a diff against the Python 2.3 version of sets.py. The changes were simple, but I may have made a mistake here or there, and since the unit tests depend on generators, it was too much trouble to try to test the module this way. I'd appreciate any help on testing it more thoroughly. So far, everything seems to be working fine. The majority of the changes were due to the new iterator protocol, lack of generators and itertools, and dictionaries not supporting "x in d". To use this diff, copy sets.py from the standard Python 2.3 library location to a directory where you have saved the following code as "sets.py.diff" and type the following: $ patch < sets.py.diff Your copy of sets.py should be ready to go. Enjoy, Dave --- /usr/lib/python2.3/sets.py 2003-10-09 09:05:40.001000000 -0700 +++ sets.py 2003-12-10 15:34:14.655250000 -0700 @@ -54,29 +54,15 @@ # - Raymond Hettinger added a number of speedups and other # improvements. -from __future__ import generators -try: - from itertools import ifilter, ifilterfalse -except ImportError: - # Code to make the module run under Py2.2 - def ifilter(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if predicate(x): - yield x - def ifilterfalse(predicate, iterable): - if predicate is None: - def predicate(x): - return x - for x in iterable: - if not predicate(x): - yield x +from __future__ import nested_scopes +def filterfalse(func, seq): + return filter(lambda elt: not func(elt), seq) +False = 0 +True = not False __all__ = ['BaseSet', 'Set', 'ImmutableSet'] -class BaseSet(object): +class BaseSet: """Common base class for mutable and immutable sets.""" __slots__ = ['_data'] @@ -90,7 +76,7 @@ raise TypeError, ("BaseSet is an abstract class. " "Use Set or ImmutableSet.") - # Standard protocols: __len__, __repr__, __str__, __iter__ + # Standard protocols: __len__, __repr__, __str__, __getitem__ def __len__(self): """Return the number of elements of a set.""" @@ -112,12 +98,8 @@ elements.sort() return '%s(%r)' % (self.__class__.__name__, elements) - def __iter__(self): - """Return an iterator over the elements or a set. - - This is the keys iterator for the underlying dict. - """ - return self._data.iterkeys() + def __getitem__(self, index): + return self._data.keys()[index] # Three-way comparison is not supported. However, because __eq__ is # tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and @@ -176,7 +158,7 @@ memo[id(self)] = result data = result._data value = True - for elt in self: + for elt in self._data.keys(): data[deepcopy(elt, memo)] = value return result @@ -227,7 +209,7 @@ little, big = self, other else: little, big = other, self - common = ifilter(big._data.has_key, little) + common = filter(big._data.has_key, little._data.keys()) return self.__class__(common) def __xor__(self, other): @@ -252,9 +234,9 @@ otherdata = other._data except AttributeError: otherdata = Set(other)._data - for elt in ifilterfalse(otherdata.has_key, selfdata): + for elt in filterfalse(otherdata.has_key, selfdata.keys()): data[elt] = value - for elt in ifilterfalse(selfdata.has_key, otherdata): + for elt in filterfalse(selfdata.has_key, otherdata.keys()): data[elt] = value return result @@ -279,7 +261,7 @@ except AttributeError: otherdata = Set(other)._data value = True - for elt in ifilterfalse(otherdata.has_key, self): + for elt in filterfalse(otherdata.has_key, self._data.keys()): data[elt] = value return result @@ -291,12 +273,12 @@ (Called in response to the expression `element in self'.) """ try: - return element in self._data + return element in self._data.keys() except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught - return transform() in self._data + return transform() in self._data.keys() # Subset and superset test @@ -305,7 +287,7 @@ self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False - for elt in ifilterfalse(other._data.has_key, self): + for elt in filterfalse(other._data.has_key, self._data.keys()): return False return True @@ -314,7 +296,7 @@ self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False - for elt in ifilterfalse(self._data.has_key, other): + for elt in filterfalse(self._data.has_key, other._data.keys()): return False return True @@ -360,31 +342,14 @@ value = True - if type(iterable) in (list, tuple, xrange): - # Optimized: we know that __iter__() and next() can't - # raise TypeError, so we can move 'try:' out of the loop. - it = iter(iterable) - while True: - try: - for element in it: - data[element] = value - return - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - else: - # Safe: only catch TypeError where intended - for element in iterable: - try: - data[element] = value - except TypeError: - transform = getattr(element, "__as_immutable__", None) - if transform is None: - raise # re-raise the TypeError exception we caught - data[transform()] = value - + for element in iterable: + try: + data[element] = value + except TypeError: + transform = getattr(element, "__as_immutable__", None) + if transform is None: + raise # re-raise the TypeError exception we caught + data[transform()] = value class ImmutableSet(BaseSet): """Immutable set class.""" @@ -476,8 +441,8 @@ value = True if not isinstance(other, BaseSet): other = Set(other) - for elt in other: - if elt in data: + for elt in other._data.keys(): + if elt in data.keys(): del data[elt] else: data[elt] = value @@ -493,7 +458,7 @@ data = self._data if not isinstance(other, BaseSet): other = Set(other) - for elt in ifilter(data.has_key, other): + for elt in filter(data.has_key, other._data.keys()): del data[elt] # Python dict-like mass mutations: update, clear From logan at phreaker.nospam Tue Dec 2 06:14:50 2003 From: logan at phreaker.nospam (Logan) Date: Tue, 02 Dec 2003 12:14:50 +0100 Subject: Names for modules and functions References: Message-ID: On Tue, 02 Dec 2003 05:18:15 +0000, Jeff Wagner wrote: > ... what is a good way to come up with names for modules, function, > etc.? I am trying to come up with meaningful names but keep feeling > like I have a new puppy I have to name (and I was never good at that, > either. My dog's name is Buddy). I like 'Buddy' :-) > So, are there any guidelines? To google for 'naming conventions' resp. 'naming scheme' or 'style guide' might help; but in general, you will only find stuff like 'use underscores', 'don't use underscores', 'use camel notation', 'don't use camel notation' etc. and something on the order resp. use of nouns, verbs etc. (e.g. 'showXmlData' vs. 'XmlDataShow') You might also want to have a look at the 'Style Guide for Python Code' by Guido van Rossum and Barry Warsaw: http://www.python.org/peps/pep-0008.html (But it does not really help in your special situation :-) > Also, is it ok to name a module and function the same? Often you will see that a module and its class have the same name (if the module contains just one class). Finally, it might help to look at the naming conventions for other languages. E.g. for C#/.NET you will find very detailed instructions on how to name stuff (Google, Microsoft website). HTH, L. -- mailto: logan at phreaker(NoSpam).net From alan.gauld at btinternet.com Fri Dec 12 04:02:49 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Dec 2003 09:02:49 GMT Subject: Python code to replace shell scripts References: Message-ID: <3fd9832d.385255327@news.blueyonder.co.uk> On 12 Dec 2003 01:58:23 GMT, William Park wrote: > > count=`ps -ef|grep "pattern"|wc -l` > > for count in `echo $count` > > do > > done > > fi In this case you could change the style to a more slightly more pythonic approach: print len(os.popen('ps -ef|grep "pattern"').read().split()) > In any case, although Python does something well, shell does most things > better. (It's okey... I've got my helmet on.) Shell is generally better at quickly gluing together existing commands. But does so at a significant cost in machine resources and often execution time. Python provides a different approach that is generally better where the solution must be repeated often or where no suitable set of commands already exists. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From mwh at python.net Fri Dec 26 14:12:25 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Dec 2003 19:12:25 GMT Subject: callable classes References: Message-ID: "Duncan Smith" writes: > I recently started to rewrite a class and decided to take a bunch of related > methods and put them in a separate callable class. (They're all what I > would call pointwise operations on pairs of instances, they raise exceptions > for identical reasons, and they all return a new instance). It seemed like > a good idea at the time, but now I'm not so sure. So my very general > questions are: > > Is this a reasonable use for a callable class? It's hard (for me at least) to see what you mean. Post some code? > In what circumstances are callable classes particularly useful? Well, I guess you could say when you have a callable with state. I must admit I prefer to use a bound method in these circumstances, but I'm not really sure why. Cheers, mwh -- Exam invigilation - it doesn't come much harder than that, esp if the book you're reading turns out to be worse than expected. -- Dirk Bruere, sci.physics.research From mike at nospam.com Mon Dec 15 18:53:41 2003 From: mike at nospam.com (Mike Rovner) Date: Mon, 15 Dec 2003 15:53:41 -0800 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: Francis Avila wrote: > Matthew Sims wrote in message >> of programming. Having some difficulty understand some items. >> >> I'm currently re-writing a Perl script into Python and with Perl I >> was free to assign any element in the array without having to fill >> in the previous elements. I can't seem to do that in Python...unless >> I'm doing it wrong. > > Again, in general, Python has *no* implicit > assignments/declarations/modifications/etc. If you don't > *explicitly* ask a list to fill in its intermediate elements, Python > won't do it. This is a conscious design decision, and a great part > of what makes Python Python. For at least two senses of "great", IMO. As were stated here many times it's not a good idea to mechanicaly translate perl to python, they are quite different in approaches despite similar syntax and capabilities. Better understand initial script logic and write python from scratch. In your case it might be list, dictionary or even none of them, so it's highly dependent on the task at hand. > I could never learn perl (despite many attempts), so I ask, what does > perl do to the intermediate elements? Is a perl array more like a > dictionary with implicit integer keys (so intermediate keys simply > don't exist), or does it fill in the intermediate elements with 0 or > something like that? In what perl idioms is this behavior useful? > (I still mean to learn perl one of these days, for shell scripting.) perl doesn't assigns them, they are 'undef', so it's more like python's dict Mike From tismer at stackless.com Tue Dec 30 21:22:53 2003 From: tismer at stackless.com (Christian Tismer) Date: Wed, 31 Dec 2003 03:22:53 +0100 Subject: Project dream In-Reply-To: References: Message-ID: <3FF232FD.4020403@stackless.com> Will Stuyvesant wrote: > Suppose you have the time and the money to start a new project in > Python. What would you like to do? I would like to provide some ideas which I'm carrying around since quite some time. My reluctance is about the fact that I almost never saw an announcement like this being a serious offer. Most of the time it was just some sugar spread around to make people excited, creating lengthy threads with no result. How serious are you about spending a reasonable amount for a really innovative application in Python. I'm a bit curious since none of my google hits reach beyond 2003. ready to be convinced -- happy new year - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From h_schneider at marketmix.com Mon Dec 1 04:35:23 2003 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 1 Dec 2003 10:35:23 +0100 Subject: Solved: McMillan Installer: No module named wxPython.wx References: Message-ID: For everyone, running into the same problem: Use cx_Freeze as an alternate installer: http://starship.python.net/crew/atuining/cx_Freeze/ It uses another import scheme, which works seamlessly with Python 2.3.2. --Harald "Harald Schneider" schrieb im Newsbeitrag news:bq4r10$otl$07$1 at news.t-online.com... > Hi, > > I ran in some problems with Gordon's Installer, after upgrading to Python > 2.3.2: > After starting the executable it brings up a > > ImportError: No module named wxPython.wx > > Before upgrading, everything went well. > I can also run the .py file without any complaints in my system's current > state. > > I tried > - Adding the site-packages and the site-packages/wxPython folder to > PYTHONPATH, > - added'em to PATH > - and added both to the pathext. in the .spec file. > > My platform is > - SUSE Linux 8.1 > - wxWindows 2.4.2 > - wxPython 2.4.2.2 without unicode support > - The latest Installer 5, freshly installed for Python 2.3.2 > - Python 2.3.2, latest release from python.org. > > Thank you very much for your help, > Harald > > > > From anand_soliton at yahoo.com Thu Dec 18 16:36:35 2003 From: anand_soliton at yahoo.com (Anand) Date: 18 Dec 2003 13:36:35 -0800 Subject: __setattr__ and __getattr__ with derived classes Message-ID: <3f5dc178.0312181336.38a72f03@posting.google.com> class base: def __setattr__(self,attr,key,*unexpected): print "Base Class :",attr,key,unexpected,self.__dict__ self.__dict__[attr] = key def __getattr__(self,attr,*unexpected): print "Base Class :",attr,unexpected,self.__dict__ return self.__dict__[attr] class derived(base): def __setattr__(self,attr,key,*unexpected): print "Derived Class :",attr,key,unexpected,self.__dict__ self.__dict__[attr] = key ## def __getattr__(self,attr,*unexpected): ## print "Derived Class :",attr,unexpected ## return self.__dict__[attr] if __name__ == '__main__': c = derived() d = base() print 'No Init yet' def init(self): print 'inside init' self.test = None self.test1 = 'string' self.test2 = 2 print self.test print self.test1 print self.test2 def init2(self): print 'inside init 2' self.test = None self.test3 = 'string' self.test4 = 2 print self.test ## print self.test1 ## print self.test2 base.__dict__['__init__'] = init c = derived() d = base() c.test d.test print "Base Had init" derived.__dict__['__init__'] = init2 c = derived() d = base() print c.test1 print d.test1 ======================================================= Output +++++++++++++++++++++++++++++++++++++++++++++++++++++++ No Init yet inside init Derived Class : test None () {} Derived Class : test1 string () {'test': None} Derived Class : test2 2 () {'test': None, 'test1': 'string'} None string 2 inside init Base Class : test None () {} Base Class : test1 string () {'test': None} Base Class : test2 2 () {'test': None, 'test1': 'string'} None string 2 Base Had init inside init 2 Derived Class : test None () {} Derived Class : test3 string () {'test': None} Derived Class : test4 2 () {'test': None, 'test3': 'string'} None inside init Base Class : test None () {} Base Class : test1 string () {'test': None} Base Class : test2 2 () {'test': None, 'test1': 'string'} None string 2 Base Class : test1 () {'test': None, 'test3': 'string', 'test4': 2} ===================================================================== look at the self.__dict__ in __init__ method Base Class : test2 2 () {'test': None, 'test1': 'string'} Now how did it change to Base Class : test1 () {'test': None, 'test3': 'string', 'test4': 2} in __getattr_ method? I get a key error after this point. the dictionary contents in base class were just fine in the __init__ method. but when i call the __getattr__ python is giving me a different dictionary!!! Can someone explain what is happening? i am using python 2.3.3 From tim.one at comcast.net Sun Dec 7 15:23:35 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 7 Dec 2003 15:23:35 -0500 Subject: Questions about datetime module Message-ID: [someone] > I have several questions about the module datetime. The module has > been added to Python 2.3. It seems that its interface is raw and dirty. > > Who is maintainer of the module? I wrote most of it, but nobody in particular maintains it now. > Who may answer for my questions and proposals? Before doing anything, please take time to learn datetime's history. Zope Corporation paid for the development of the datetime module, and its design was debated extensively on a public WIki: http://zope.org/Members/fdrake/DateTimeWiki/FrontPage Post questions to comp.lang.python, and I'll try to answer when I can make time for it; somebody else may also be able to make time for it then too (e.g., Fred Drake, Jim Fulton, and Guido were also heavily involved in the design). Bugs should be reported on SourceForge. Proposals are a different story -- they usually won't happen unless you're willing to write the code, docs and test suite, and can devote a significant part of your life to arguing. From ajsiegel at optonline.com Sun Dec 7 10:20:01 2003 From: ajsiegel at optonline.com (Arthur) Date: Sun, 07 Dec 2003 15:20:01 GMT Subject: Lists and Tuples References: Message-ID: On Sun, 07 Dec 2003 15:07:58 GMT, Arthur wrote: >On Sun, 7 Dec 2003 15:09:48 +0100, "Fredrik Lundh" > wrote: > >>Arthur wrote: >> >>> "Type" is not normally an ambiguous word. >> >>really? in my experience, "type" and "object" are about as ambiguous >>as words can get, especially when you're talking about Python. >> >> > >I am sure you are right. On faith. Though its not particularly >helpful. > >Art Or else I can rephrase my question. Having learned that type and object are highly ambiguous words, why do we would tend to use them when wanting to clarify list/tuple distinctions. Art From peter at engcorp.com Tue Dec 9 16:14:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Dec 2003 16:14:13 -0500 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> <7xy8tln207.fsf@ruckus.brouhaha.com> Message-ID: <3FD63B25.DC412905@engcorp.com> Paul Rubin wrote: > > Rene Pijlman writes: > > >Why not just stick the import statement where you need it? > > > > Because I need a module from one of a number of different packages, at one > > specific point in my code. > > I still don't understand why you don't want to use an exec statement > for this. That's by far the most natural and understandable way to do it. In this case, he's getting the actual string from the web, so I wouldn't be surprised if exec would be a real can of security worms. -Peter From mars.spider at tiscalinet.it Wed Dec 10 07:35:33 2003 From: mars.spider at tiscalinet.it (Mars Spider) Date: Wed, 10 Dec 2003 13:35:33 +0100 Subject: Python and Flash Message-ID: Is there a way to embed a Flash Animation (es: a menu) into a Python aaplication for desktop? -- Mars Spider Flash Developer From deets_noospaam at web.de Tue Dec 2 13:25:13 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2003 19:25:13 +0100 Subject: Stuck newbie References: <20619edc.0312020958.4c1700cb@posting.google.com> Message-ID: > If that is correct, what I don't understand is how to reference and > modify elements of an individual object. For example, I want to do > things like (in pseudocode): The nice thing is - your pseudocode is quite close python-code ;) > namelist.append( new_record ) > .... > namelist[ index ].flags = 99 > namelist[ index ].list1.append( 100 ) > namelist = [] new_record = [0, [], []] namelist.append(new_record) namelist[-1][0] = 99 namelist[-1][1].append(100) However, if you prefer to access the records fields using names, you can go with a dicionary: new_record = {'flags': 0, 'list1':[], 'list2':[]} Then access is like this namelist[-1]['flags'] = 99 namelist[-1]['list1'].append(100) The last approach would be to create a class new_record: class new_record: def __init__(self): self.flags = 0 self.list1 = [] self.list2 = [] Then your code above should work. Diez From bhan at andrew.cmu.edu Thu Dec 25 13:27:40 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Thu, 25 Dec 2003 13:27:40 -0500 (EST) Subject: Threaded server: what's wrong with this code? In-Reply-To: References: Message-ID: Thank you for the reply, my questions follow: On Thu, 25 Dec 2003, Ahmed MOHAMED ALI wrote: > The problem is in JMSocketThread.handle .When this function terminates its > execution flow,the parameter "self.request" is not longer valid. > So the thread work with an invalid socket.For this reason,you got the 'Bad > file descriptor' error. Maybe my understanding is wrong - but when you pass self.request the reference count should still be greater than 0, so it shouldn't be garbage-collected? > To correct the problem here's the modified code. > > #---Modified JMHandler class > > class JMHandler (SocketServer.BaseRequestHandler): > def handle (self): > print 'Client connected...' > threadEvent = Event() # create an event to wait for the thread Minor: should be threading.Event() > JMSocketThread(self.request,threadEvent ).start() # don't forget > to pass the event parameter here > print 'Request handed off to a thread.' > threadEvent.wait() > > #---Modified JMSocketThread class > > class JMSocketThread (threading.Thread): > def __init__ (self, theSocket): > > threading.Thread.__init__(self,target=self._myRun,args=[theSocket,theEvent]) > # don't forget to pass the event here > def _myRun (self,theSocket,theEvent): #don't forget to pass the event > here too > global THREAD_COUNT > THREAD_COUNT+=1 > print 'Threaded request started (%d)...'%THREAD_COUNT > input='' > while 1: > input += theSocket.recv(1024) > if len(input) and input[-1]=='\n': break > input=input.strip() > > print 'Got input: \'%s\''%input > if input=='Is it you?': > theSocket.sendall('Yes honey.\n') > > print 'Threaded request finished.' > THREAD_COUNT-=1 > theEvent.set() # set the event here to tell the handler to exit > > > Best regards, > Ahmed But this solution sort of defeats the purpose of using threads? Because now every request must wait until the last one is fully processed... I'd appreciate more comments on these questions. Thank you! Ben > > > "Fortepianissimo" wrote in message > news:ef08387c.0312241345.26a1430d at posting.google.com... > > Below are three simple scripts: jmSocketLib.py contains library code > > for socket server and client, server.py instantiates a server binding > > to port 50000+ (grab the first available port), and client.py > > simulates 1000 consecutive connection requests to the server (stress > > test). The client searches from port 50000 for the server, and sends a > > challenge "JM?" and expects to get a response "0_87" - otherwise > > anything that happens to own a port 50000+ would be mistaken to be the > > real server. > > > > The code: > > > > ---------- jmSocketLib.py ---------- > > #!/usr/bin/env python > > > > import SocketServer,socket,threading > > > > PORT_MIN=50000 > > PORT_MAX=50005 > > > > THREAD_COUNT=0 > > > > class JMSocketThread (threading.Thread): > > def __init__ (self, theSocket): > > > threading.Thread.__init__(self,target=self._myRun,args=[theSocket]) > > def _myRun (self,theSocket): > > global THREAD_COUNT > > THREAD_COUNT+=1 > > print 'Threaded request started (%d)...'%THREAD_COUNT > > input='' > > while 1: > > input += theSocket.recv(1024) > > if len(input) and input[-1]=='\n': break > > input=input.strip() > > > > print 'Got input: \'%s\''%input > > if input=='Is it you?': > > theSocket.sendall('Yes honey.\n') > > > > print 'Threaded request finished.' > > THREAD_COUNT-=1 > > > > > > class JMHandler (SocketServer.BaseRequestHandler): > > def handle (self): > > print 'Client connected...' > > JMSocketThread(self.request).start() > > print 'Request handed off to a thread.' > > > > > > class JMServer (SocketServer.TCPServer): > > def __init__ (self): > > port=PORT_MIN > > while port > try: > > SocketServer.TCPServer.__init__(self,('',port),JMHandler) > > print 'Bound port %d'%port > > break > > except: > > port+=1 > > > > class JMClient: > > def __init__ (self): > > port=PORT_MIN > > > > while port<=PORT_MAX: > > try: > > self.socket=socket.socket(socket.AF_INET, > > socket.SOCK_STREAM) > > self.socket.connect(('',port)) > > self.socket.sendall('Is it you?\n') > > print 'Query sent...' > > reply='' > > while 1: > > reply += self.socket.recv(1024) > > if len(reply) and reply[-1]=='\n': break > > reply=reply.strip() > > > > print 'Got reply: \'%s\''%reply > > > > if reply == 'Yes honey.': > > print 'Found the server at port %d'%port > > break > > else: raise None > > except: > > self.socket.close() > > port+=1 > > > > > > ---------- server.py ---------- > > #!/usr/bin/env python > > > > from jmSocketLib import * > > > > if __name__ == '__main__': > > jmServer=JMServer() > > jmServer.serve_forever() > > > > ---------- client.py ---------- > > #!/usr/bin/env python > > > > from jmSocketLib import * > > > > if __name__ == '__main__': > > # stress test > > for i in range(1000): > > print i > > JMClient() > > > > > > > > > > Now the problem is, every now and then I got this error from the > > server side: > > > > ---- ERROR on server side ---- > > Client connected... > > Threaded request started (1)... > > Request handed off to a thread. > > Got input: 'Is it you?' > > Exception in thread Thread-125: > > Traceback (most recent call last): > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > > line 436, in __bootstrap > > self.run() > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/threading.py", > > line 416, in run > > self.__target(*self.__args, **self.__kwargs) > > File "/Users/ben/temp/jmSocketLib.py", line 25, in _myRun > > theSocket.sendall('0_87\n') > > File "", line 1, in sendall > > File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/socket.py", > > line 143, in _dummy > > raise error(EBADF, 'Bad file descriptor') > > error: (9, 'Bad file descriptor') > > -------------------------- > > > > Of course the client then freezes: > > > > > > ---- Client output ---- > > 124 > > Query sent... > > (and freezes) > > > > > > Does anyone have an explanation why this didn't work? Thanks a lot! > > > From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Dec 9 02:23:55 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 9 Dec 2003 08:23:55 +0100 Subject: running non-python progs from python References: Message-ID: Hi ! You can also do (sample) : import os vret = os.popen('c:\\pfiles\\lplayer.exe') print vret @+ -- Michel Claveau From eli at elipollak.com Tue Dec 23 23:55:37 2003 From: eli at elipollak.com (Eli Pollak) Date: Wed, 24 Dec 2003 15:55:37 +1100 Subject: A dictionary list? References: <3fe91593@clarion.carno.net.au> Message-ID: Do you mean you want an iterable dictionary ? Such as in php : $arr = array() $arr[0] = 'a'; $arr[1] = 'b'; $arr['somestr'] = 'str'; $arr[2] = 'c'; foreach($arr as $element) print $element which prints 'a','b','str','c' Or do you mean something else ? Cheers, Eli "Steve" wrote in message news:3fe91593 at clarion.carno.net.au... > Hi, > > How can I create a list of a dictionary? (in other words, I need to > create an array of a dictionary). Please help! > > Steve From logistix at cathoderaymission.net Wed Dec 31 11:49:32 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 31 Dec 2003 08:49:32 -0800 Subject: Is Python Mac Centric??? References: Message-ID: <3c91a864.0312310849.8509c4a@posting.google.com> "Tim Peters" wrote in message > [hokieghal99] > > < I think it would have a much larger user base if Windows user got > > what mac users get. > > It would, but why would Microsoft want to increase Python's user base? They > probably see Python as a competitor to their own programming language > offerings, and they make money from the latter. > > > Could someone explain this to me? > > Not every company is primarily concerned with your best interests . Microsoft has Resource Kit CD's that contain a bunch of "unsupported" tools, some of which are required to do any serious system administration. For some strange reason, they include ActiveState Perl, along with a zip file containing the source code, although it doesn't install by default. They must not have any worries about that language competing seriously with their products ;-) From tismer at tismer.com Fri Dec 19 04:32:37 2003 From: tismer at tismer.com (Christian Tismer) Date: Fri, 19 Dec 2003 10:32:37 +0100 Subject: Last chance! (was: Does anybody really use frame->f_tstate ?) In-Reply-To: <3FDE6D35.3090100@tismer.com> References: <3FDE6D35.3090100@tismer.com> Message-ID: <3FE2C5B5.8080208@tismer.com> Dear Python community, since I didn't get *any* reply to this request, either the request was bad or there is really nobody using f_tstate in a way that makes it urgent to keep. I will wait a few hours and then make the change to Stackless, and I'd like to propose to do the same to the Python core. Christian Tismer wrote: > Hi colleagues, > > this is my second attempt to get rid of the f_tstate field > in frames. I need to find every user of this field. > > What am I talking about? > Well, Python always has a thread state variable which > is a unique handle to the current thread. This variable > is accessed in many places, and there exists a fast macro > to get at it. > Every executing Python frame also gets a copy on creation. > In some cases, this frame->f_tstate field is used, > in other cases the current tstate variable is used. > > If this sounds foreign to you, please stop reading here. > > ------------------------------------------------------------- > > I would like to get rid of the frame->f_tstate, and I'm trying > to find out if there is a need for it. I don't need it, > for Stackless, it is the opposite, it disturbs. > > There was a small thread about this in June this year, where > Guido convinced me that it is possible to create a traceback > on a frame that comes from a different thread. > > http://mail.python.org/pipermail/python-dev/2003-June/036254.html > > Ok, this is in fact possible, although I don't think > anybody has a need for this. > > My question to all extension writers is this: > If you use frame->f_tstate at all, do you use it just > because it is handy, or do you want to use it for > some other purpose? > > One purpose could be that you really want to create a traceback > on a different than the current thread. I have never seen this, > but who knows, so that's why I'm asking the Python world. > > In most cases, a traceback will be created on a frame > that is currently processd or just has been processed. > Accessing a frame of a different thread that is being processed > might make sense for special debugger cases. > > My proposal is > -------------- > > a) change semantics of PytraceBack_Here to use the current tstate. > > b) if such a special purpose exists, create a new function for it. > > c) if urgent, different needs exist to keep f_tstate, > then let's forget about this proposal. > > Especially for Stackless, I'd be keen of getting rid of this. > > thanks for input -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From brian at macnevin.net Sun Dec 14 05:07:30 2003 From: brian at macnevin.net (BJ MacNevin) Date: Sun, 14 Dec 2003 10:07:30 GMT Subject: LIVEWIRES package problem... Message-ID: If anyone is familiar with the Livewires package... I can't get the graphics windows to behave. When I run the test() then everything seems to be working fine. But when I try to use it this happens: begin_graphics() #The graphics window opens as it does for test() draw(200,200) #nothing happens. No graphics. And then, when the mouse is over the window there is a WAIT cursor... and if I click, it all stops working. DOH! Could there be a mouse driver problem? I have no clue at all. Thanks fro any suggestions! BJ MacNevin From max at cNvOiSsiPoAnMtech.com Fri Dec 26 12:49:13 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Fri, 26 Dec 2003 17:49:13 GMT Subject: ANN: Python Language Reference In-Reply-To: References: Message-ID: Stephen Ferg wrote: > An attempt to produce a complete, alphabetized reference of all of > Python's language features. The purpose is support developers, who > http://www.ferg.org/pyref/index.html A VERY noble effort! It earned a bookmark in my browser - thanks! From slzatz at hotmail.com Mon Dec 1 11:21:14 2003 From: slzatz at hotmail.com (Steve Zatz) Date: 1 Dec 2003 08:21:14 -0800 Subject: wxPython: combining wxListCtrl and wxCheckBox References: Message-ID: <6747bc9d.0312010821.33cbd483@posting.google.com> One way to do this is to use the capability of the ListCtrl to display images in the first position in the row. You can create checked and unchecked images and then insert whichever image is appropriate for a given row in the List. When the row is created, LCtrl.InsertImageStringItem(...) can insert the appropriate image and you can then add as many additional columns as you need with LCtrl.SetStringItem(row, column, string) If some event changes the checkbox status of a row: LC_Item = LCtrl.GetItem(row) if __some condition__: LC_Item.SetImage(index_unchecked) else: LC_Item.SetImage(index_checked) LCtrl.SetItem(LC_Item) cartermark46 at ukmail.com (Mark Carter) wrote in message news:... > I would like a wxListCtrl with 3 columns in it. The number of rows in > it will vary during run-time. In the first column of each row should > be a wxCheckBox, which the user can check or uncheck. > > Is such an arrangement possible? > Any example source code? > > wxCheckListBox comes close - but not close enough. Unfortunately, it > does not derive from wxListCtrl, which contains the function > InsertColumn() needed for multiple columns From francisgavila at yahoo.com Tue Dec 23 04:48:43 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 23 Dec 2003 04:48:43 -0500 Subject: global and None References: Message-ID: Leo Yee wrote in message ... >My purpose is to init g. This is very useful when we cannot construct a >global variable. Like when? And why? >But what I got was: >UnboundLocalError: local variable 'g' referenced before assignment Yes; the Python bytecode compiler assumes g is a local unless you specify otherwise (with the global statement). So when g is referenced, it doesn't yet exist in the local namespace, even though Python looks for it there. Hence the error. Your first global is redundant, because you're already in the global namespace. >So I try to solve the problem in this way: >--- code begin --- > >global g >g=None >def foo(): > global g > if g==None: > g=0 >foo() > >--- code end --- > >And it works but the python documentation told me the following: >"Names listed in a global statement must not be defined as formal parameters >or in a for loop control target, class definition, function definition, or >import statement. " Actually, I've looked at this closely, and thought about it a bit, and I'm not sure I understand what the docs mean. Here are my guesses: "formal parameters" def foo(a=1): global a SyntaxError: name 'a' is local and global ("", line ?) Ok, no doubt there. ... "for loop control target" I believe means you can't do the following: def foo(): global i for i in range(10): pass However, you *can* do it, and section 6.3 (assignment statements), where target_list semantics are expounded, allows it: """ Assignment of an object to a single target is recursively defined as follows. - If the target is an identifier (name): + If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace. + Otherwise: the name is bound to the object in the current global namespace. """ Python bug or doc bug in "global"? Or do I misunderstand? ... moving on: "class definition, function definition" def bar(): global foo class/def foo(object): pass ??? This is currently legal, and works AFAICT. Why should it be prohibited, aside from being dangerous and abusive? ... "import statement" Same thing: def foo(): global re import re foo() # imports re globally. Currently possible, ugly, and dangerous, but prohibited? >Does anyone know what I should do to solve this problem? Thanks in advance. What problem? The way you use global doesn't fall under any of these cases it prohibits. Aside from that, all the cases it prohibits work just fine. BTW, your code should be: g = None def foo(): global g if g == None: g = 0 Notice, no 'global g' at the top. This is why global was made, you know. You're using it properly. Whether you should be using globals, however, is another story ;) -- Francis Avila From tweedgeezer at hotmail.com Tue Dec 2 07:42:12 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 2 Dec 2003 04:42:12 -0800 Subject: Handling exceptions consistently with the logging module. Message-ID: <698f09f8.0312020442.4f7558df@posting.google.com> I've just converted my application to use the logging module for its logging needs (it's quite excellent, actually :)). One thing I still have to resolve, though: in many places in my application, I want to catch *all* exceptions *except*, for instance, KeyboardInterrupt and SystemExit. So I'll have code like this: try: callback(data) except Exception, e: log.exception("Uncaught exception from callback") except: # Crazy string exceptions! log.exception("Uncaught exception from callback") With my former hand-rolled logging system, those "log.exception" calls were actually "debug.recoverableException" calls, and if the exception debug.recoverableException found was in the list of "deadly" exceptions, it would simply re-raise it. I've tried that in my logging subclass like so: def formatException(self, (E, e, tb)): for exn in deadlyExceptions: if issubclass(e.__class__, exn): raise return cgitb.text((E, e, tb)).rstrip('\r\n') This, however, doesn't seem to work -- log.exception seems to be logging (and not re-raising) KeyboardInterrupt, and I have to press Ctrl-C three times to actually exit my application. Anyway, I was curious if there's a way to do what I want to do without modifying every "catch all exceptions" places to catch everything but the deadly exceptions. Thanks, Jeremy From tjreedy at udel.edu Sun Dec 21 14:40:09 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 14:40:09 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" wrote in message news:vu8dii9mh30bf9 at news.supernews.com... > > It doesn't matter. As you can see by my reply to Bengt, > the crux of the issue is that, in Ruby, the function call > syntax is *optional.* There is no way to make it optional > in Python, and it is not clear whether it should be. Just so you know, your adding as conclusion the line > It's a non-starter for Python, though. did change how I read (and responded to) that (and other) posts. Since there is no serious proposal to change Python, there is no proposal to resist. Terry J. Reedy From mwh at python.net Mon Dec 15 13:26:05 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Dec 2003 18:26:05 GMT Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: Ville Vainio writes: > Gustavo Niemeyer writes: > > > Heh.. "people should not".. That's the tipical RMS arrogance. > > To be fair to RMS, I must say I didn't quote him directly. Just tried > to shoot in the right direction, more or less. > > BTW, the page > http://www.gnu.org/gnu/rms-lisp.html > > Talks about this issue a bit, and > says something that is more on topic and kinda interesting: > ---- > We had a person working last summer finishing up a translator from > Python to Scheme. I don't know if it's entirely finished yet, but for > anyone interested in this project, please get in touch. So that's the > plan we have for the future. I think that might be quite out of date. Not sure, mind. [snippety] > > > How small does it need to be for your application? > > > > Do you have something with 1kb? :-) > > Perhaps someone might be able to hack up a dynamically scoped Lisp > interpreter in that space... Well, there was the lisp interpreter that won the IOCCC a few years back... that must have compiled to something pretty tiny :-) Cheers. mwh -- it's not that perl programmers are idiots, it's that the language rewards idiotic behavior in a way that no other language or tool has ever done -- Erik Naggum, comp.lang.lisp From db3l at fitlinxx.com Fri Dec 26 10:25:26 2003 From: db3l at fitlinxx.com (David Bolen) Date: 26 Dec 2003 10:25:26 -0500 Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: "Francis Avila" writes: > Is this what you consider inelegant? If it's too over-engineered (!) for > you, use a more basic data type, like a dict (as you suggest later). Or you > can simply bypass init and assign directly: > > x = object() > x.a = 3 > x.b = 5.0 > > But since you *know* the struct's structure, you might as well use __init__ > to formalize it. And you're still executing object's __init__, anyway. Another way to accomplish the above but in a declarative way, needn't even involve the use of __init__ - you could just: class mystruct: a = 3 b = 5.0 and you're done. Technically the names 'a' and 'b' are class level, but they'll work the same way as instance variables unless they are assigned to (in which case they become local to the instance). This also lets you access them as class level if this is really just a single grouping of data rather than something you want multiple instances of. Of course, this code is still being "executed" so that doesn't address the OP's issue on that front (although IMO that's really a non-issue). -- David From engsolnom at ipns.com Sun Dec 28 21:15:49 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Sun, 28 Dec 2003 18:15:49 -0800 Subject: NEWBIE: What's the instance name? Message-ID: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Hi, I've been using constructs(?) like the below. def display(instance, start = None, end = None): if instance.__class__.__name__ == 'UPCA': do some UPCA stuff if instance.__class__.__name__ == 'UPCE': do some UPCE stuff launched by: lx = UPCA(sx), where sx is a string then: display(lx) This all works well. What I'd like to do is display is the instance name. Is it hiding somewhere? Also, if I have a string 4 chars long, representing two bytes of hex, how can I *validate* the string as a *legal* hex string? isdigit works until string = '001A', for example isalnum works, but then allows 'foob' Is there a 'ishexdigit'? I could parse the string, but that seems "un-Pythonish" Thanks in advane....Norm From tim.one at comcast.net Mon Dec 8 22:52:03 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 8 Dec 2003 22:52:03 -0500 Subject: Lists and Tuples In-Reply-To: Message-ID: [Fredrik Lundh] > ... > I expect an apology. No you didn't . But, in the Holiday Spirit, I'm terribly sorry, and while I don't expect you to forgive me, I promise I'll do my best to see that it never happens again. if-only-an-apologetic-spirit-were-contagious-ly y'rs - tim From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Dec 21 19:00:41 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 22 Dec 2003 01:00:41 +0100 Subject: manpage of python 2.3? In-Reply-To: References: Message-ID: <3fe63429$0$242$e4fe514c@news.xs4all.nl> leo wrote: > but i couldn't find a manpage (i use cygwin) nor a general documentation > which commandline switches python recognizes. > > any idea? Try python -h from a dos prompt? --Irmen From danbmil99 at yahoo.com Tue Dec 2 09:36:33 2003 From: danbmil99 at yahoo.com (dan) Date: 2 Dec 2003 06:36:33 -0800 Subject: slightly OT: how do you do that? Message-ID: I recall reading somewhere that posts to c.l.p are crossposted to a python mailing list. Does anyone have a pointer to the technical information on how this is set up? I'm involved in a newsgroup proposal and this issue has come up. thanks in advance. From fredrik at pythonware.com Sun Dec 14 03:42:11 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Dec 2003 09:42:11 +0100 Subject: connection to samba server References: <3fdbc954$0$218$e4fe514c@news.xs4all.nl> Message-ID: Francis Avila wrote: > After <5 minutes of googling, and knowing nothing about windows programming, > it seems that the function you need is WNetAddConnection2: > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wnet/wnet/w > netaddconnection2.asp > > There is a (very popular) Python package out there which exposes the win32 > api. I'm not sure what it's called. (win32api? pythonwin? win32all?) win32all: http://starship.python.net/crew/mhammond/win32/ but I'm pretty sure you can use os.system("net use ...") as well... From tismer at tismer.com Mon Dec 8 23:37:59 2003 From: tismer at tismer.com (Christian Tismer) Date: Tue, 09 Dec 2003 05:37:59 +0100 Subject: Execution state persistence for workflow application In-Reply-To: <3FC3443B.92709051@hotmail.com> References: <3FC3443B.92709051@hotmail.com> Message-ID: <3FD551A7.2030905@tismer.com> Alan Kennedy wrote: > [Serge Orlov] > >>>The problem is that one day you will >>>have to upgrade your program and your last dumpexec won't be >>>compatible with your next loadexec(). You will have to separate >>>code from data to do it. So it means execution persistence is not >>>enough for real life use. Why not just use data persistence alone? > > > [Paolo Losi] > >>In fact data persistence is not sufficient to stop and resume scripts >>in case, for example, system reboot. >>I do want my workflow scripts to resume exactly (and with the same >>globals/locals setup) where they left... >> >>The real alternative would be to define a new script language >>with standard constructs (for, while,...) but again... i don't want >>to reinvent the wheel. >> >>I do not seen execution persistence as an alternative to data >>persistence: I would need both. > > > You might want to investigate Stackless python, an excellent research > work which can save and resume execution state, to some degree. Try > the following google query Here is a small example that I wrote last weekend for Zope. It looks very simple, it lets you run 10 answers *from* the web server against the client in a loop, with no visible call-backs. It *is* a server loop, but ti's obvious that there cannot be a simple loop, since the server freezes until the next request come in. Well, it looks simple, but here is the real power! http://www.centera.de/tismer/stackless/zope_demo/runDemo Will try to finish this and publish, soon -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jeder at earthlink.net Tue Dec 23 00:06:22 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Tue, 23 Dec 2003 05:06:22 GMT Subject: Some pygame issues References: Message-ID: Thanks Lee and Marcos, Got it to work, Of course, if I have another problem I'll be sure to ask. Talk to you later, and Merry X-mas ;) ~Ryan From jason at tishler.net Tue Dec 2 07:54:13 2003 From: jason at tishler.net (Jason Tishler) Date: Tue, 2 Dec 2003 07:54:13 -0500 Subject: cygwin tcltk 8.3 In-Reply-To: References: Message-ID: <20031202125413.GC1660@tishler.net> Greg, On Sat, Nov 29, 2003 at 06:53:11PM -0500, Grzegorz Dostatni wrote: > Does anyone have tcltk 8.3 packages for cygwin? I spend the last 6 > hours searching for them on the net. Could you please check your > cygwin archive? See the following for some stale Cygwin mirrors: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=tcltk-20021218-1 Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From andymac at bullseye.apana.org.au Mon Dec 15 06:31:15 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 15 Dec 2003 22:31:15 +1100 (EST) Subject: ossaudiodev In-Reply-To: References: Message-ID: <20031215222910.R21784@bullseye.apana.org.au> On Sat, 13 Dec 2003, Tyler Eaves wrote: > The docs list the module as being available on FreeBSD, yet neither 2.2 > (built from ports) or 2.3.2 (built by hand from canonical sources) have > it. I don't know about 2.2, but I'm sure that I tested building just before release of 2.3 and it was built on both FreeBSD 4.8 and 5.1 (though from a CVS checkout rather than ports). -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From ville.spammehardvainio at spamtut.fi Sat Dec 27 06:49:03 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 27 Dec 2003 13:49:03 +0200 Subject: Chandler status (was Re: Project dream References: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Message-ID: > > Yes, that's what I meant. Although Chandler seems much more ambitious. > > Very interesting project. > > I wonder how healty it is: their wiki is empty, the Mitch Kapor blog > is stopped, there is not much recent news. But interesting certainly. Reading the blog at http://blogs.osafoundation.org/mitch/ suggests that he is turning his energies to execution: """ What remains is the sometimes unglamorous process building the complete team and orchestrating the complex software development process efficiently to realize the dreams we have created. It is to that end that I am now trying to turn my energies to. """ So the project seems healthy. Even if the blog entry starts in the style of writing that usually accompanies "we tried our best, we had good people, but we're screwed" announcements. The fact that they have new job postings on the Announcements page, dating Dec 18, can't be a bad sign either. -- Ville Vainio http://www.students.tut.fi/~vainio24 From mesteve_b at hotmail.com Fri Dec 19 22:01:15 2003 From: mesteve_b at hotmail.com (python newbie) Date: Sat, 20 Dec 2003 03:01:15 GMT Subject: Books on Python for Windows Message-ID: <%XOEb.31$Bt7.18@newssvr27.news.prodigy.com> I thought I'd ask in case anyone knew: Does anyone foresee a future updated book on Python scripting in Windows, anytime soon? Using Com objects, WSH, etc.. From tchur at optushome.com.au Wed Dec 17 14:33:13 2003 From: tchur at optushome.com.au (Tim Churches) Date: 18 Dec 2003 06:33:13 +1100 Subject: Microsoft SQL Server & python In-Reply-To: References: Message-ID: <1071689593.1202.2.camel@emilio> On Thu, 2003-12-18 at 04:02, Lindstrom Greg - glinds wrote: > Is it possible to connect my python to Microsoft's SQL server? Can anyone > point me in the right direction? I'm on a windows 2000 "professional" box > connection to SQL Server 6.0. Have a look at Object Craft's MS SQL Server Python module at http://www.object-craft.com.au/projects/mssql/ -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From sombDELETE at pobox.ru Fri Dec 26 17:59:18 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 27 Dec 2003 01:59:18 +0300 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com><3014031e.0312242351.d2604c2@posting.google.com><20031225145455.01ad3747.wtrenker@shaw.ca> Message-ID: "Skip Montanaro" wrote in message news:mailman.118.1072449998.684.python-list at python.org... > > Bill> I don't know if this is of any benefit but I was using the latest > Bill> Opera web browser on my Linux system and happened to try out the > Bill> Arabic introduction page on the unicode.org site. The url is: > Bill> http://www.unicode.org/standard/translations/arabic.html > > Looks gorgeous in Safari. Again, I don't read Arabic, so I can't tell what > it's saying, just that it looks nice. (Arabic strikes me as a very pretty > language.) > > Interestingly enough, the highlighting is backwards. If I press and drag > the mouse button from the right edge of a line, the background highlighting > starts from the left edge. It appears Apple doesn't have all the kinks > worked out. It looks great in Firebird 0.7 and IE 6.0. But there are still minor selection problems too. In Firebird double clicking Arabic word sometimes selects extra characters on the left. Double clicking on English word among Arabic is badly wrong. In IE selecting English words together with Arabic highlights the English words in the wrong direction. Unicode _is_ rocket science -- Serge. From skip at pobox.com Sat Dec 20 19:02:24 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 18:02:24 -0600 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <16356.58128.692664.528955@montanaro.dyndns.org> John> The world changes, and ideas that seemed to be perfectly John> appropriate five or ten years ago may no longer be such. Small John> languages with a limited audience have a perfect right to be as John> quirky or as "pure" as their authors want. Once they get beyond John> that point, there's a bit of social responsibility involved in John> addressing common problems. So fork Python and show how it could be done better. If that's the case, people will either drift over to Python-JR, or (some of) your ideas will find their way back into Python-GvR. Or, as in the Emacs/XEmacs split, darts may be thrown across the void for the forseeable future. ;-) Skip From jeder at earthlink.net Sat Dec 6 13:50:45 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Sat, 06 Dec 2003 18:50:45 GMT Subject: Moving around in a string References: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> <5PSdndqm1duFeEyiRVn-sw@sysmatrix.net> Message-ID: On Sat, 06 Dec 2003 08:18:00 -0600, Mark Engle wrote: > Peter Otten wrote: > >> Mark Engle wrote: >> > http://www.python.org/doc/current/lib/module-string.html >> > >> >> One caveat (only for the string module), quoting from the above >> document, but easily overlooked: >> >> "Many of the functions provided by this module are also defined as >> methods of string and Unicode objects; see ``String Methods'' >> (section 2.2.6) for more information on those." >> >> So whenever you're tempted to write string.somefunc(s, moreargs), >> rather use s.somefunc(moreargs). >> >> Peter > > Thank you. Time to do some more reading. > > Mark Hello Everyone, I pulled it off. Thank you for the direction of the split function, Mark. [start code] words_within = sentence.split() word_count = 0 for i in words_within: word_count = word_count+1 print "There are", word_count, "words." [end code] Haha, Now that I've got my parsing fun over with, I can head back to my translation. All I need to figure out now is how to apply the code [start code] pig_latin = word[1:]+word[0]+"ay" [end code] to each word in the string. Any advice on what I should do would be appreciated. Thanks, ~Ryan From nika.nospam at kassube.de Sun Dec 21 12:59:03 2003 From: nika.nospam at kassube.de (Nils Kassube) Date: Sun, 21 Dec 2003 18:59:03 +0100 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: <81vfoadpco.fsf@darwin.lan.kassube.de> "John Roth" writes: > Ruby can get away with it because, as far as I know, functions are > not first class objects. They certainly aren't in Perl which was > Ruby's inspiration. It's more likely to be inherited from Smalltalk, the other big source of inspiration for Matz. A Ruby program is composed of objects whom you "talk to" by sending messages, i.e. calling a method. There are no "functions" as in the hybrid, but in its history getting more and more object-oriented language Python. It's a different way of thinking, not necessarily better or worse. Using function objects as a way of passing small pieces of code is replaced by blocks, also borrowed from Smalltalk. From bowwnz at telstra.com Tue Dec 23 21:54:32 2003 From: bowwnz at telstra.com (Simon B) Date: Wed, 24 Dec 2003 02:54:32 GMT Subject: Is anyone using Python for .NET? In-Reply-To: References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: Mark Hammond wrote: > Simon B wrote: > >> .NET the platform is, to programmers, a common set of types and >> libraries across multiple languages, whereas the JVM was sold along >> with the language Java, which in my opinion the only difference in >> marketing... Sun associated the JVM with Java so that to use the JVM >> they expected you to program in Java. Weird, because they could just >> have easily sold it as a platform on which other languages ran, and >> then we'd all be impressed about the vision of having multiple >> languages use common types... But it's happening anyway >> (http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html). There are far >> more languages running on the JVM than languages running on .NET. > > > This is true, but if you speak to the language implementors, you will > find they prefer .NET over the JVM - mainly as Microsoft got alot of > them into a room at once, and asked them what they truly needed, then > delivered. Many problems that do not exist for Java, C#, C++ or VB, but > do for more niche languages have solutions inside the VM, explicitly to > help solve these problems that noone inside MS ever sees. > > Dynamic languages are still missing some support in V1, but MS promised, > and is delivering, enhancements that better support dynamic languages, > even though it is not a direct issue for these MS languages. I've heard it said that .NET is designed around having multiple languages utilise it as their VM, whearease the JVM was designed to have java utilise it as it's VM... Certainly a better vision, although not something that is uncorrectable with the JVM. Sun could turn around tomorrow and begin changing the JVM spec to make it easier to support other languages, implement a new JVM, and we'd all be none the wiser (aside from the Language implementors :) > >> UNIX is cloning .NET not because it is superior technology (although >> it migth be, but that is arguable) but because it creates a situation >> where UNIX can run all of the software being churned out by .NET >> programmers. > > > I don't agree, but there is no way either of us can be proved right > here. However, I seriously doubt people are putting all this work into > .NET with the sole intention of running code churned out by below > average programmers working for some huge insurance company - and that > is exactly where .NET is "hot" at the moment. Marketting rules here - > "no brain for programming - try .NET" :) The truly smart people, > including the people working on alternate implementations, understand > the bigger picture. > But if Insurance Company has spent millions deveoping code in .NET, and tomorrow we said they could run that code on platform B, with no changes, then it would be a massive boon for platform B. It removes a cost of migration to alternative platforms. I'm not going to second guess the objectives for those re-implementing .NET (albiet, i did in the above paragraph!), but from the perspective of someone who likes the resulting flexibility of moving to platform B, I think it's an amazing ramification. > >> My opinion on why MS did take the .NET path is based on the premise >> that they are only really interested in Operating Systems, which isn't >> too bigger a stretch. They want to sell operating systems, and part of >> the reason corporations don't upgrade to the lastest version until >> they absolutely have to (and even then, they often don't!) is because >> they have invested big money in software that will require >> considerable testing and/or modification and/or risk if the underlying >> OS changes. >> >> .NET solves that problem for Microsoft. > > > I don't understand what you are saying here. That MS only developed > .NET to force people to upgrade their OS? I thought .NET was available > for existing OS's, for free? > > MS have invested *hugely* in this - if every legitimate user of an MS OS > upgraded once, I seriously doubt they would recover their investment. I > believe MS are looking a little more forward than that. > > Underestimate MS at your own risk. It is one thing to not like MS, and > possibly a reasonable positition to take. However, underestimating them > is for fools. > > Mark. > My point was that .NET was developed so that business CAN upgrade their OS. MS only have to support the .NET API, which is not tied to their OS. There are thousands of system implementations that can't move from NT because of the amount of testing and QA (and code changes) that is required to get onto W2k, or Winxp, or Win2k3. As you pointed out... they're looking forward, and cleverly see .NET can't solve this immediate problem, but it can solve tomorrows problem. Any new development on NT should be started in .NET so that these migration issues don't exist for the new software... It's a perfect way of ceasing a businesses investment in yesterdays technology, and beginning their investment in todays technology, with a clear upgrade path to todays operating system... (and tomorrows operating system for that matter!). I would never underestimate MS... which is why I like them so very much and will continue to like and admire them until they cease to hold a grasp on a large volume of the businesses that I work for :) Simon From see_signature__ at hotmail.com Wed Dec 3 07:02:13 2003 From: see_signature__ at hotmail.com (Georgy Pruss) Date: Wed, 03 Dec 2003 12:02:13 GMT Subject: Binary number manipulation References: <350rsvkbsht8rgs1fsjjc7vkktf87sahi7@4ax.com> Message-ID: <9hkzb.52005$Vu5.3422581@twister.southeast.rr.com> "Tim Roberts" wrote in message news:350rsvkbsht8rgs1fsjjc7vkktf87sahi7 at 4ax.com... | SBrunning at trisystems.co.uk wrote: | > | >> 2. If 1 is no, does that mean that I need to do all the manipulation in | >> some icky string format and then go back? | > | >I use: | > | >((high << 16) | low) | | ...which, unfortunately, gives a FutureWarning in Python 2.3 if high | happens to be larger than 32767. Yes, it's really annoying. I use (high * 65536 + low) instead. -Georgy From JoeyTaj at netzero.com Sun Dec 7 23:13:36 2003 From: JoeyTaj at netzero.com (Paradox) Date: 7 Dec 2003 20:13:36 -0800 Subject: PyDoc modifying the source. References: <924a9f9c.0312071552.6ae2302d@posting.google.com> Message-ID: <924a9f9c.0312072013.45b898c1@posting.google.com> JoeyTaj at netzero.com (Paradox) wrote in message news:<924a9f9c.0312071552.6ae2302d at posting.google.com>... > I would really like to document our private (ie underscored) methods > with PyDoc but it does not seem to support this. I would appreciate it > if anyone knew a good way to modify it to accomplish this. > > > Thanks Joey NM, I found the answer. There is a function called visiblename in PyDoc.py. You can make this function return 1 for any object that you want documented. From phildog22 at yahoo.com Fri Dec 12 10:40:54 2003 From: phildog22 at yahoo.com (Phil D.) Date: Fri, 12 Dec 2003 07:40:54 -0800 (PST) Subject: Simple question from Python Newbie Message-ID: <20031212154054.51689.qmail@web41506.mail.yahoo.com> Hello Python Hackers! I just started working with Python a few days ago and have a simple question that I can't seem to figure out. I am trying to build an application to monitor my mouse moving habits while I'm surfing the web for a project at MIT and I can't seem to figure out how to capture mouse clicks. I know that I can capture mouse clicks using Tkinter or another GUI toolkit, but that won't work outside the GUI (in a web browser) as far as I can tell. I get the cursor position pretty easily with win32api.GetCursorPos(), but I can't figure out how to get mouse clicks. Thoughts anyone? What's the easiest way to get mouse clicks outside of a GUI? Thanks in advance! Phil --------------------------------- Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing -------------- next part -------------- An HTML attachment was scrubbed... URL: From noemail at noemail4u.com Mon Dec 22 08:23:55 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 22 Dec 2003 13:23:55 GMT Subject: dynamic typing question References: Message-ID: <27377dcdd307865f045cc7064818d389@news.teranews.com> On Fri, 19 Dec 2003 08:28:58 -0600, "Jason Tesser" wrote: >I work for at a college where I am one of 2 full-time developers and we are looking to program a new >software package fro the campus. This is a huge project as it will include everything from registration to >business office. We are considering useing Java or Python. I for one don't like Java because I feel the >GUI is clunky. I also think that we could produce quality programs faster in Python. > >The other programmer here is very concerned about dynamic typing though in Python. He feels like this >would be too much of a hinderance on us and too easy for us to make a mistake and not catch it until >runtime making debugging harder. > >OK what are your guys thoughts here? How have you all overcome the lack of static typing? Is Python a >bad decision here? By the way we will be using Postgres in the back if that matters to anyone. The point of 'interfaces' in Java is to support something like dynamic typing. In Python, as with Java interfaces, you don't care what an object *is*, only what it *does*. Also, there are external programs (pychecker (href="http://freshmeat.net/projects/pychecker") and pylint (href="http://freshmeat.net/projects/pylint") that perform many of the checks that you would get with a statically-typed language. Finally, the standard Python distribution includes PyUnit for developing unit tests, following the same principles as JUnit, et al. If you create unit tests, you should be able to find run-time problems pretty quickly. I'd recommend avoiding tests that make sure the caller is passing the right "type" of object, though. If the test crashes because the arguments can't *do* the thing the test requires, either the test or the caller is wrong. Either way, you've found a problem. --dang From joshway_without_spam at myway.com Fri Dec 19 11:43:22 2003 From: joshway_without_spam at myway.com (JCM) Date: Fri, 19 Dec 2003 16:43:22 +0000 (UTC) Subject: dynamic typing questions References: Message-ID: Jason Tesser wrote: ... > The other programmer here is very concerned about > dynamic typing though in Python. He feels like this > would be too much of a hinderance on us and too easy > for us to make a mistake and not catch it until > runtime making debugging harder. I come from a mixed background and have worked on projects in both statically and dynamically-typed languages. My only strong advice is to avoid weakly-typed languages like C, so it's good to not hear you asking about that one :) It's true some errors which could have been caught at compile-time by statically typed languages will not be caught until runtime in Python. But the decreased development time you'll enjoy partly makes up for this. To fully make up for it I suggest (as I'm sure will others) robust unit-testing. Also, adding an occasional "assert type(x) == expected_type" might be helpful. From fperez528 at yahoo.com Wed Dec 10 21:50:36 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 10 Dec 2003 19:50:36 -0700 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: Message-ID: Christian Seberino wrote: > I know IPython is another interpreter for Python and was wondering > what people liked about it and if I should switch to it. As the ipython developer, you could say that I'm biased :) But you could simply try it and see if you like it. It's a simple python package with no C dependencies (under *nix), so getting it going is pretty straightforward. I personally can't stand using the standard python shell anymore, which to me feels like a crippled toy. But YMMV. As Sean pointed, some of its nicer features (readline and color support) are finally available to Windows XP/2k users, but only with CVS code. I'll be making a new release soon-ish, but I want to clean some other outstanding small bugs before that. > If it is so good then why is it not part of the standard Python > tarball? I'd like it to, but I haven't even considered proposing such an idea. Right now the ipython internals are a heinous mess, and nobody in their sane mind would accept to maintain such a codebase. But there's hope for a rewrite with the help of some dedicated users (I have very limited time for its development). If we manage to clean it up completely, it might be conceivable to propose it for the standard distribuition (not as a replacement, but as an alternative: it's still slower to load and more complex code). Regards, Fernando. From jepler at unpythonic.net Mon Dec 29 18:06:50 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Dec 2003 17:06:50 -0600 Subject: NEWBIE: ishexdigit revisited In-Reply-To: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> Message-ID: <20031229230650.GA24898@unpythonic.net> The only suggestion I would make is to skip calculating ix and instead just use len(sx). The length of a string is already stored, so it doesn't require Python to count the number of chars again (unlike C's strlen()). Well, actually, I'll make two suggestions: If it's an error in some cases to have an extra nibble, I'd use a 'raise' statement instead of a different return value, something like: def ishexdigit(sx, silent=True): for cx in sx: if not cx in '0123456789abcdefABCDEF': return False if silent or len(sx) % 2 == 0: return True raise ValueError, "Extra nibble in '%s'" % sx Now, ishexdigit('0') or ishexdigit('0', True) will return 1, and ishexdigit('0', False) will cause an exception. Jeff From skip at pobox.com Sun Dec 21 09:35:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Dec 2003 08:35:50 -0600 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: <279b566d.0312201935.38fb2156@posting.google.com> Message-ID: <16357.44998.516266.102889@montanaro.dyndns.org> Francis> H.V wrote in message <279b566d.0312201935.38fb2156 at posting.google.com>... >> Skip Montanaro wrote in message Francis> news:... >> >> Given all that Guido has said about functional programming, i'm >> starting to wonder why he even made functions first class in python . Note that I didn't write the above. HV did. Skip From mwilson at the-wire.com Fri Dec 5 12:32:14 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 05 Dec 2003 12:32:14 -0500 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: In article <8089854e.0312050419.2cf36e34 at posting.google.com>, michael at foord.net (Fuzzyman) wrote: >Right - because if I do something like : > >a = 4 >b = a >a = 5 >print b > >It prints 4... not 5. >In other words - the line b = a creates a name pointing to the object >4, rather than a name pointing to the contents of a..... > >I think I see what you mean - since the object 4 is immutable...... >the line a = 5 destroys the old name a and creates a new one pointing >to object 5, rather than changing what the name a is pointing to. Take care.. forgetting the old binding and replacing it with the new one doesn't depend on 4 being immutable: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a=[4] >>> b=a >>> a=5 >>> print b [4] >>> print a 5 It's more because the `a` in `a=` is simply a name, and the rule for assigning to a name is to forget the previous binding (if any) and create a new binding. If you say `a[0]=` instead, that's a different rule. If `a` referred to an immutable object then it (probably) would make no sense to say `a[0]=`. ("Probably" because people can do the damndest things with class definitions. Can't trust 'em.:) >Since lists and dictionaries are mutable..... changing the contents >modifies the object rather than destroying the refereence tothe old >one and creating a new one..... Lists and dictionaries are mutable, and it does make sense to say `some_list[some_index] = `. When you do *this*, the python-object-reference kept in `some_list` at position `some_index` is forgotten, and is replaced by a new python-object-referemce. Something similar will happen with a dictionary. Also with code like `some_instance.some_attribute =` which you could think of as re-binding `some_attribute` or as mutating `some_instance.__dict__`. Regards. Mel. From __peter__ at web.de Wed Dec 3 07:28:03 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Dec 2003 13:28:03 +0100 Subject: Adding method to object References: Message-ID: Thomas Guettler wrote: > How can I add a method to an object. self is not passed automatically, if you call an instance attribute. You can provide a default value instead: >>> class Foo: ... def __init__(self): ... self.counter = 0 ... >>> f = Foo() >>> def incr(self=f): ... self.counter += 1 ... >>> f.incr = incr >>> f.incr() >>> f.counter 1 >>> If you have more than one instance with the same incr() method, you can wrap it into a lambda: >>> g = Foo() >>> g.incr = lambda self=g: incr(self) >>> g.incr() >>> g.incr() >>> g.counter 2 Peter From olivier.hoarau at shom.fr Fri Dec 19 05:44:28 2003 From: olivier.hoarau at shom.fr (Olivier Hoarau) Date: Fri, 19 Dec 2003 11:44:28 +0100 Subject: SocketServer broadcast References: <3FE2BC10.210AEF11@mortauxspams.bz> Message-ID: <3FE2D68C.D7A493E1@mortauxspams.bz> Torsten Rueger a ?crit : > If so, could you post it ? Of course The server import socket import sys import time GROUP = '192.168.20.255' HOST='192.168.20.73' PORT=10000 print "Port diffusion en fonction",PORT service = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) service.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 ) service.connect((GROUP,PORT)) while 1: contenu=time.ctime(time.time()) service.send(contenu) print "Message envoye" time.sleep(1) service.close() And the client import socket import sys host='192.168.20.73' port=10000 s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) while 1: t,server=s.recvfrom(65535) print t s.close() I hope it will help Olivier From martin at v.loewis.de Mon Dec 15 16:52:14 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 15 Dec 2003 22:52:14 +0100 Subject: codecs latin1 unicode standard output file In-Reply-To: References: Message-ID: Bengt Richter wrote: > I think the OP is thinking files [1] with # -*- coding: iso-8859-1 -*- [2] > _do_ have an encoding, so in some way [3] should be an unambiguous character sequence, > not just a byte sequence The OP could easily overcome this aspect of the problem with a Unicode literal (and in fact, he originally did convert the string literal to a Unicode object before further processing). This does not solve the problem, though: Writing the Unicode object to a file still gives an encoding error, since he did not specify the encoding of the file. Regards, Martin From martin at v.loewis.de Sun Dec 7 04:08:37 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Dec 2003 10:08:37 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > Ok, I'm happy with that. But let's see where the errors come from. > By definition it's from associating the wrong encoding assumption > with a pure byte sequence. Wrong. Errors may also happen when performing unexpected conversions from one encoding to a different one. > 1a. Available unambiguous encoding information not matching the > default assumption was dropped. This is IMO the most likely. > 1b. The byte sequence came from an unspecified source and never got explicit encoding info associated. > This is probably a bug or application design flaw, not a python problem. 1b. is the most likely case. Any byte stream read operation (file, socket, zipfile) will return byte streams of unspecified encoding. > IMO a large part of the answer will be not to drop available > encoding info. Right. And this is very difficult, making the entire approach unimplementable. > I hope an outline of what I am thinking is becoming visible. Unfortunately, not. You seem to assume that nearly all strings have encoding information attached, but you don't explain where you expect this information to come from. > >As I said: What would be the meaning of concatenating strings, if both > >strings have different encodings? > If the strings have encodings, the semantics are the semantics of character > sequences with possibly heterogenous representations. ??? What is a "possibly heterogenous representation", how do I implement it, and how do I use it? Are you suggesting that different bytes in a single string should use different encodings? If not, how does suggesting a heterougenous implementation answer the question of how concatenation of strings is implemented? > The simplest thing would probably be to choose utf-16le like windows > wchar UIAM and normalize all strings that have encodings to that Again: How does that answer the question what concatenation of strings means? Also, if you use utf-16le as the internal encoding of byte strings, what is the meaning of indexing? I.e. given a string s='Hallo', what is len(s), s[0], s[1]? > Instead, the latter could become explicit, e.g., by a string prefix. E.g., > > a'...' > > meaning a byte string represented by ascii+escapes syntax like > current practice (whatever the program source encoding. I.e., > latin-1 non-ascii characters would not be allowed in the literal > _source_ representation even if the program source were encoded in > latin-1. (of course escapes would be allowed)). Hmm. This still doesn't answer my question, but now you are extending the syntax already. > IWT .coding attributes/properties would permit combining character > strings with different encodings by promoting to an encoding that > includes all without information loss. No, it would not - atleast not unless you specify further details. If I have a latin-1 string ('\xf6'), and a koi-8r string ('\xf6'), and concatenate them, what do get? > Of course you cannot arbitrarily combine byte strings b (b.coding==None) > with character strings s (s.coding!=None). So what happens if you try to combine them? > >2. Convert the result string to UTF-8. This is incompatible with > > earlier Python versions. > Or utf-16xx. I wonder how many mixed-encoding situations there > are in earlier code. Single-encoding should not require change > of encoding, so it should look like plain concatenation as far > as the byte sequence part is concerned. It might be mostly > transparent. This approach is incompatible with earlier Python versions even for a single encoding. If I have a KOI-8R s='\xf6' (which is the same as U+0416), and UTF-16 is the internal represenation, and I do s[0], what do I get, and what algorithm is used to compute that result? > socket_or_file.read().coding => None > > unless some encoding was specified in the opening operation. So *all* existing socket code would get byte strings, and so would all existing file I/O. You will break a lot of code. > Remember, if there is encoding, we are semantically dealing with > character sequences, so splicing has to be implemented in terms of > characters, however represented. You never mentioned that you expect indexing to operate on characters, not bytes. That would be incompatible with current Python, so I was assuming that you could not possibly suggest that approach. If I summarize your approach: - conversion to an internal represenation based on UTF-16 - indexing based on characters, not bytes I arrive at the current Unicode type. So what you want is already implemented, except for the meaningless 'coding' attribute (it is meaningless, as it does not describe a property of the string object). > >No, in current Python, there is no doubt about the semantics: We > >assume *nothing* about the encoding. Instead, if s1 and s2 are ^^^^^^^^^^^^^^^^-- If that is so, why does str have an encode method? By mistake, IMO. Marc-Andre Lemburg suggested this as a generalization of Unicode encodings, allowing arbitrary objects to be encoded - he would have considered (3).encode('decimal') a good idea. With the current encode method on string objects, you can do things like s.encode('base64'). > That's supposed to go from character entities to bytes, I thought ;-) In a specific case of character codecs, yes. However, this has (unfortunately) been generalized to arbitrary two-way conversion between arbitrary things. > Which is why I thought some_string.coding attributes to carry that > information explicitly would be a good idea. Yes, it sounds like a good idea. Unfortunately, it is not implementable in a meaningful way. Regards, Martin From Padraig at Linux.ie Thu Dec 18 14:11:12 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Thu, 18 Dec 2003 19:11:12 +0000 Subject: cleanup after exceptions Message-ID: <0%mEb.1392$HR.4074@news.indigo.ie> Hi, I'm a little confused why objects are not deleted after they go out of scope due to an exception? For e.g. >>> import time >>> >>> def f(): >>> myfile=open("file.test","w") >>> myfile.write("not flushed\n") >>> exception=throw >>> >>> f() >>> time.sleep(10) The file is not written/closed until the python interpreter exits. The same thing applies to other objects. cheers, P?draig. From netnews at goldenspud.com Sun Dec 28 13:37:11 2003 From: netnews at goldenspud.com (Matthew Scott) Date: Sun, 28 Dec 2003 18:37:11 GMT Subject: pointers References: Message-ID: km wrote: > Hi all, > > may i know??if??there?is?any?plans?of??introducing?the?concept?of?pointers > into?python?language?as?in?C????(atleast?in?future?versions??) > > regards, > thanks > KM Python is much more "high-level" than C or similar languages. As such there is no real need for a concept such as pointers. Instead, Python uses the concept of references to connect variable names with the objects they represent. For instance, here is an example that demonstrates how two variable names can "point" (or "refer") to the same object. The >>> and ... are the prompts that would be output by the Python interactive interpreter if you were to run this example code in it. (After you read this, you might also check out the "Names" and "Assignment" section of this web page: http://www.effbot.org/zone/python-objects.htm) Create an empty class that we will add some attributes to below. >>> class Foo: ... pass ... Create an instance of the class. The name "f1" now refers to the instance we create. >>> f1 = Foo() Add an attribute to the Foo instance we just created. >>> f1.xyz = 5 Assign the same instance to the name "f2". Now f1 and f2 are two separate names, but they both refer to the exact same object. >>> f2 = f1 Inspect the f2.xyz attribute to see that it contains the same value as f1.xyz. >>> f2.xyz 5 Assigning a new value to the f2.xyz attribute results in f1.xyz being updated as well, because they are the exact same attribute. >>> f2.xyz = 6 >>> f1.xyz 6 You can use the id() function to show that the names "f1" and "f2" point to the same object. (The output of id() will be different on your machine, since they are internal identification numbers used by Python) >>> id(f1) 1075959340 >>> id(f2) 1075959340 >>> id(f1) == id(f2) True If you want "f2" to be a different object than "f1", assign a new instance of Foo to the name "f2". Now "f2.xyz" does not exist since "f2" does not refer to the same object as "f1" any longer. >>> f2 = Foo() >>> f2.xyz Traceback (most recent call last): File "", line 1, in ? AttributeError: Foo instance has no attribute 'xyz' The ID of two separate objects will always be different. >>> id(f2) 1075959372 >>> id(f1) == id(f2) False -- Matthew Scott From jjl at pobox.com Thu Dec 4 18:45:23 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Dec 2003 23:45:23 +0000 Subject: Web authentication References: <7xn0a8qsao.fsf@ruckus.brouhaha.com> Message-ID: <878ylsdu5o.fsf@pobox.com> Paul Rubin writes: > "luigipaioro" writes: > > Does anybody know how can I acces to my site with authentication? > > > > I think that urllib2 can help me but I don't undestand how!!! > > It's documented in the manual. Try something like (untested): > > import urllib > > class Open_with_auth(urllib.FancyURLopener): > def prompt_user_passwd(self, host, realm): > return ('username', 'userpassword') # the uid and passwd you want to use > > urllib._urlopener = Open_with_auth() Doesn't/shouldn't http://user:passwd at example.com/blah.html work? I don't know where that syntax is specified (if anywhere) -- do you know, Paul? It seems at a glance that urllib understands that syntax for ordinary Basic Auth., where urlib2 only knows it as a syntax for proxy Basic Auth., but I may be wrong there... John From bokr at oz.net Fri Dec 5 20:39:23 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Dec 2003 01:39:23 GMT Subject: Newbie question: Any way to improve this code? References: Message-ID: On Fri, 05 Dec 2003 23:45:04 GMT, "David M. Cook" wrote: >In article , Gustavo Campanelli wrote: > >> import string >> f = open("firmas.txt",'r') # open the file >> texto = f.read () >> n = range (len (texto)) >> frases = [0] >> frase ="" >> cant = 0 >> for a in n: >> if texto [a] != "\n": >> frase = frase + (texto [a]) >> else: >> if cant == 0: >> frases [0] = frase >> else: >> frases.append (1) >> frases [cant] = frase >> cant +=1 >> frase = "" > >f = open("firmas.txt",'r') # open the file >frases = [] >for line in f.readlines(): > frases.append(line[:-1]) > >line[:-1] is all but the last element of line. > >or even > >frases = map(str.rstrip, f.readlines()) > >although that may strip more of the end than you want. Someone's working too hard ;-) Should work: frases = file('firmas.txt').read().splitlines() Regards, Bengt Richter From aleax at aleax.it Sat Dec 27 18:24:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Dec 2003 23:24:30 GMT Subject: lists with zero-valued elements References: <3c228754.0312271335.4acfe0fb@posting.google.com> Message-ID: Skip Montanaro wrote: ... > If I wanted to count how many elements were zero, I might do something > like: > > nzeros = 0 > for element in somelist: > if element == 0: > nzeros += 1 > > or more succinctly: > > nzeros = len([element for element in somelist if element == 0]) I'd do somelist.count(0) -- faster, more direct, and even more succint. Alex From hjwidmaier at web.de Mon Dec 15 04:46:01 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 15 Dec 2003 01:46:01 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <6e990e29.0312150146.1edba3bb@posting.google.com> Jamey Cribbs wrote in message news:... > I think GTK looks great on Windows and my PyGTK apps have been very > stable and responsive. On a more subjective note, for me, the PyGTK API > just fits my brain better than the wxPython one does. It just feels > more seemless to me and things make more sense when I look at them. > Like I said, pretty subjective. I've just more or less completed my first program using pyGTK (all my previous programs used Tkinter). While I could have done this with Tkinter as well, I decided to change when I was searching for something like a terminal widget (for still another project, not yet started) and there was already a nice example with pyGTK. My first fears of pyGTK needing much more code (as there aren't zillions of options for the widget creator but hundreds of methods) were unfounded, and the early code ran quite well. There are quite a few rough edges, though, predominantly with Windows: - Under older Windows versions, the default font isn't found, which causes endless warning assertions. It ignores the rc file so you can't simply change the font. (Of course you could work around that, but not trivially, as I understand.) - The file selection dialog has no line for the floppy disk ('A:'). It's ok for Unix, but looks alien and ugly under Windows. - I found no way to stack the windows like I want, i.e. my "file exists, overwrite?"-dialog pops up _below_ the file dialog and isn't seen. Despite my attempts to close the file selection first and raise the other. Under Linux this works fine. - When I create a button with a stock image, I always get a text beside it. (Like "Open" for STOCK_OPEN.) It takes some hoop-jumping to get rid of those. - Under windows, there's no simple installation that just works. You have to play with the path so the DLLs are found. Maybe some of my problems are the result of my newbie status. OTOH, I did try wxPython a few times, and it always crashed on me while playing with the demo. Besides, I'm a bit reluctant to use a framework -- I consider Python to be one -- instead of just a GUI toolkit. Just my personal experience and thoughts. Hans-Joachim From vincent at visualtrans.de Mon Dec 15 17:37:46 2003 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 15 Dec 2003 23:37:46 +0100 Subject: PyThreadState_Swap difference in 2.3.2? References: Message-ID: "Paul Miller" schrieb im Newsbeitrag news:knbstvgsn3o3qmmtu975g8eb94rhpmae2o at 4ax.com... | I have a C++ application that uses multiple embedded Python interpreters. I | allocate multiple interpreters using Py_NewInterpreter, and switch between | them using PyThreadSate_Swap. | | In 2.2.2, this all worked fine. | | I just installed 2.3.2, but now the first time I call Py_NewInterpreter, it | bails out in PyThreadState_Swap, in the debug checking code, with: | | Py_FatalError("Invalid thread state for this thread"); | | Has the interpreter/thread setup code changed since 2.2? | | To be complete, I set up with this: | | Py_Initialize(); | PyThreadState *globalState = PyThreadState_Get(); | | // allocate new interpreter | PyThreadState *interp = Py_NewInterpreter(); The same thing stumped me too a couple of days ago (s. http://groups.google.nl/groups?q=PyNew_Interpreter&hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=braiu1%243r3%241%40news4.tilbu1.nb.home.nl&rnum=1 ) with 2.3.3c1 (same applies 2.4a0 for that matter). Although I am sure the following snip in PyThreadState_Swap was put there for a reason, it would be great if someone could put some light on the matter....: /* It should not be possible for more than one thread state to be used for a thread. Check this the best we can in debug builds. */ #if defined(Py_DEBUG) && defined(WITH_THREAD) if (new) { PyThreadState *check = PyGILState_GetThisThreadState(); if (check && check != new) Py_FatalError("Invalid thread state for this thread"); } #endif Regards Vincent Wehren | | I am investigating to see if a crash I used to see with 2.2 is still around | in 2.3, where if you call Py_Initialize() and Py_Finalize() multiple times | it would die. | | From i at bleat.nospam.com Fri Dec 26 04:08:35 2003 From: i at bleat.nospam.com (Servé Lau) Date: Fri, 26 Dec 2003 10:08:35 +0100 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "Brandon J. Van Every" wrote in message news:bsglco$cskls$1 at ID-207230.news.uni-berlin.de... > But this discussion would only (properly) be about the appropriateness of > various languages for prototyping Game Designs. I say Python is > appropriate, and C isn't. I agree, but simple text files with a few statements, loops and ocnditional expressions are good enough for Game Designs -- Looking for a C(99) compiler for windows? Download lccwin32. http://www.cs.virginia.edu/~lcc-win32/ From dave at pythonapocrypha.com Mon Dec 29 17:39:26 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 29 Dec 2003 15:39:26 -0700 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com><3fef7965.439576157@news.blueyonder.co.uk> <3ff0a9cc.517502278@news.blueyonder.co.uk> Message-ID: <046a01c3ce5c$9db08410$6401fea9@YODA> Alan wrote: > > > If you want to get the Windows "kite-mark" then probably Python > > > is not the best solution > > > > Why? Just curious, but what specifically are you thinking of? The OP's question > > was pretty vague, so it's hard to tell what the question was really about. > > Well for example writing a fully windows compliant screne saver > is impossible using Python You may find this link interesting then. :) http://homepage.hispeed.ch/py430/python/index.html > > > and because you get access to all the windows stiuff when you > > > need it. > > > > That's what ctypes is for. :) > > Gives you access to the types but not the low level win32 APIs. Are you sure you know what ctypes does? What "low level win32 APIs" are you referring to? -Dave From pkropf at legato.com Mon Dec 8 19:57:02 2003 From: pkropf at legato.com (Peter Kropf) Date: Mon, 8 Dec 2003 16:57:02 -0800 Subject: Converting a python script into a standalone application Message-ID: <96F3EC4BDF504540BB9715CBE9DACB8B01948A50@pa-mail1.legato.com> I'm using Installer and have been quite pleased with it and with the support that Gordon provides. We're running it on Windows, Solaris and Linux with plans to add AIX and HP-UX in the near future. - Peter > -----Original Message----- > From: sandeep182 at hotmail.com [mailto:sandeep182 at hotmail.com] > Sent: Monday, December 08, 2003 4:41 PM > To: python-list at python.org > Subject: Converting a python script into a standalone application > > > Hi, > > I've written a commercial application that uses Python > scripts for some of the functionality. Installing the Python > portion of the application requires me to first install > Python, and then install the scripts. I'm looking for an > easier way to install the Python portion. > > I've been referred to: http://www.mcmillan-inc.com/install1.html > > Which application would people recommend for creating a > standalone executable? > > Are there any licensing issues I need to consider wrt > including a "Python runtime" with my distribution? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ray at rays-web.com Fri Dec 26 17:03:13 2003 From: ray at rays-web.com (Ray Smith) Date: Fri, 26 Dec 2003 22:03:13 GMT Subject: Project dream In-Reply-To: References: Message-ID: <3fecafc6@news.syd.ip.net.au> Will Stuyvesant wrote: > Suppose you have the time and the money to start a new project in > Python. What would you like to do? [snip] > What would your favorite be? I'd like to develop some business type of app, eg: * like a personal accounting system, * followed by commercial accounting, * POS, Python still "seems" to lack "mature" business applications. Regards, Ray Smith From jacek.generowicz at cern.ch Wed Dec 10 08:38:38 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 14:38:38 +0100 Subject: About the use of **args References: Message-ID: Duncan Booth writes: > Mark McEahern wrote in > news:mailman.27.1071059861.9307.python-list at python.org: > > > # We can still access the "private" member variable. In Python, > > # private is merely a convention. > > print s._size > > Except that in Python the convention for private variables is to begin them > with two underscore characters, and then it is more than just a convention: Now, I always believed that "private" in Python is spelt "_", while "mangle this name for me because I want to avoid name clashes in multiple inheritance scenarios" is spelt "__". However, I've heard _so_ many people make the (in my opinion incorrect) claim that "private" is spelt "__", that I'm beginning to question my sanity. Where is the Python spelling of "private" set in stone ? I find the suggestion that a mangled name is somehow "more private" than one with a single leading underscore, mildly insulting to the clients of your code. The implcation is that they can neither work out the (very complicated and cryptic[*]) mangling scheme, not use dir(). If a Python programmer wants to acces a private attribute, he can do so, regardless of the number of leading underscores. [*] Sarcasm alert. (This alert was brought to you by the International Campaign for Promotion of Understanding between Cultures.) From whiteywidow at yahoo.com Tue Dec 9 17:23:18 2003 From: whiteywidow at yahoo.com (rt lange) Date: 9 Dec 2003 14:23:18 -0800 Subject: Instance Exception Oddity: Implicit and Explicit not the same? References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > "If it is an instance of the class, the *instance* *becomes* the *exception* > *value*" this says nothing about the *type* of exception, just the *value*. "6.9 The raise statement ...The first two objects are used to determine the type and value of the exception. If the first object is an instance, the TYPE of the exception is the class of the instance, the instance itself is the VALUE, and the second object must be None." >>> class E(Exception): pass >>> i = E('foo') >>> try: raise i except: print sys.exc_info()[:2] (, <__main__.E instance at 0x00A5A850>) *makes perfect sense* "If the first object is a class, it becomes the TYPE of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception VALUE." >>> try: raise Exception, i #first object is a class: becomes the type #second object instance of (sub)class: becomes the valu except: print sys.exc_info()[:2] (, <__main__.E instance at 0x00A5A850>) >>> *hmmm "Exception" did NOT become the TYPE of the exception* As for why I was passing an exception instance to the constructor for a different exception...just pointing out the nonequivalence of the two forms. Why would someone want to do this? Don't ask me. I only use string exceptions. :) RT From dman at dman13.dyndns.org Fri Dec 5 16:34:28 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Fri, 05 Dec 2003 21:34:28 GMT Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> Message-ID: <04a7a1-s8r.ln1@dman13.dyndns.org> On 4 Dec 2003 00:54:11 -0800, Todd Gardner wrote: > --------------------------------------------------------------- > I would appreciate any ideas how to write to the parallel port (Mem > 0x378) when runnning WinXP or Mandrake 9.2. On the linux side, the following code works : f = file('/dev/lp0', 'w') f.write( "Some Data" ) f.close() This assumes that the parallel port you wanted to write to is the first one. (I have no idea what the memory addresses are, and I don't care either :-)) If you are trying to print something, though, I'd recommend not accessing the device directly. On linux use the popen() call to invoke /usr/bin/lp and let the print server handle the actual hardware. If you are trying to interact with some other parallel port device, then some abstraction layer like the recommended PyParallel would be better for production. -D -- Better a little with righteousness than much gain with injustice. Proverbs 16:8 www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From timr at probo.com Wed Dec 10 02:34:23 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Dec 2003 23:34:23 -0800 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: Gustavo Campanelli wrote: > >As far as I've learned so far, .net is good for client server but not >that great for standalone because of the need for the .net runtime to >run things, which creates a large overhead. Disk space is cheap and getting cheaper. Overhead is just not the issue it once was. Plus, the run-time only has to be installed once, and it will be included in all future Microsoft operating systems. >Performance is an issue too, as everything compiles JIT. This is less of an issue than you might think. As you say, everything is compiled the first time it is encountered, so anything used more than one is actually native code. I'm also dubious, but people I respect tell me that .NET program performance is surprisingly good. Plus, the standard library is quite outstanding. It rivals Python's, and exceeds it in Microsoft-centric areas. >I think that's why although .net is a great >idea, a lot of languages will remain language of choice for >standalone/no runtimes/speed critical/cross platform aplications. I >could be wrong, but I don't think I'm far from the truth. There are rumors that the Windows release after Longhorn might be restricted to CLR/.NET programs only. I don't know what that actually means, nor what the sentencing guidelines are for violating the rule, but there it is. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From erralNOSPAMI8SpammeRS at canal21.com Thu Dec 18 02:32:17 2003 From: erralNOSPAMI8SpammeRS at canal21.com (erral) Date: Thu, 18 Dec 2003 08:32:17 +0100 Subject: Parsing an HTML file In-Reply-To: <5e290f27.0312170808.4590723e@posting.google.com> References: <5e290f27.0312170808.4590723e@posting.google.com> Message-ID: CodeGuru73 wrote: > I am trying to find the best way to parse a bunch of html files. They > are all simillar in structure and I need to get them into a database. You can read chapter "HTML Processing" in Diveintopython: http://diveintopython.org/html_processing/index.html From bdesth.tagada at tsoin-tsoin.free.fr Thu Dec 18 07:41:11 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Thu, 18 Dec 2003 13:41:11 +0100 Subject: Save the pythons. In-Reply-To: References: <3fe0e2af$0$24024$626a54ce@news.free.fr> Message-ID: <3fe19c1a$0$1155$636a55ce@news.free.fr> Gilles Lenfant wrote: > "Bruno Desthuilliers" a ?crit dans le > message de news:3fe0e2af$0$24024$626a54ce at news.free.fr... > >>f29 wrote: (snip troll) >>Too big. Won't work. >> > > > Worked anyway :) > Yes :( I guess it's time for a general troll'o'meter revision. From mhammond at skippinet.com.au Mon Dec 15 19:07:48 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 16 Dec 2003 11:07:48 +1100 Subject: PyThreadState_Swap difference in 2.3.2? In-Reply-To: References: Message-ID: vincent wehren wrote: > "Paul Miller" schrieb im Newsbeitrag > news:knbstvgsn3o3qmmtu975g8eb94rhpmae2o at 4ax.com... > | I have a C++ application that uses multiple embedded Python interpreters. > I > | allocate multiple interpreters using Py_NewInterpreter, and switch between > | them using PyThreadSate_Swap. > | > | In 2.2.2, this all worked fine. > | > | I just installed 2.3.2, but now the first time I call Py_NewInterpreter, > it > | bails out in PyThreadState_Swap, in the debug checking code, with: > | > | Py_FatalError("Invalid thread state for this thread"); > | > | Has the interpreter/thread setup code changed since 2.2? > | > | To be complete, I set up with this: > | > | Py_Initialize(); > | PyThreadState *globalState = PyThreadState_Get(); > | > | // allocate new interpreter > | PyThreadState *interp = Py_NewInterpreter(); > > The same thing stumped me too a couple of days ago (s. > http://groups.google.nl/groups?q=PyNew_Interpreter&hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=braiu1%243r3%241%40news4.tilbu1.nb.home.nl&rnum=1 ) > with 2.3.3c1 (same applies 2.4a0 for that matter). > > Although I am sure the following snip in PyThreadState_Swap was put there > for a reason, > it would be great if someone could put some light on the matter....: > > /* It should not be possible for more than one thread state > to be used for a thread. Check this the best we can in debug > builds. > */ > #if defined(Py_DEBUG) && defined(WITH_THREAD) > if (new) { > PyThreadState *check = PyGILState_GetThisThreadState(); > if (check && check != new) > Py_FatalError("Invalid thread state for this thread"); > } > #endif Python stores information in the thread-state structure which is specific to the thread - information such as the exception being handled, the current recursion depth, etc. The assertion above is reporting the fact that 2 distinct ThreadState objects are trying to be used on a single thread. The same thread for which you are trying to create a thread-state already has such a state. Earlier versions of Python made no attempt to detect this, but as far as everyone can tell, was always an implicit assumption. Unfortunately, much of this stuff has never been thought through correctly. Trying to work with multiple InterpreterState objects is also very difficult, and in some cases simply does not work, as not all global variables are stored in an InterpreterState. Theoretically though, this is probably what you want - if a different InterpreterState is current, I would expect a ThreadState specific to the InterpreterState could be used - but I doubt it works The easy answer is to stop trying to create multiple interpreter states, then use the PyGILState calls to manage your thread-state. These should be 2 lines per function (rather than the many that exist now). If you need to build in both pre 2.3 and 2.3+: #if (PY_VERSION_HEX >= 0x02030000) #define USE_GILSTATE #endif /* Then */ #ifdef USE_GILSTATE PyGILState_State state = PyGILState_Ensure(); #else 20 lines of existing code #endif // your body, and at the end #ifdef USE_GILSTATE PyGILState_Release(state); #else existing code #endif Mark. From spam at yourself.com Sat Dec 13 13:28:54 2003 From: spam at yourself.com (Ingo Blank) Date: Sat, 13 Dec 2003 19:28:54 +0100 Subject: psyco + expat SEGVs Message-ID: Hi, while 95% of my 'psycoed' applications run fine, it throws SIGSEGVs in conjunction with expat. Anybody noticed the same ? Python 2.3.2 (#4, Nov 13 2003, 02:10:49) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 $ uname -a Linux euler 2.4.20-8 #1 Thu Mar 13 17:18:24 EST 2003 i686 athlon i386 GNU/Linux psyco 1.1.1 compiled from source, standard config. expat 1.95.5 , standard, 'out of the box', Redhat 9 Thanks --ibl From jacek.generowicz at cern.ch Mon Dec 8 09:21:29 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Dec 2003 15:21:29 +0100 Subject: Speed: bytecode vz C API calls Message-ID: I have a program in which I make very good use of a memoizer: def memoize(callable): cache = {} def proxy(*args): try: return cache[args] except KeyError: return cache.setdefault(args, callable(*args)) return proxy which, is functionally equivalent to class memoize: def __init__ (self, callable): self.cache = {} self.callable = callable def __call__ (self, *args): try: return self.cache[args] except KeyError: return self.cache.setdefault(args, self.callable(*args)) though the latter is about twice as slow. I've got to the stage where my program is still not fast enough, and calls to the memoizer proxy are topping profiler output table. So I thought I'd try to see whether I can speed it up by recoding it in C. The closure-based version seems impossible to recode in C (anyone know a way?), so I decided to write an extension type equivalent to "class memoize" above. This seems to run about 10% faster than the pure Python version ... which is still a lot slower than the pure Python closure-based version. I was expecting C-extensions which make lots of calls to Python C API functions, not to be spectacularly fast, but I'm still a little disapponited with what I've got. Does this sort of speedup (or rather, lack of it) seem right, to those of you experienced with this sort of thing? or does it look like I'm doing it wrong? Could anyone suggest how I could squeeze more speed out of the memoizer? (I'll include the core of my memoize extension type at the below.) [What's the current state of the art wrt profiling Python, and its extension modules? I've tried using hotshot (though not extensively yet), but it seems to show even less information than profile, at first blush.] The memoize extension type is based around the following: typedef struct { PyObject_HEAD PyObject* x_attr; PyObject* cache; PyObject* fn; } memoizeObject; static int memoize_init(memoizeObject* self, PyObject* args, PyObject* kwds) { PyArg_ParseTuple(args, "O", &(self->fn)); Py_INCREF(self->fn); self->cache = PyDict_New(); return 0; } static PyObject* memoize_call(memoizeObject* self, PyObject* args) { PyObject* value = PyDict_GetItem(self->fn, args); if (! value) { PyDict_SetItem(self->cache, args, PyObject_CallObject(self->fn, args)); value = PyDict_GetItem(self->cache, args); } //Py_INCREF(value); return value; }; Thanks, From arjen.dijkstraNoSpam at hccnet.nl Fri Dec 19 03:24:33 2003 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Fri, 19 Dec 2003 09:24:33 +0100 Subject: Hiding console with program compiled in PY2EXE References: <4378fa6f.0312182234.42c4fe73@posting.google.com> Message-ID: <3fe2b5cc$0$65900$e4fe514c@dreader9.news.xs4all.nl> # setup.py from distutils.core import setup import py2exe setup(name="convertdpi", scripts=["convertdpi.pyw"], ) >From the dos command prompt: c:\python23> python.exe setup.py py2exe This works for me. Hope it helps, Arjen "Marc" schreef in bericht news:4378fa6f.0312182234.42c4fe73 at posting.google.com... > Hi all, > > I know that to hide a console normally you simply change the extension > from .py to .pyw. That's simple enough. However I can't seem to > accomplish the same thing after freezing the program. I've tried > building the setup file with the python script as a .pyw file, but it > crashes and doesn't give me a reason. This is of course because the > debug window doesn't open, so you don't know what happened (ahh, the > irony). > > Does anyone know how to successfully freeze a program with py2exe? > > Many thanks, > Marc From nickforest at myrealbox.com Sat Dec 27 16:35:28 2003 From: nickforest at myrealbox.com (Nick Forest) Date: 27 Dec 2003 13:35:28 -0800 Subject: lists with zero-valued elements Message-ID: <3c228754.0312271335.4acfe0fb@posting.google.com> Any body knows a trivial way to enumerate a list with n zero-valued elements? From emile at fenx.com Sun Dec 14 10:07:38 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 14 Dec 2003 07:07:38 -0800 Subject: nested function scopes References: <3fd83270$1@news.broadpark.no> Message-ID: Terry Reedy: > > Nils Grimsmo: > > i'm having some trouble nesting functions. consider the following: [snip] > > def f(): > > x = 1 > > def g(): > > print x # this is not ok > > x = 2 # this implies that x is local to g [snip] > > how do i declare that x belongs to the parent function, so that i can do > > assignments to it? > > Currently you cannot. > Why not use the old method of passing variables to nested functions: def f() x = 1 def g(x=x): print x x = 2 Emile van Sebille emile at fenx.com From quiteblack at yahoo.com Mon Dec 22 22:56:17 2003 From: quiteblack at yahoo.com (black) Date: Mon, 22 Dec 2003 19:56:17 -0800 (PST) Subject: undo and redo Message-ID: <20031223035617.44641.qmail@web21326.mail.yahoo.com> Howdy~ i am with Win2k and had built a window with Tkinter, it has 3 button on its topright corner as common window, but what i want is just one or tow of them. ie, is there any way i can configure the appearance of minimize, maximize and close button ? Regards~ --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Dec 29 17:28:55 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Dec 2003 22:28:55 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <3ff0a51b.516301712@news.blueyonder.co.uk> On Mon, 29 Dec 2003 11:03:46 -0800, engsolnom at ipns.com wrote: > As to the (good) suggestions I use : > > lx = UPCA() > lx.display() > > I considered this approach. The reason I rejected it is that the > actual program has a total of 13 UPCA-like classes (different names, > of course). So you have an inheritance heirarchy? > In use, each class may have one or many instances at a > time, as determined by the user script. My idea was to include the > calling instance 'name' in the display ...not strictly needed, but a > nice touch. > > I could use: > display(lx, 'lx') So you could add a name parameter to the method and do: lx.display('lx') > Why the display in the first place? The user *may* desire to display > the class output, probably most often while trouble-shooting a user > script problem. > > Some of the classes have a common (or near common) display routine, So OOP to the rescue and only write it once at the appropriately common point in the inheritance heirarchy. > others are totally different. And override it for the unique cases. > If I use lx.display(), the display code has to be contained as a > method in each class. Which is good becausae if the data in the class changes you can change the display method (or add a new override if it was using a common one) at the same time in the same place. The display method is tightly coupled to the internals of the class so should be kept with the class. > I chose, for ease of maintenance, to make a display module > with all the display routines gathered together in one spot. In fact that will almost certainly make it harder to maintain, because the most likely need to change a display method is because the class itself has changed. Now you have to change the class and change the display in a separate place. And if the class programmer forgets to change display after making a change it breaks! This is exactly the kind of maintenance scenario that OOP tries to avoid [Note: if you want to change how the display occurs(eg from terminal to GUI) then the best way is to get display to return a string which you can then externally write to console or text widget as needed. In fact if this is for debugging you may want to look at providing a custom repr() method. repr() is intended for giving a programmers view and returns a string. Then you can dosplay your classes at the >>> prompt too for free.] > needed to add a class/display, I feel there's less chance of his/her > messing up the UPCA-like classes. Addimng a class is no problem since he could add a new display method. EXtending an existing class should be done by inheritance so that the origibnal code is not affected, and will simply extend the display method... class UPCA: def display(self, name = ''): # do it here class newUCPA(UCPA): def __init__(self, foo): UCPA.__init__(self) self.foo = foo def display(self, name = '') UCPA.display(self,name) print self.foo > I guess I'm a believer in classes/methods doing a limited number of things, > and doing them well. Classes should manage their own data and that includes displayig it if thats whats neeed. The minute you introduce extermnal functions which access the innards of a class you have broken the data hiding metaphor of OOP and introduced potential for corruption of the data... > Is that a C hang-over? Probably! :-) > Another idea might be to make a display base class, and inherit the > proper display method in each UPCA-like class. But that still leaves > the problem of passing the instance name to the display method. You could use a mixin style (which is what you propose) but it buys very little here. If your aim is to display the internal data of the class then the class itself should do it, its the only one who should know whats inside, to the rest of the world (including the inherited display class) it should be a black box. Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jjl at pobox.com Tue Dec 16 08:38:42 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Dec 2003 13:38:42 +0000 Subject: How to access MFC classes in Python using SWIG ? References: Message-ID: <87zndsyja5.fsf@pobox.com> harry_chillboy at rediffmail.com (Harish) writes: > I am using Python2.3 version with SWIG-1.3.19 to access C++ interface > provided by a DLL. > Some of its function returns MFC class objects like CString , CMap. I > tried to generate wrapper for these classes using SWIG by including > respective header files in .i file. > But it doesn't work. Swig reports hundreds parsing errors in MFC's > file. I'd guess that looking into how win32all does it, and copying that and integrating your stuff with it would be the easiest way to go. I don't think it uses SWIG. John From jetmano1 at yahoo.com Fri Dec 5 00:55:10 2003 From: jetmano1 at yahoo.com (Jethro Ma) Date: Fri, 05 Dec 2003 05:55:10 -0000 Subject: Embedding Python in C++ Message-ID: Here is what I have: ... pName = PyString_FromString("btdownloadheadless"); pargs = PyString_FromString("argv = 'foo.torrent'"); PyImport = PyImport_ImportModuleEx ("btdownloadheadless",pargs, pargs, 0); ... I have a feeling my pargs is wrong. How do I make it so that it is the equivalent of typing btdownloadheadless.py --responsefile=foo.torrent in the command line From fnord at u.washington.edu Tue Dec 23 15:04:28 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 23 Dec 2003 12:04:28 -0800 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: <3FDDC8FE.AED055CB@engcorp.com> <3FE861CF.FCE33746@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3FE861CF.FCE33746 at engcorp.com>... > > ?? Actually it was not, but I'm unclear why you bother saying otherwise > without a smiley... were you trying to be funny, or do you somehow have > better knowledge of what I intended than I did? > > (It was *unclearly* not intentional, perhaps, but it was not clearly intentional.) > > -Peter I was just trying to be funny. I apologize if I've offended. =) From mcfletch at rogers.com Tue Dec 30 01:08:31 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 30 Dec 2003 01:08:31 -0500 Subject: Installing PyOpenGL - can't find libnumarray module In-Reply-To: <7447dd2a.0312292108.13c9a737@posting.google.com> References: <7447dd2a.0312292108.13c9a737@posting.google.com> Message-ID: <3FF1165F.9030302@rogers.com> Steven Gutstein wrote: >"Mike C. Fletcher" wrote in message > > > >>Basically, to fix the problem, uninstall NumArray and install NumPy 23.0. >> >> >I tried this, without success. >I also find I get the same error when I type > >from numarray import * > > You are trying to import a package you just un-installed? Is this line showing up from some other package you're trying to run and you're debugging by trying it at the Python prompt? A Numpy import looks like this: from Numeric import * AFAICS, there's nothing named numarray anywhere in a Numpy 23.0 installation, so if you get that working, then you've not got NumArray purged yet. However, since your original problem was an import error, "the same error" probably (posting exception tracebacks is useful) indicates that you're getting an ImportError saying that numarray doesn't exist. That's what you *want* (since you don't want NumArray hanging around). >I'm wondering if there's some problem with the fact that libnumarray >is a .pyd file. I came across a comment that for some reason .pyd >files don't get found and what I should do is create the following >setup.cfg file: > > This is only for creating stand-alone executables, it has nothing to do with just running PyOpenGL. It's also related to NumArray, *not* Numpy, so again, not relevant. >Is there something >obvious that I'm missing here ? > > Hopefully not any more. Good luck, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From roy at panix.com Fri Dec 19 21:33:37 2003 From: roy at panix.com (Roy Smith) Date: Fri, 19 Dec 2003 21:33:37 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: Ville Vainio wrote: > If the extra features [...] were really > worthwhile, they would be added to Python Down that path lies madness (i.e. Perl). From gandalf at geochemsource.com Tue Dec 2 04:38:47 2003 From: gandalf at geochemsource.com (Gandalf) Date: Tue, 02 Dec 2003 10:38:47 +0100 Subject: python's threading has no "interrupt"? References: Message-ID: <3FCC5DA7.80802@geochemsource.com> > > >>As far as I know python's threading module models after Java's. >>However, I can't find something equivalent to Java's interrupt and >>isInterrupted methods, along with InterruptedException. >>"somethread.interrupt()" will wake somethread up when it's in >>sleeping/waiting state. >> >>Is there any way of doing this with python's thread? I suppose thread >>interrupt is a very primitive functionality for stopping a blocked >>thread. >> >> >Well, I haven't got any answer since I posted it. Meanwhile, I have >been searching for it myself. Something new has been added in 2.3 in >thread module. That's interrupt_main. But, unfortunately, it is the >opposite of what I expected; It interrupts the main thread. > >After all this, I am a bit disappointed about Python. (it's sad) > > Did you try condition objects? threading.Condition Example from the library reference: # Consume one item cv.acquire() while not an_item_is_available(): cv.wait() get_an_available_item() cv.release() # Produce one item cv.acquire() make_an_item_available() cv.notify() cv.release() You can block a thread with a condition object by calling its 'wait()' method. You can call the 'notify()' method from another thread and that will 'interrupt' the blocked thread. It is not the very same thing, but I suspect you can use it for the same purposes. Cheers, Laci 1.0 From image9n at hotmail.com Mon Dec 8 13:17:28 2003 From: image9n at hotmail.com (Agency) Date: 8 Dec 2003 10:17:28 -0800 Subject: Nub needs help withTkinter References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> Message-ID: <1cca69c7.0312081017.27140c39@posting.google.com> > You will need to __bind__ a callback to the key press on a widget. > something like :- > > > > from Tkinter import * > > > root=Tk() > lab = Label(root, text = "Beat Counter : ") > lab.pack() > > beats = 0 > > > > def beatCounter(event): > print "increment counter" > global beats > beats = beats + 1 > lab.config(text = "Beat Counter : %d" %beats) > > def beatReset(event): > print "reset counter" > global beats > beats = 0 > lab.config(text = "Beat Counter : %d" %beats) > > > root.bind("", beatCounter) > root.bind("", beatReset) > > > root.mainloop() > > > You should rewrite the above so it does not use the global statement > ('cause thats cheating!) > > > > HTH > Martin ------------------------------------------------------------------------- Wow. Thats perfect. I'm not sure what you meant about the global statement, this is my first time trying to program anything, but I'll look through the docs and see if I find something out. Now, I just have figure out how this codes works and have it correspond to a clock function on a display, which gives the bpm. Thanks, I was getting rather frustrated. I'll post back if I get stumped. From xah at xahlee.org Sat Dec 20 15:04:04 2003 From: xah at xahlee.org (Xah Lee) Date: 20 Dec 2003 12:04:04 -0800 Subject: replacing two EOL chars by one Message-ID: <7fe97cc4.0312201204.7accda32@posting.google.com> i have a bunch of java files that has spaced-out formatting that i want to get rid of. I want to replace two end of line characters by one end of line characters. The files in question is unix, and i'm also working under unix, so i did: perl -pi'*~' -e "s@\n\n@\n at g" *.java but this to no avail. after many minutes of checking and rechecking and lots of trial and error with frustration, i realized that the fucking perl to my expectations again cannot do this simple fucking thing. Nor can the unix utility tr. Fucking stupid perl couldn't do a simple task of replacing strings. let me just take this opportunity to explain one shit from the thousands from perldoc. The following is a excerpt from perlre: m Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string. s Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match. Note the first sentences of the two, which are logical opposites, but in fact they are sinister and not opposite at all. Fucking stupid perl documentation and Larry Wall moron who is i believe incapable of writing clearly and logically in English masquerading as humor. Now may i ask those who wallow in unix and perl: How do you do this? (if the answer is to write a more elaborate program in perl that explicitly open files and tread lines, please don't bother answering. Unix util answer also welcome. (this message is cross posted to python and scheme and ruby groups because i want them to know the incompetence and sham aspects of perl. (or my opinions thereof.))) Thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From rasjidw at openminddev.net Wed Dec 3 07:11:40 2003 From: rasjidw at openminddev.net (Rasjid Wilcox) Date: Wed, 03 Dec 2003 23:11:40 +1100 Subject: Building a GUI agnostic database application References: <3fcd9d2a@mail.netspeed.com.au> Message-ID: <3fcdd2ba@mail.netspeed.com.au> Uwe Grauer wrote: > Take at look at PAF http://www.dctools.org Interesting. Should I worry about it only being a 0.1 release? Is it mostly just a packaging of several existing established components, or is it something more than that. It does seem to cover pretty much everything I was thinking about. Brian Kelley wrote: > Why not just make a database model that doesn't know anything about the > GUI? The model can a python compliant database driver (say odbc or > whatnot) and you can supply the proper business logic in a concise model. This is _precisely_ what I was planning to do. The issue is that the 'client' program (GUI or text based interface or some other scripted component or whatever) may or may not be running on the same machine as the 'business logic' backend component, which may or may not be on the same machine as the database. I am aware that there are several frameworks around that resolve this problem, and am just having trouble working out which to choose. I guess what I'm really after is some pro's and con's of the alternatives. I probably did not phrase the original question clearly enough. Although I understand the concepts, I'm still learning the lingo. Cheers, Rasjid. From doeringm at gmx.de Tue Dec 2 06:44:47 2003 From: doeringm at gmx.de (Martin Doering) Date: Tue, 02 Dec 2003 12:44:47 +0100 Subject: un-tuple (newbie) References: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> <3fcbc37c$1@nntp0.pdx.net> Message-ID: On Mon, 01 Dec 2003 13:44:57 -0800, sdd wrote: >Personally, I'd call it "cursor", not "c". Also my DB predeliction >leads me to prefer calling it a "row", not a "line". Yes, for shure. It was my first try. :-) >If you know (and don't care to check) that a single row is returned, >with a single value, I might try something like this: > > def single_value_query(db, sql): > cursor = db.cursor() > try: > cursor.execute(sql) > return cursor.fetchone()[0] > finally: > cursor.close() Ah! This is exactly, what I was searching for. For shure, I must force the query to just deliver ONE value back. Thanks also to Heather. The indexing was the bit I did not know till now. The more I do with [J|Y]ython, the more I like the language. Very elegant and clear to read. :-) -- Martin From bignose-hates-spam at and-benfinney-does-too.id.au Wed Dec 3 22:03:57 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 4 Dec 2003 13:53:57 +1050 Subject: newbie: suppressing return values References: Message-ID: On Wed, 3 Dec 2003 19:41:13 -0700 (MST), Jim Benson wrote: > I have a simple newbie question: > It appears that in general functions "show" > their return values. i.e. > >>>> def makeList(): > ... list = [1,2,3] > ... return list > ... >>>> >>>> makeList() > [1, 2, 3] >>>> a = makeList() >>>> This is only in the interactive Python prompt. Python will show the "result", for want of a better word, of any callable or displayable object you type in at the prompt. So there's nothing inherent in 'return' that makes it output its value; it's the invocation of that function at the Python interactive prompt that gives that effect. -- \ "I washed a sock. Then I put it in the dryer. When I took it | `\ out, it was gone." -- Steven Wright | _o__) | Ben Finney From abhjrpe at comcast.net Tue Dec 30 21:20:09 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Tue, 30 Dec 2003 21:20:09 -0500 Subject: Test if IDLE is a mature program Message-ID: ### this will test if your version of IDLE on windows is a MATURE program design ### print "Hello world, If Python IDLE is a mature program design it will output this" Save this simple single line program as "select.py" and try to run it. Then exit IDLE and try to restart IDLE. Aubrey From wtrenker at shaw.ca Sun Dec 21 06:31:49 2003 From: wtrenker at shaw.ca (William Trenker) Date: Sun, 21 Dec 2003 11:31:49 +0000 Subject: memory overhead using from-import? In-Reply-To: <20031221102848.4f901801.wtrenker@shaw.ca> References: <20031221102848.4f901801.wtrenker@shaw.ca> Message-ID: <20031221113149.77f5b7bd.wtrenker@shaw.ca> William Trenker wrote: > Could someone please confirm that if I code the following line in my own module: > from cgi import escape > that the only additional memory overhead from the cgi module will be that required to store the escape function's code. After some experimenting with the /proc filesystem and a closer reading of the Python docs, I think I've answered my own question. It looks like from-import does import the entire module. So, from cgi import escape brings in the entire cgi module but only exposes the escape function to the importing module's namespace. The code, below, set me straight. Bill Python 2.3.2 (#1, Oct 27 2003, 10:19:56) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import cgi >>> import os,re >>> pid = os.getpid() >>> s = file('/proc/%s/status'%pid,'rb').read() >>> print re.search('(VmSize:.*?kB).*(VmExe:.*?kB)',s,re.DOTALL).groups() ('VmSize:\t 5300 kB', 'VmExe:\t 712 kB') Python 2.3.2 (#1, Oct 27 2003, 10:19:56) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from cgi import escape >>> import os, re >>> pid = os.getpid() >>> s = file('/proc/%s/status'%pid,'rb').read() >>> print re.search('(VmSize:.*?kB).*(VmExe:.*?kB)',s,re.DOTALL).groups() ('VmSize:\t 5300 kB', 'VmExe:\t 712 kB') From jjl at pobox.com Mon Dec 22 11:45:14 2003 From: jjl at pobox.com (John J Lee) Date: Mon, 22 Dec 2003 16:45:14 +0000 (GMT) Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: <20031222160434.GA5685@titan.progiciels-bpi.ca> References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> <20031221235511.GA11803@titan.progiciels-bpi.ca> <20031222032550.GA15674@titan.progiciels-bpi.ca> <20031222160434.GA5685@titan.progiciels-bpi.ca> Message-ID: On Mon, 22 Dec 2003, [iso-8859-1] Fran?ois Pinard wrote: > [John J Lee] > > > I had the impression that Mark's thing (Pythonwin, I think it's called -- > > or is that the MFC wrapper? I can never remember.) used the standard > > library, or hooked in at the C level, so that syntax colouring is always > > correct -- unlike Emacs (and unlike vi, I guess). > > You can never be sure to have syntax colouring correct unless you scan > the source from its beginning. Consider for example that you could have > long sections of Python code embedded in triple quotes, turning it all > into a single long string indeed. Most editors try to limit the amount > of text to consider for syntax colouring, as analysing a lot of text may > slow down the editor considerably. They try to limit the analysis to > the currently displayed text, and a bit before, not far. No doubt you're better informed than me about what Pythonwin actually does, but never say never. You could scan the whole thing once, then keep everything 100% correct subsequently just by watching the edits. No, I don't claim it would be easy!-) John From http Mon Dec 15 15:34:43 2003 From: http (Paul Rubin) Date: 15 Dec 2003 12:34:43 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: <7x1xr5g6qk.fsf@ruckus.brouhaha.com> Ville Vainio writes: > > > How small does it need to be for your application? > > > > Do you have something with 1kb? :-) > > Perhaps someone might be able to hack up a dynamically scoped Lisp > interpreter in that space... There have been smaller Lisps than that, but they're not really practical. Your best bet is probably FORTH (http://www.forth.org). From skip at pobox.com Tue Dec 30 11:45:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Dec 2003 10:45:30 -0600 Subject: Is Python Mac Centric??? In-Reply-To: <20031230163855.GN6171@unpythonic.net> References: <20031230163855.GN6171@unpythonic.net> Message-ID: <16369.43946.94768.203083@montanaro.dyndns.org> Jeff> Python could probably be included in the next version of Windows Jeff> if Bill Gates decided he wanted to. But I don't think he's called Jeff> Guido up yet. I believe the Python license gives Bill the option of including Python without Guido's permission. ;-) Skip From ptmcg at austin.rr.com Wed Dec 10 10:56:23 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 10 Dec 2003 15:56:23 GMT Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? (drifting OT) References: <74cc162865d76ebb99c70f018945a32f@news.teranews.com> Message-ID: > One could argue that my approach to learning new modules could use > improvement. And while that may be true, I've found that learning to > recognize error messages, and what causes them, makes it easier to > help others. I would say you have nothing to apologize for, this approach to learning new modules sounds strikingly similar to my own. It's part of what I think is a big advantage to Python (and similar scripting languages), that you can engage in a highly efficient, quick turnaround, exploratory process, without the overhead and delay of compile/correct-syntax-errors/compile/link/run. The immediate feedback (and sometimes, gratification) allows you to stay in that high-intensity mental zone, without the distractions of awkward meta-tasks, for hours at a time (or days or weeks!). -- Paul From newsgroups at jhrothjr.com Wed Dec 17 16:23:33 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 17 Dec 2003 16:23:33 -0500 Subject: filter and map / deprecated? References: Message-ID: "Logan" wrote in message news:pan.2003.12.17.18.35.25.713854 at phreaker.nospam... > I read in PEP 279 the following comment by GvR: > > "filter and map should die and be subsumed into list > comprehensions, not grow more variants." > > Actually, I am using 'filter' and 'map' a lot in my scripts > (not really because they are necessary, but more because I > like them). Should I avoid the usage of 'filter' and 'map' > in the future? The above comment by GvR makes me a little > bit afraid that they will become deprecated one day and that > I will have to change many of my scripts then. My understanding is that they are on the list of functions to go away in 3.0. Guido would like to get rid of all five of the "functional programming" mechanisms. So far, filter, map and apply have acceptable substitutes, and the arm waving brigade is claiming that the new sum() function will handle all "real" use cases for reduce. (You can tell I don't agree, but that doesn't seem to be relevant.) Lambda is the odd man out at this point. I believe it's waiting on an acceptable syntax for blocks, which seems to be very hard to do. John Roth > > -- > mailto: logan at phreaker(NoSpam).net > From ptmcg at austin.rr.com Mon Dec 29 10:47:18 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 29 Dec 2003 15:47:18 GMT Subject: Best match searching References: Message-ID: "Daniel Pryde" wrote in message news:mailman.3.1072700087.8134.python-list at python.org... > Hi everyone. > I was wondering if anyone might be able to help me out here. I'm currently > looking to find the quickest way to find a best fit match in a large array. > My problem is that I have an array of, say, 600*400, which contains a value > at each point, and I need to find the value in that array which is closest > to the input value. > Any hints or tips would be really helpful. :-) > > Daniel I think inverting your matrix to a dictionary may be more "Pythonic". The included snippet constructs an array of values, then creates a dictionary of which values are located at which positions in the array (also handles possibility of duplicates in the array). If you change ROWS and COLS to your problem values of 400 and 600, the matrix-to-dictionary inversion takes a bit of time - but the searches are blindingly fast. -- Paul # mat2Dict.py from random import random import pprint ROWS = 4 COLS = 6 # create matrix print "creating data matrix" matrix = [ [ random() for i in range(COLS) ] for j in range(ROWS) ] print "create dictionary of values" valdict = {} for i,row in enumerate(matrix): for j,elem in enumerate(row): if valdict.has_key(elem): valdict[elem].append( (i,j) ) else: valdict[elem] = [ (i,j) ] # uncomment this line to view the dictionary of values # pprint.pprint( valdict ) matvals = valdict.keys() matvals.sort() print len(matvals),"unique values in matrix" def findClosestVal( searchval ): if searchval <= matvals[0]: return matvals[0] if searchval >= matvals[-1]: return matvals[-1] # do binary search - see http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary hi = len(matvals) lo = -1 while (hi-lo) > 1: loc = ( hi + lo ) / 2 if matvals[loc] > searchval: hi = loc else: lo = loc if abs(searchval-matvals[lo]) < abs(searchval-matvals[hi]): return matvals[lo] else: return matvals[hi] # look up some values for v in range(10): vv = v/10. closestVal = findClosestVal( vv ) print vv, "->", closestVal, "occurring at", valdict[closestVal] From cbrown at metservice.com Mon Dec 1 23:13:58 2003 From: cbrown at metservice.com (Colin Brown) Date: Tue, 2 Dec 2003 17:13:58 +1300 Subject: FD_SETSIZE not working in 2.3.2? References: Message-ID: <3fcc1032$1@news.iconz.co.nz> "Krister Liljedahl" wrote in message news:a9eddd02.0312011354.750039e5 at posting.google.com... > Hi, ... > Does anyone else experience problem with large numbers (>63) of > sockets under Windows? Yes, see details of previous post of mine below. ====================================================== windows under Win2K does not work properly (missed & very delayed transmissions). Under Redhat Linux 9 (where I will be using it) it works fine (with up to 250 sending threads; I hit the thread limit at 255!) Any idea why do I not get any errors reported under Windows? Colin Brown PyNZ --[Sender.py]-------------------------------------------------------- # Send 50 'simultaneous' tcp transmissions to receiver import os,socket,sys,time,thread,traceback def error(): tb = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info( )[2]) return tb[len(tb)-1].replace('\n','') class client: def __init__(self,nodeport): self.nodeport = nodeport self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.cli.settimeout(60.0) def connect(self): self.cli.connect((self.nodeport)) def write(self,data): self.cli.sendall(data) def close(self): self.cli.close() def send(v,data): cli = client(('localhost',20031)) for cnt in range(5): try: cli.connect() break except: if cnt == 4: print v,'Connect failure: ',error() else: time.sleep(0.3) try: cli.write(data) except: print v,'Send failure: ',error() cli.close() print v def action(data,number): for ii in range(1,1+number): thread.start_new_thread(send,(str(ii),data)) if __name__ == '__main__': action(''.join(['00001000',chr(32)*1000]),50) time.sleep(75.0) --[Receiver.py]------------------------------------------------------ import select,socket,thread, time COUNTER = 0 TIME0 = 0.0 class rx: def __init__(self,LocPort=20031,NumConn=100): self.svr = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.svr.bind (('', LocPort)) self.svr.listen(NumConn) def nextConnAddr(self): if select.select([self.svr], [], [], None)[0]: return self.svr.accept() else: raise 'SocketReceiver.rx.nextConnAddr','connection lost' def rxThread(self,recvr): thread.start_new_thread(newSession,(recvr,)) def close(self): self.svr.close() def newSession(conn): sess = session(conn) sess.run() class session: def __init__(self,conn,timeout=180.0): self.conn = conn self.conn.settimeout(timeout) def recvblock(self,length): block = [] size = length while size > 0: chunk = self.conn.recv(size) if chunk: block.append(chunk) size = size - len(chunk) else: raise 'Session.recvblock','connection lost' return ''.join(block) def getsize(self): length = self.recvblock(8) return int(length) def getdata(self,size): return self.recvblock(size) def run(self): global COUNTER, TIME0 data = self.getdata(self.getsize()) if len(data) != 1000: print 'Transmission error' else: COUNTER = COUNTER + 1 if TIME0 == 0.0: TIME0 = time.time() print '%i%s%0.3f' % (COUNTER,'\t',time.time()-TIME0) rcvr = rx() while 1: rcvr.rxThread(rcvr.nextConnAddr()[0]) ---------------------------------------------------------------------- From quiteblack at yahoo.com Thu Dec 25 06:36:16 2003 From: quiteblack at yahoo.com (black) Date: Thu, 25 Dec 2003 03:36:16 -0800 (PST) Subject: how to pass keyword arguments to derived class~ Message-ID: <20031225113616.54983.qmail@web21322.mail.yahoo.com> Hi all~ I met problem when trying passing keyword arguments to derived class. my goal is to pass all keyword arguments to taht derived class as they did for superclass, but the result was not exactly what i want. below is my code: class A: def __init__(self, *args, **kw): print args print kw print class B(A): def __init__(self, *args, **kw): A.__init__(self, args, kw=kw) a = A("a?", a_pro="a!") b = B("b?", b_pro="b!") here is the output: ('a?', ) {'a_pro':'a!'} (('b?', ), ) # I want to get simply ('b?', ) here {'kw':{'b_pro':'b!'}} # Here should also be ('b_pro':'b!') any help ??? --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Fri Dec 5 18:16:41 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 23:16:41 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On 05 Dec 2003 19:18:50 +0100, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >bokr at oz.net (Bengt Richter) writes: > >> If you put a sequence of those in a "string," ISTM the string should >> be thought of as having the same encoding as the characters whose >> ord() codes are stored. > >So this is a matter of "conceptual correctness". I could not care >less: I thought you bring forward real problems that would be solved >if strings had an encoding attached. I thought I did, but the "problem" is not achieving end effects (everyone appreciates your expert advice on that). The "problem" is a bit of (UIAM -- and to explore the issue collaboratively is why I post) unnecessary explicitness required to achieve an end that could possibly happen automatically (according to a "conceptually correct[-me-if-I'm-wrong]" model ;-) > >> But either way, what you wanted to specify was the latin-1 glyph >> sequence associated with the number sequence > >I would use a Unicode object to represent these characters. Yes, that is an effective explicitness, but not what I was trying to get at. > >> >The answer would be more difficult for (4/5)+4.56 if 4/5 was a >> >rational number; for 1 < 0.5+0.5j, Python decides that it just cannot >> >find a result in a reasonable way. For strings-with-attached encoding, >> >the answer would always be difficult. >> Why, when unicode includes all? > >Because at the end, you would produce a byte string. Then the question >is what type the byte string should have. Unicode, of course, unless that coercion was not necessary, as in ascii+ascii or latin-1 + latin-1, etc., where the result could retain the more specific encoding attribute. > >> >assuming it is ASCII will give the expected result, as ASCII is a >> ^^^^^^^^ oh, ok, it's just an assumption. > >Yes. I advocate you should never make use of this assumption, but I >also believe it is a reasonable one - because it would still hold if >the string was Latin-1, KOI-8R, UTF-8, Mac-Roman, ... Why not assume latin-1, if it's just a convenience assumption for certain contexts? I suspect it would be right more often than not, given that for other cases explicit unicode or decode/encode calls would probably be used. > >> >What is the advantage of having an encoding associated with byte >> >strings? >> If e.g. name had latin-1 encoding associated with it by virtue of source like >> ... >> # -*- coding: latin-1 -*- >> name = 'Martin L??wis' >> >> then on my cp437 console window, I might be able to expect to see the umlaut >> just by writing >> >> print name > >I see. To achieve this effect, do > ># -*- coding: latin-1 -*- >name = u'Martin L??wis' >print name Right, but that is a workaround w.r.t the possibility I am trying to discuss. > > >> Why should I have to do that if I have written # -*- coding: latin-1 -*- >> in the second line? Why shouldn't s='blah blah' result in s being internally >> stored as a latin-1 glyph sequence instead of an 8-bit code sequence that will >> trip up ascii assumptions annoyingly ;-) > >Because adding encoding to strings raise difficult questions, which, >when answered, will result in non-intuitive behaviour. Care to elaborate? I don't know what difficult questions nor non-intuitive behavior you have in mind, but I am probably not the only one who is curious ;-) > >> >Currently, they are represented as ASCII+escapes. I see no reason to >> >change that. >> Ok, that's no biggie, but even with your name? ;-) > >I use Unicode literals in source code. They can represent my name just >fine. Ok, ok ;-) > >> interesting. Will u'...' mean Unicode in the abstract, reserving the >> the choice of utf-16(le|be)/wchar or utf-8 to the implementation? > >You seem to be missing an important point. u'...' is available today. No, I know that ;-) But I don't know how you are going to migrate towards a more pervasive use of unicode in all the '...' contexts. Whether at some point unicode will be built into cpython as the C representation of all internal strings, or it will use unicode through unicode objects and their interfaces, which I imagine would be the way it started. Memory-limited implementations might want to make different choices IWG, so the cleaner the python-unicode relationship the freer those choices are likely to be IWT. I was just speculating on these things. > >The choice of representation is currently between UCS-2/UTF-16 and >UCS-4, with UTF-8 being an unlikely candidate for implementation >choice. > >> Yes that seems obvious, but I had some inkling that if two modules >> m1 and m2 had different source encodings, different codes would be >> allowed in '...' literals in each, and e.g., >> >> import m1,m2 >> print 'm1: %r, m2: %r' % (m1.s1, m2.s2) >> >> might have ill-defined meaning > >That is just one of the problems you run into when associating ^--not ;-) >encodings with strings. Fortunately, there is no encoding associated >with a byte string. So assume ascii, after having stripped away better knowledge? It's fine to have a byte type with no encoding associated. But unfortunately ISTM str instances seem to be playing a dual role as ascii-encoded strings and byte strings. More below. > >> But if s = '...' becomes effectively s = u'...' will type('...') => >> ? > >Of course! Just checking ;-) > >> What will become of str? Will that still be the default >> pseudo-ascii-but-really-byte-string general data container that is >> is now? > >Well, will continue to be the byte string type, and >conversion to str() will continue to produce byte strings. It might be >reasonable to add a string() built-in some day, which is a synonym for >unicode(). How will the following look when s == '...' becomes effectively s = u'...' per above? >>> str('L\xf6wis') 'L\xf6wis' >>> str(u'L\xf6wis') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in ange(128) Will there be an ascii codec involved in that first str('...') ? Hm. For a pure-bytes string type, you could define an assumed 8-bit encoding in place of ascii, so that you could always get a unicode translation 1:1. You could do it by using a private code area of unicode, so e.g. '\x00' to '\xff' becomes u'\ue000' to u'\ue0ff' and then e.g., unicode.__str__(u'\ue0ab') could render back '\xab' as the str value instead of raising UnicodeEncodeError saying it's not in ascii range. Also, u'\ue0ab'.encode('bytes') would presumably return the byte string '\xab'. To get the e000-e0ff unicode, you'd do some_byte_string.decode('bytes') analogous to the apparent some_ordinary_str.decode('ascii') that seems to be attempted in some contexts now. BTW, is that really some_ordinary_str.decode(sys.getdefaultencoding()) ? Another thing: what encoding should an ordinary user object return from __str__ ? (I still think str instances with explicit optional mutable 'encoding' attribute slots could be useful ;-) Or should __str__ not return type str any more, but unicode?? Or optionally either? BTW, is '...' =(effectively)= u'...' slated for a particular future python version? Regards, Bengt Richter From skip at pobox.com Tue Dec 2 09:13:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Dec 2003 08:13:54 -0600 Subject: Module for doing some Parsing in Python In-Reply-To: References: Message-ID: <16332.40482.27092.385298@montanaro.dyndns.org> Boris> I'm looking for parsing a Verilog file in my python module, is Boris> there already such a tool in python (a module in progress) to Boris> help instead of doing a duplicate job. And do you know of some Boris> generic parsing module in python, in which you give some kind of Boris> grammar and callbacks ? Check out the SPARK toolkit: http://pages.cpsc.ucalgary.ca/~aycock/spark/ Skip From rstephens at vectron.com Tue Dec 23 17:50:47 2003 From: rstephens at vectron.com (Ron Stephens) Date: 23 Dec 2003 14:50:47 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: I'm sorry to hear about those problems, Russell. I am using Tkinter on Aqua, and I guess now that I think about it, I've noticed a few non-perfect looking dialogs or widgets, but they didnt really bother me. I'm still using the Ptyhon 2.3 that came installed on Panther, I believe, and I hadn't hear about the diffiulties upgrading to a new Python version; it almost makes me want to try it to find out what troubels lurk. Maybe I will and report back... From wtrenker at shaw.ca Thu Dec 18 07:39:27 2003 From: wtrenker at shaw.ca (William Trenker) Date: Thu, 18 Dec 2003 12:39:27 +0000 Subject: distutils enhancements Message-ID: <20031218123927.649331fa.wtrenker@shaw.ca> I believe I recently read that distutils is in the process of being enhanced. Is that correct? Does anyone know if their is an "uninstall" command in the works for distutils? Thanks, Bill From km at mrna.tn.nic.in Wed Dec 31 02:32:18 2003 From: km at mrna.tn.nic.in (km) Date: Wed, 31 Dec 2003 13:02:18 +0530 Subject: Tkinter Message-ID: <20031231073218.GA5738@mrna.tn.nic.in> Hi all, I am in need of some sample scripts which cover vital issues of starting Tkinter with Python. Can somebody provide me with such links ? thanks in advance, regards, KM From pascal.parent at free.fr Wed Dec 3 05:44:34 2003 From: pascal.parent at free.fr (Pascal) Date: 3 Dec 2003 02:44:34 -0800 Subject: Remove no-printable characters in string Message-ID: Hello, What's the best way to delete or replace no-printable characters in a string. i.e.: "\x08toto\x00titi" -> "tototiti" or " toto titi" From tjreedy at udel.edu Sun Dec 21 11:51:15 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 11:51:15 -0500 Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> <7xekv0b0cf.fsf@ruckus.brouhaha.com> <7xad5o7xjw.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xad5o7xjw.fsf at ruckus.brouhaha.com... > Carl Banks writes: > > But I hope the reason you want this is because it's less surprising, > > more intuitive, more useful, or whatnot, and not just because Common > > Lisp did it that way. Because people who can't see the side of any > > computer programming argument except in the context of Common Lisp are > > just pathetic. > > It avoids the need for ridiculous kludges to check whether there is a > real arg there or not, etc. I'd prefer that Python had used the CL > method in the first place since I find the Python method bizarre and > counterintuitive. Now that I know you are wishing for the 'CL method', which I have no knowledge or experience of, I can better understand why our sense of 'ridiculous kludge', 'bizarre', and 'counterintuitive' are somewhat different. Terry J. Reedy From pinto at map.com Thu Dec 11 16:02:32 2003 From: pinto at map.com (David Pinto) Date: 11 Dec 2003 13:02:32 -0800 Subject: minidom and pulldom Message-ID: I'm trying to use either the minidom or pulldom to find table tags in html web pages. I've tried parsing two web pages that show up fine in my browser, but I get errors when I call minidom.parse, or try to get events with pulldom. Is there a parser that is as forgiving as web browsers? From jobs at kandidates.com Thu Dec 4 01:10:19 2003 From: jobs at kandidates.com (techdude27) Date: Thu, 04 Dec 2003 06:10:19 -0000 Subject: Python and Zope Jobs Yahoo Group Message-ID: Python and Zope Jobs Yahoo Group http://groups.yahoo.com/group/pythonzopejobs From google12 at mail.apol.com.tw Sun Dec 14 11:35:18 2003 From: google12 at mail.apol.com.tw (google12) Date: Mon, 15 Dec 2003 00:35:18 +0800 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: Message-ID: Ann... I had tried to use Photoshop 7 to save a .png file with transparency as a .jpg file, and the transparency will be kept in the .jpg file. Thus, I don't know why... Thanks for your help. "Mike C. Fletcher" ??? news:mailman.141.1071412755.9307.python-list at python.org ???... > >Oh, sorry. I made a mistake... > > > >My question is -- when I run the code described below, the transparence of > >the orginal image will be removed. How can I keep the transparence? > > > > im = Image.open(test.png) > > fp = open('test.jpg','wb') > > im.save(fp,'JPEG') > > > > > I believe the thrust of Fredrik's post was: you can't. JPEG does *not* > store alpha channels. It's just not part of the format, so if you need > to store in JPEG format, you will not be storing the alpha channel in > the file. > > If what you're asking is whether you can store the alpha data to a > separate file (as is done with programs such as 3DStudio Max), yes, that > can be done too: > > >>> import Image > >>> i = Image.open( r'p:\OpenGLContext\tests\wrls\simple_texturergba.png' ) > >>> alpha = i.getdata( 3 ) > >>> i2 = Image.new( 'L', i.size, ) > >>> i2.putdata( alpha ) > >>> i2.save( r'p:\OpenGLContext\tests\wrls\simple_texturea.jpg', 'jpeg' ) > From bokr at oz.net Mon Dec 1 14:20:55 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Dec 2003 19:20:55 GMT Subject: Separation of content and code for web (was Re: Python for web ?) References: <3FCB8535.F8F89132@engcorp.com> Message-ID: On Mon, 01 Dec 2003 13:15:17 -0500, Peter Hansen wrote: >Robert Brewer wrote: >> >> Jay O'Connor wrote: >> > Same here. I do the backend programming and usually give the >> > designer a >> > page (See these marks? Don't touch them, the rest of the page is >> > yours) Works well because I'm *not* a graphices designer and >> > I get much >> > better results when I make it work and I give it to a friend >> > to make it look good. >> >> Heh. I'm trying to move into the opposite situation: I do the design and >> give a backend programmer a page (See these marks? Touch them and them >> only; the rest of the page is mine). Works well because the design is >> not then driven by someone who's not a designer. :) > >By far the most rigorous separation that I've seen to date, and one >we're experimenting with more right now, is to have a pure-HTML (or XHTML) >web page with *no* code or funky little embedded crap of any kind at >all, and rely exclusively on "id" attributes on the dynamic parts. > >The code is built to work on the appropriate ids, generally working with >an in-memory model of the data, with serialization back to [X]HTML >when the job is done. > >Web folks get their HTML page without code, programmers get nice >code without embedded HMTL, and everyone is happy. > >I think there's a Java system where this idea was implemented best >but the name doesn't come to mind at the moment. > >Anyone know of a Python-based approach using the same core concept? > It's been on one of my burners for a long time. I have a C++ CGI-based version that uses an embedded ad-hoc scripting language to script the HTML transformation. I had intended just to change the embedded scripting part to Python, but I since have had even grander ideas (;-) so it's not done yet ;-/ I'm wondering what the best way would be to assess the market for it and how to get a fair return for my work on that, (assuming it's really useful and easy to use). Regards, Bengt Richter From j.r.gao at motorola.com Sun Dec 28 21:19:30 2003 From: j.r.gao at motorola.com (J.R.) Date: Mon, 29 Dec 2003 10:19:30 +0800 Subject: Using python to check the status of a program References: Message-ID: "The Jetman" wrote in message news:a38d43b0.0312271424.70a4138c at posting.google.com... > > 1st, which OS are we talking about ? *IF* we're talking about > Linux/Unix/FreeBSD, then it only takes a few lines: > import os > import string > f = os.popen( 'ps -ax' ) > s = f.readlines() > if string.find( s, 'target_pgm' ) > -1: > #### we found it, so do something.... If the process id is known, use "kill -0 pid" to check if the process is still running. Additional, you may need to check if it's coring even the return value of the kill command is not 0. From oren-py-l at hishome.net Mon Dec 22 19:41:38 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 22 Dec 2003 19:41:38 -0500 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <21bb8d55.0312221204.51d86182@posting.google.com> References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: <20031223004138.GA74266@hishome.net> On Mon, Dec 22, 2003 at 12:04:21PM -0800, Stormbringer wrote: > Hi, > > Given a string s and a char c, is there a short & elegant way to > determine how many consecutive occurences of c are in the beginning of > s ? > > For example if s = ">>>>message1" and c = ">" then the number I am > looking for is 4 (the string begins with 4 '>'). re.match('>*', s).end() Oren From simonb at webone.com.au Mon Dec 22 21:38:59 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 23 Dec 2003 13:38:59 +1100 Subject: How do I test if an object is a sequence? References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: On Mon, 22 Dec 2003 15:11:55 +0100, Max M wrote: > Is there a common idiom for testing if an object is a sequence? > > Both list, tuple and non-standard objects etc. I have Googled, but didn't > find a usable answer. > > > There are a few direct approaches: > > > def is_sequence(unknown): > return type(unknown) = type([]) or type(unknown) = type(()) > return type(unknown) in (list,tuple) this works in python 2.2 for me. I don't use a function for it tho. Simon Burton. From xavim at fqingenieria.es Tue Dec 9 12:08:50 2003 From: xavim at fqingenieria.es (Xavier Martinez) Date: Tue, 9 Dec 2003 18:08:50 +0100 Subject: regex confusion References: Message-ID: <00c701c3be77$1f24d8c0$0102a8c0@xavim> John Hunter wrote: > In trying to sdebug why a certain regex wasn't working like I expected > it to, I came across this strange (to me) behavior. The file I am > trying to match definitely contains many instances of the letter 'a', > so I would expect the regex > > rgxPrev = re.compile('.*?a.*?') > > to match it the string contents of the file. But it doesn't. Here is > a complete example > > import re, urllib > rgxPrev = re.compile('.*?a.*?') > > url = 'http://nitace.bsd.uchicago.edu:8080/files/share/showdown_example2.html' > s = urllib.urlopen(url).read() > m = rgxPrev.match(s) > print m > print s.find('a') > > m is None (no match) and the s.find('a') reports an 'a' at index 48. By default, the dot '.' mathches anything *but a newline*. So if there is no 'a' occurrence in the first line of the string the match will fail. If you want the dot '.' to match anything you can define your regex as: rgxPrev = re.compile('.*?a.*?', re.DOTALL) > I read the regex to mean non-greedy match of anything up to an a, > followed by non-greedy match of anything following an a, which this > file should match. > Also note that the las '.*?' is completely superfluous unless it is followed by something else. Being non-greedy means that it will much *as little as possible* as needed to match the whole pattern, and being at the end means that it can match the empty string and still make the whole pattern happy. Depending on what you are up to, it would also be wise to consider if it is possible to do it using string methods. They are quite easier to handle *and debug*. If you need to do extensive text processing in Python, there is a nice book by David Mertz, which discusses the issue (from simple string methods up to regexes and parsers) at: http://gnosis.cx/TPiP/ which might also be of help. Xavier Martinez From and-google at doxdesk.com Tue Dec 16 07:14:42 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 16 Dec 2003 04:14:42 -0800 Subject: Newbie : Gif transparency with Pil problem. References: Message-ID: <2c60a528.0312160414.7a3aabbe@posting.google.com> Gustavo Campanelli wrote: > However when I read the file and try something on it and then save it > under a new name, the transparency goes away I don't think PIL saves GIFs with transparency at all - at least it didn't last time I played with it, which is one reason I wrote this: http://www.doxdesk.com/software/py/gifWriter.html -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From jjl at pobox.com Mon Dec 22 18:49:56 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Dec 2003 23:49:56 +0000 Subject: HTML data extraction? References: Message-ID: <87k74oh0pn.fsf@pobox.com> [Sorry if this got posted twice, not sure what I did...] Dave Kuhlman writes: [...] > I'd like something that would do things like the following: > > - return the data which is inside a tag which is inside a >
  • tag. > > - return the data which is inside a tag that has attribute > href="http://www.python.org". > > - Etc. > > It would be a sort of structured grep for HTML. 1. http://wwwsearch.sf.net/bits/pullparser.py It's a port of Perl's HTML::TokeParser. p = pullparser.PullParser(f) p.get_tag("b") p.get_tag("li") print p.get_text() p = pullparser.PullParser(f) for tag in p: tag = p.get_tag("a") if dict(tag.attrs).get("href") == "http://www.python.org": print p.get_text() I'll release a beta version in a day or so with a couple of minor changes (including that .get_text() will no longer raise NoMoreTagsError) and a proper tarball package. 2. stuff your data through mxTidy or uTidylib to get XHTML, then into XPath from PyXML. http://www.zvon.org/xxl/XPathTutorial/General/examples.html In fact, tidying HTML is sometimes necessary even if you don't need XHTML or a tree-based API. 3. microdom http://www.xml.com/pub/a/2003/10/15/microdom.html Haven't used it myself. John From fredrik at pythonware.com Mon Dec 8 14:03:41 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 20:03:41 +0100 Subject: BuiltinFunctionType.__self__ References: Message-ID: Jacek Generowicz wrote: > Where can I find information on the __self__ attribute of builtin > functions ? it's the same thing as im_self, but for methods/functions implemented in C. that is, if "x" is a bound method, "x.__self__" is the object that method is bound to: >>> x = ["spam"] >>> x.count >>> dir(x.count) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] >>> x.count.__self__ ['spam'] for unbound methods (and functions), it's set to None. From davecook at nowhere.net Wed Dec 24 10:25:14 2003 From: davecook at nowhere.net (David M. Cook) Date: Wed, 24 Dec 2003 15:25:14 GMT Subject: Remembering References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Message-ID: In article <37c4fd7c.0312221002.1f4fe6d0 at posting.google.com>, MComp wrote: > Hey guys, I'm another new to programming guy. I have one quick > question. How do you make a program not forget everything you input, > once it shuts down? Thanks in advance. One (very fancy) possibility is ZODB: http://zope.org/Wikis/ZODB/FrontPage Dave Cook From matt.gerrans at hp.com Wed Dec 17 16:48:41 2003 From: matt.gerrans at hp.com (Matt Gerrans) Date: Wed, 17 Dec 2003 21:48:41 GMT Subject: filter and map / deprecated? References: Message-ID: Also, I suppose if you were *really* in a rush and wanted to get old code working, then all you'd have to do is add something like this to it: def map( func, seq ): return [ func(x) for x in seq ] def filter( func, seq ): return [ x for x in seq if func(x) ] This will probably be less efficient than Serge's solution. It is probably also better to have that self-documenting "from legacy ..." in there, to boot. I think after a using list comprehensions for a while, they become a lot more comfortable though, so it is not such a bad thing to develop the habit of using them instead. Then, in the fullness of time, map() and filter() will begin to look funny. From guettli at thomas-guettler.de Mon Dec 8 10:00:46 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 08 Dec 2003 16:00:46 +0100 Subject: More examples in the docs? Message-ID: Hi! I read "How Python is developed" (comp.lang.python.announce), and think that there could be more examples in the docs. One think I really like to see: An example with mycmp(a, b)... in the documentation for sort(). I would add DSU (Decorate, sort, undecorate) there, too. The re module would needs more examples, too. I will have some spare time around christmas. What is the best way to do this? Send patches via the patch tracker of sourceforge? thomas From claird at lairds.com Thu Dec 11 11:55:37 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 16:55:37 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7x65gn1jk5.fsf@ruckus.brouhaha.com> Message-ID: In article , John Roth wrote: . . . >And that is what is called a "real good question." I believe that >you're supposed to be able to use the Tk libraries without using >TCL, but the people that wrote Tkinter weren't able to make it >work. I don't, however, know this for a fact, it's just something >that's bouncing around the old synapses... . . . It's a choice. Perlites tried both ways, and largely settled on Perl/Tk, which uses the Tcl-free C bindings. It's much, MUCH easier maintaining a Tcl-coded applica- tion, though, so Tkinter pops out a couple of hours after a new Tk release, while Perl/Tk takes months of calendar time. Guido certainly has the ability to do a low-level binding to Tk (and I know someone did, on an experimental basis, in the mid-'90s--was that he?); he chooses to invest his time elsewhere. There's actually more to it than that. These are the right highlights, though, to the best of my knowledge. -- Cameron Laird Business: http://www.Phaseit.net From lkcl at lkcl.net Thu Dec 18 17:57:48 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Thu, 18 Dec 2003 22:57:48 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> <20031216212312.GL17021@lkcl.net> <20031218092922.GF6324@lkcl.net> Message-ID: <20031218225748.GE2234@lkcl.net> On Thu, Dec 18, 2003 at 10:33:52PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > so, with the correct codebase reordering, a simple capabilities > > based system can be added, the problem goes away. > > > > yes? > > I still don't see how it could, neither do i: i believe that the best person you should address that concern to is to greg ewing, who raised this point: "The spirit behind my suggestion was to start thinking about ways in which functionality could be separated out so that this kind of special-casing for security purposes isn't needed." in other words, i think he means that by restructuring the python codebase [and libraries? and its design?] it _may_ be possible to avoid a need for adding ACLs at all. and i believe he may be thinking along the lines of being able to permanently _remove_ at run-time, under python-programmer-control, access to __class__ from objects. somehow. > and I believe I understand pretty well > what kind of feature you propose. Restricted execution is just > something completely different. if you believe that, then i have evidently not explained myself clearly enough. i'll give this one more shot. i'll be honest with you. if it's not obvious enough at the end of this message, i have to give up and stop, and say i tried but did not succeed in explaining this clearly enough to you, which is no failing on your part, but on mine. anyway. first i should outline the pseudo-code modifications needed to Python/ceval.c which are necessary, then after that i will outline what ACLs are needed. what i _can_ say that i haven't gone into detail on [in this message] is _how_ the acls are obtained from the function object. e.g. in GetACLforFunction. but it is worth mentioning that _how_ the acls are _associated_ with the function object (or any other object) is an implementation-specific issue NOT a design / specification issue. static PyObject * call_function(PyObject ***pp_stack, int oparg) { PyObject **pfunc = (*pp_stack) - n - 1; PyObject *func = *pfunc; /* caller function name on stack below?? probably not, but the principle is at least demonstrable */ PyObject *calling_func = GetCallerFunction(*pp_stack) - n - 2; PyACL *acl_for_func = GetACLforFunction(func); ... if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_EXECUTE) { return Exception("access denied"); } ... } also, to satisfy the requirements of "capabilities", a specific check to make it look like the object doesn't exist is added. it's probably possible to have a look-up table on a per-opcode basis to look up the permissions to be checked against, which alleviates the need to put a call to check_permissions in every darn switch statement. note the check for ACL being NULL: if it's NULL, that's assumed to mean "anything goes". it also means that there's not much performance hit involved unless you actually add permissions. case STORE_ATTR: if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_CAN_SEE) { return Exception("attrib doesn't exist"); } if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_WRITE) { return Exception("access denied"); } case DELETE_ATTR: if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_CAN_SEE) { return Exception("attrib doesn't exist"); } if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_WRITE+PERMS_DELETE) { return Exception("access denied"); } case LOAD_ATTR: if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_CAN_SEE) { return Exception("attrib doesn't exist"); } if (acl_for_func != NULL && !check_permissions(calling_func, acl_for_func, PERMS_READ) { return Exception("access denied"); } basically, as long as code is only executed through eval_frame(), then it's likely to be the only place where access control checks are needed to be added. basically, therefore, once calls to restrict operations are added, it's a matter of dropping the ACLs in at the right places. _that's_ how you achieve the same job as the rexec.py code. you place an acl on __builtins__ to restrict "all functions", DENY, EVERYTHING. you place an acl on open() to restrict "all functions", DENY, FILE_WRITE. you place an acl on open.__class__ "all functions", DENY, CAN_SEE+FILE_WRITE in fact you might even be able to get away with putting an acl on EVERY function right at the top-level. but that, as described previously, means that it'd be necessary to get the "ACL-inheritance" to work properly, in order to avoid having to add a DENY FILE_WRITE acl to every single file operation capable of writing, for example. so like i said, i believe it to be a relatively simple job to spec out how to add the means _by which_ ACLs can be usefully evaluated. what i CAN'T tell you is exactly WHERE every single ACL [needed to achieve the same results as rexec] have to be added [such that they will be usefully evaluated]: i simply don't have enough knowledge of the python codebase to do that on my own. [unless someone was happy to pay me for long enough to find out, of course]. is this making sense at all? in some ways, the longer this is left, the harder it is going to be to retrospectively bolt on. there's an adage that says security cannot be easily added in, it has to be designed in from the start. fortunately, i think there are a lot of smart people about :) sincerely, l. From ben at adversary.org Sun Dec 21 03:56:21 2003 From: ben at adversary.org (Ben McGinnes) Date: Sun, 21 Dec 2003 19:56:21 +1100 Subject: What's going on with python.org In-Reply-To: ; from aahz@pythoncraft.com on Sat, Dec 20, 2003 at 12:20:46AM -0500 References: <56f42e53.0312192013.333cfeef@posting.google.com> Message-ID: <20031221195621.I12130@devious.adversary.org> Aahz(aahz at pythoncraft.com)@Sat, Dec 20, 2003 at 12:20:46AM -0500: > In article <56f42e53.0312192013.333cfeef at posting.google.com>, > sebb wrote: > > > >Just want to know why python.org is down. > > Tell your DNS provider to do a reload. Given it was just a slightly broken re-delegation, it's more feasible for most people to have waited for usual DNS propagation than try to convince their upstreams/ISPs to reload their DNS servers for one non-local domain's benefit. Most ISP staff would take one look at such a request and snicker. Alternatively, if one uses some form of *nix, there are at least a couple of ways to get around this. Regards, Ben -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 181 bytes Desc: not available URL: From jjl at pobox.com Tue Dec 2 07:22:56 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Dec 2003 12:22:56 +0000 Subject: comparing nan "number" References: <87vfp01muq.fsf@pobox.com> Message-ID: <874qwjfly7.fsf@pobox.com> Michael Hudson writes: > jjl at pobox.com (John J. Lee) writes: [...] > > I suppose: > > > > NAN = any_calculation_that_returns_nan() > > > > if some_other_calculation() is NAN: > > ... > > I wouldn't expect that to work. Unfortunately, I don't think there is > a reliable way. [...] Yeah, I forgot nan is a floating point value, not a special Python thingy like None, duh (thanks Alexander). John From hokiegal99 at hotmail.com Tue Dec 23 08:52:12 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 08:52:12 -0500 Subject: Count Files in a Directory In-Reply-To: References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: Robin Munn wrote: > I wonder if symlinks or hard links might account for the difference? > > Here's an idea: modify your script to print (on stdout) the name of each > filesystem object found. Do the same with the OS's functions. Then > compare the two. I.e., on a Unix system, something like: > > (Modify Python script to print full paths to stdout) > python myscript.py /some/path > python_file_list.txt > find /some/path -print > find_file_list.txt > sort python_file_list.txt > python_file_list_sorted.txt > sort find_file_list.txt > find_file_list_sorted.txt > diff -u find_file_list_sorted.txt python_file_list_sorted.txt > rm find_file_list*txt python_file_list*txt > > That should tell you precisely which file is being found by the Python > script but isn't being found when you get the OS to do the work. > This is very good. I will test it out today. Not sure exactly where the difference is coming from. I noticed last night that when the script is ran as root that Python counts many more files than the OS does... maybe it is a permission issue too. Thnaks again!!! From bokr at oz.net Fri Dec 12 01:10:41 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Dec 2003 06:10:41 GMT Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: On Tue, 09 Dec 2003 01:06:09 +1300, David McNab wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >Hi, > >I've just built a framework which allows mountable linux filesystems to >be implemented in pure python. > >It consists of a back-end to LUFS (lufs.sf.net), and is available from >http://www.freenet.org.nz/python/lufs-python > >Simple to use - after adding the pythonfs code to LUFS, and >building/installing, one only needs to copy the template.py python >module and flesh out the methods in the Filesystem class. Generous >docstrings spell out exactly what is needed. > Thanks for the link. Maybe it can help if I ever get to trying some of the ideas in http://groups.google.com/groups?selm=begle0%241fs%240%40216.39.172.122 I think using a vfs as an interface to windows/widget hierarchy would be particularly interesting. And if the package noticed the difference between opening a widget-as-file in binary vs text mode, one could have efficient marshalled packed data formats a la cpickle to define and initialize GUI structures, as well as text interfaces for interactive noodling. If it could be built on top of a low level video HAL a la frame buffer or maybe simulated via directx or such, it could be interesting. If there was system support so that different processes could open differently owned GUI subtrees from a shared "desktop" root, that you could switch between like F-keys on linux between console windows, it might also lead to a different way of handling user login/access control, and ... ramble, ramble ;-) It would also make an interesting interface for output of graphic formats, whether graphs and plots, or thin wrappers around pdf/postscript/svg/latex/windows-metafile/etc static formats, not to mention smil and multimedia etc. Regards, Bengt Richter From hwlgw at hotmail.com Sat Dec 20 11:57:35 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 20 Dec 2003 08:57:35 -0800 Subject: PNG to EPS with Python? References: Message-ID: > [Just] > Have you looked at PIL yet? No, I had not, and thank you for the suggestion Just! WOW, PIL is amazing! I was looking all over the internet for "png2eps" etcetera, but my favorite programming language can do it all with PIL! A simple recipe to put a screenshot in your LaTeX file under Windows (where there is no png2eps utility): First of all you have to install PIL, get the Windows .exe and run it, nice and simple. Then copy the screenshot to your Windows clipboard with or whatever keycombo your keyboard has. Then open MSPAINT.EXE, "paste" the image in there (via the Edit menu) and "save as" a .PNG file via the File menu (for name I filled in "myscreenshot"). Then open CMD.EXE and go to the directory where you did save the .PNG and start the Python interpreter there. Now just >>> import Image >>> im = Image.open("myscreenshot.PNG") >>> im.save("myscreenshot.eps") This produces a hefty 9MB .eps file for my test screenshot, but when you include it in your LaTeX with \includegraphics[width=\textwidth]{myscreenshot.eps} and produce PDF from the LaTeX (witht the MikTeX dvipdfm.exe) it amounts to only about 90k for a PDF file with one page with the screenshot on it. If you produce .PS from the LaTeX then it is still 9MB :-) From danb_83 at yahoo.com Thu Dec 25 01:54:37 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 Dec 2003 22:54:37 -0800 Subject: arguments problem~ References: Message-ID: black wrote in message news:... ... > i coded a class say named "A" which can receive arbitrary arguments and all > works fine but problem came when i created another class "B" which > inherited "A". it can not receive arguments as expected, ie it collected > keywords arguments to nonekeywords arguments tuple and keep keywords dict > empty. My destination is just to pass all keywords from A to B without any > modification and same does nonekeywords. below is my code, I'd much > appreciate if anyone could inspires me, thanx~ > > class A: > def __init__(self, *args, **kw): > print args > print kw > print > class B(A): > def __init__(self, *args, **kw): > A.__init__(self, args, kw) The above line should be A.__init__(self, *args, **kw) From claird at lairds.com Fri Dec 26 12:11:58 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 26 Dec 2003 17:11:58 -0000 Subject: dynamic typing question References: Message-ID: In article , Jason Tesser wrote: . . . >>5. In writing, "the GUI is clunky" about >> Java, what do you mean? Are you refer- >> ring to a particular IDE, or a specific >> GUI toolkit? Java has several of each; >> perhaps alternatives would suit you >> better. > >Java's main gui. Swing it is slow. . . . Slow in development or deployment? Is there a chance SWT would serve you better? Are you sure a Web application can't meet your requirements? -- Cameron Laird Business: http://www.Phaseit.net From MidasOneTwo at hotmail.nospam.com Sat Dec 27 16:37:07 2003 From: MidasOneTwo at hotmail.nospam.com (Midas) Date: Sat, 27 Dec 2003 21:37:07 GMT Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> Message-ID: <3fedf97e.54680044@news.iprimus.ca> Thanks for replying. It looks like you hardcoded the name ObjectB within ClassA. I'd like to avoid all hardcoding of names. In other words, I'd like ObjectA to be *told*, at run time, which object to call and which method to call. On Sat, 27 Dec 2003 21:42:05 +0100, Lawrence Oluyede wrote: >You could simply do something like this: > >class A: > def __init__(self): > self.ObjectB = B() > >class B: > def someMethod(self): > pass > >if __name__ == "__main__": > ObjectA = A() > ObjectA.ObjectB.someMethod() From abhjrpe at comcast.net Tue Dec 30 19:55:35 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Tue, 30 Dec 2003 19:55:35 -0500 Subject: GO AHEAD -MAKE ME LOOK DUMB- Please Message-ID: <2_ednbq16ZkVg2-iRVn-iQ@comcast.com> I have exhausted places to look for where "PYTHONPATH" is located.. In windows (using the DOS command) no such thing exist but path does. I find no file with that name. I have yet to find a config file that I would think might work as PYTHONPATH. What am I missing? Thanks Aubrey From martin at v.loewis.de Thu Dec 4 02:28:16 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Dec 2003 08:28:16 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: "Mike C. Fletcher" writes: > AFAIK, that's the plan. IIRC, rationale was that there would be some > other type for 8-bit data, while all "normal" strings would become > Unicode strings. No. will remain a byte string type for any foreseeable future. The only change that is likely to happen is this: To denote bytes > 128 in source code, you will need to use escape codes. A change that might happen in the future is this: A string literal does not create an instance of , but an instance of . However, IMO, this should only happen after a syntax for byte string literals has been introduced. > >I'm very unimpressed with this decision if that's the case. > > > Doesn't make me ecstatic, either, as I like the simple 8-bit-clean > string type. But maybe we'll luck out and it will turn out that I'm > all wet on this one :) . The byte string type is not going away. It is a useful type, e.g. when reading or writing to or from a byte stream. Regards, Martin From fumanchu at amor.org Fri Dec 19 14:50:27 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Dec 2003 11:50:27 -0800 Subject: Simple Recursive Generator Question Message-ID: Probably not what you meant, but one of the things you're missing is that generators nullify the need for recursion in this case: def big(mask): index = 0 while True: if mask == 0: break if mask & 0x1: yield index index += 1 mask = mask >> 1 >>> for x in big(0x16): ... print x ... 1 2 4 The generator saves you having to pass the "index" param recursively. You save both object memory size (only one 'index' and one 'mask' object and their bound names) and function-calling overhead (stack space). Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: MetalOne [mailto:jcb at iteris.com] > Sent: Friday, December 19, 2003 11:14 AM > To: python-list at python.org > Subject: Simple Recursive Generator Question > > > I am trying to write a generator function that yields the > index position > of each set bit in a mask. > e.g. > for x in bitIndexGenerator(0x16): #10110 > print x > --> 1 2 4 > > > This is what I have, but it does not work. > Changing yield to print, shows that the recursion works correctly. > > def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) > > What am I missing? > -- > http://mail.python.org/mailman/listinfo/python-list > From mnations at airmail.net Fri Dec 19 17:47:39 2003 From: mnations at airmail.net (Marc) Date: 19 Dec 2003 14:47:39 -0800 Subject: Hiding console with program compiled in PY2EXE References: Message-ID: <4378fa6f.0312191447.29baeef7@posting.google.com> Thanks to all the replies. I tried it using the --windows option, but I get the same problem. However I'm also increasing the difficulty a little bit by using COM with py2exe. Here's my setup file: # setup.py from distutils.core import setup import py2exe setup(name="CCT", scripts=["CCT.py"], ) Here's the command I use to initiate the process: python setup.py py2exe --progid "Excel.Application" --windows It appears to compile successfully, but I get the same problem as I did when inserted my program with the .pyw option. It starts to open, then dies. Does adding other options, such as COM, interfere with this process? Does COM need the window for some reason? Thanks, Marc From http Thu Dec 18 22:01:24 2003 From: http (Paul Rubin) Date: 18 Dec 2003 19:01:24 -0800 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: <7x1xr133zv.fsf@ruckus.brouhaha.com> Glen Wheeler writes: > My program uses many millions of integers, and Python is allocating > way too much memory for these. I can't have the performance hit by > using disk, so I figured I'd write a C extension to define a new type. > Problem is, my C knowledge is years old and regardless of my > attempts distutils will not recognise my installation of the MS > compiler. > I am thinking, is there any easier way to use a 5 or 6 bit integer > in python? Even a regular 8-bit would be fine. I only need to > represent either 32 or 64 distinct numbers. Look at the docs for the array module. From gherron at islandtraining.com Tue Dec 16 21:23:24 2003 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 16 Dec 2003 18:23:24 -0800 Subject: Can someone please send me a copy of spread.pyd Message-ID: <200312161823.24745.gherron@islandtraining.com> Hi list, Can someone who has built the SpreadModule on a windows machine please send me the results of the build (or just point me an a binary distribution). Here's why: I'm starting to use the spread library (www.spread.org) in Python via the SpreadModule (http://www.python.org/other/spread/). The SpreadModule builds fine on Linux, but on my windows box, distutils quits when it notices that Python is built with version 6 of Visual Studio whereas I've got version 7 installed on my machine. I've got two choices: (1) rebuild Python, win32all, the spread library, the whole GTK suite, and whole bunches of other extension modules with my copy of Visual Studio 7 (yuck, yuck, YUCK!) , or (2) hope someone can ship me a (version 6 compiled) binary. Clearly option (2) is preferable. If the Linux build is any indication, the windows build will result in a single file (probably) named "spread.pyd". Thanks ever so much if you can send me a copy, Gary Herron From ramen at lackingtalent.com Fri Dec 19 12:53:41 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 19 Dec 2003 17:53:41 -0000 Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> <93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: In article , Thomas Heller wrote: > Dave Benjamin writes: > >> In article , >> Fredrik Lundh wrote: >>> A console program may use the Windows API to disconnect from the >>> console, or create a window, and a window program may use the API to >>> create a console if it needs one (a version of pythonw that did this >>> if/when the application prints to sys.stderr would be quite useful, >>> btw) >> >> Yes! Especially if it paused afterwards, so you could actually read >> the error message! Speaking of which, is there any way to keep the >> console window on the screen after double-clicking on a .py file so >> that syntax errors don't result in a spead-reading test? > > Several I can think of. > > - untested, but you get the idea: > > try: > main() > except: > import traceback > traceback.print_exc() > raw_input() This is the sort of thing I usually do, but it doesn't catch syntax errors. I wind up in this state of self-conflict, unsure if I should just run the program again, and read really fast (which rarely works, because it always runs faster the second time) or if I should just bite the bullet and open up a command window. Sometimes, it takes me awhile to recover. ;) > - set the PYTHONINSPECT env variable during runtime I didn't even know it existed. =) > - or even fire up the debugger when a problem occurs: > > Cool! > And, by the way, py2exe 0.5 (still officially unreleased and > undocumented) created console-less programs automatically write > exceptions into a logfile. Can py2exe produce a custom Python interpreter? Kind of like how freewrap did this with Tcl, where your "wrapped" program could be used as an interpreter to run other scripts in an environment of your choice? Thanks for the info. -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From fedor at mailandnews.com Tue Dec 9 13:47:48 2003 From: fedor at mailandnews.com (Fedor) Date: Tue, 9 Dec 2003 19:47:48 +0100 Subject: online examination system References: <425cc8d1.0312090932.697fd6c6@posting.google.com> Message-ID: <3fd618d1$0$108$3a628fcd@reader2.nntp.hccnet.nl> Have you looked at http://zope.org/Wikis/zope-edu? Fedor "mir nazim" wrote in message news:425cc8d1.0312090932.697fd6c6 at posting.google.com... > hi there, > One of my client needs a computer based examination system. It should > have following capabilities. > > 1. It should support Multiple choice questions. > 2. It should be adaptive, that is, difficulty should vary with each > question. > kind of those used in MCSD/MCSE/SCJP etc examinations. > 3. should be web based. > 4. MySQL support. (better be Database independent) > 5. OS independent. > > Now please let me know if there is one available for ZOPE platform. > blesses-n-luck From __peter__ at web.de Fri Dec 5 13:42:22 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Dec 2003 19:42:22 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Jeff Epler wrote: > On Wed, Dec 03, 2003 at 06:07:08PM -0800, Jimmy Retzlaff wrote: >> My solution used threads. I'd love to know if someone comes up with a >> solution not involving threads. Here's a simple example of my >> thread-based approach: > [...] > > In standard Python, this is the only approach that can work. It's > possible that Stackless Python might provide a solution that doesn't > involve OS threads, but I don't have any actual experience with > Stackless. > > One problem with your code is the use of a sentinel value. Another > poster suggested using multiple queues and a timeout to return > exceptions or end-of-queue. Instead, you should use a queue but insert > easily distinguishable items in it. For instance: > None: end of iterator, raise StopIteration > (0, a, b): exception in f, raise a, None, b (re-raise exception) > (1, blah): callback got blah, return it from next() > > > import sys, Queue, threading > > class CallbackGenerator: > def __init__(self, func, pre=(), post=()): > self.func = func > if type(pre) is not tuple: pre = (pre,) > if type(post) is not tuple: post = (post,) > self.args = pre + (self.cb,) + post > self.queue = Queue.Queue(maxsize=1) > self.thread = threading.Thread(target=self.go) > self.thread.start() > > def __iter__(self): return self > > def next(self): > item = self.queue.get() > if item is None: > raise StopIteration > if item[0] == 0: > raise item[1], None, item[2] > else: > return item[1] > > def go(self): > try: > self.func(*self.args) > except: > info = sys.exc_info() > self.queue.put((0, info[1], info[2])) > else: > self.queue.put(None) > > def cb(self, *args): > self.queue.put((1, args)) > > # Example 1: os.path.walk -> generator > import os > for i in CallbackGenerator(os.path.walk, "/tmp", None): > print i > > # Example 2: Prints 1, 2 then shows a traceback > def f(cb): > cb(1) > cb(2) > 1/0 > > for i in CallbackGenerator(f): > print i Your code looks far more concise than mine. However, it suffers from the same problem: # nasty example maxRepeat = 0 for i in CallbackGenerator(os.path.walk, "/tmp", None): if maxRepeat == 0: break print i maxRepeat -= 1 How do you handle the case where the generator is not run to exhaustion? Peter From Samwatson at yahoo.com Mon Dec 8 20:10:37 2003 From: Samwatson at yahoo.com (Sam Watson) Date: Mon, 08 Dec 2003 20:10:37 -0500 Subject: Building a new app in python and need some architecture advice. References: <3fd51ecb$0$210$e4fe514c@news.xs4all.nl> Message-ID: <2v7atvkja4e7gd54sualt1d1jjprh9v0sg@4ax.com> >What do you mean exactly with "across the web"? Over HTTP? Port 80? >"in a secure fashion": SSL? Encrypted? Authentication? Authorization? >So many options ;-) > I dont know exactly what i mean :) It doesnt matter to me as long as its secure. I dont really need stateless because this thing aint gonna scale past 10 users and keeping state solves a bunch o problems. >Yes. Pyro has support for secure custom connection >validators that can be used to authorize clients to connect >(by using an authentication mechanism of your own choice, >for instance login+password based, or with secure hashes,...). >You can also run Pyro over SSL if you want encryption. >(although I must say that it's been a long time since I >did this, so it might or might not work. If I have some >spare time, I'll check the SSL stuff, but I'm too busy >with other things at the moment). > It sounds like pyro may do the trick here. The thing it would seem I would be losing with pyro is the ease of iterating and linking maps and lists of objects. Can I do this transparently with pyro? I'll investigate further. Thanks for the help! >> Twisted (Is this overkill?) >Don't know, depends on your type of server application I guess. > its nothing special. your basic data entry app with some minor reporting. Simple as it gets. >> Pure sockets (a lot of infrastructure to write but im pretty >> experienced with it) > >Why write it when you don't have to (see other options). > The only reason I would write it myself would be control, performance, and ultimate flexibility. It doesnt seem very pythonish tho. From ville.spammehardvainio at spamtut.fi Sat Dec 20 12:17:17 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Dec 2003 19:17:17 +0200 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" writes: > Notice that there is only one polarity here: Perl vs Python. Ruby goes > meta on the discussion in that it looks at what the customer (the developer) > *wants*, rather than what the language designer thinks they should have. Customer is often less informed than the language designer. I think someone mentioned somewhere that Perl is a "popularity whore", I guess the same applies to Ruby. I can rest assured that Python won't start decaying because the language designers wanted to please the whims of some members of the audience. > Most businesses would look at a competitor who is stealing customers > as an opportunity to figure out what those customers want that they > aren't getting. Fair enough. Someone might want to compile a list where the issue could be dissected once and for all. A lot of the issues rubyists have tend to be along the lines of "well, Python has this feature *now*, but it wasn't in version blah blah when I tried it. We had it since the beginning, so it is not an add-on but a real feature!". IOW, they fall apart w/ even a minor analysis. > and in the case of list comprehensions, pretty darned useful although > I think that it's a rather baroque addition to an otherwise very clear > and comprehensible language. List comprehensions are, for me, one of the killer features in Python that raise Python above all other languages (Haskell has them, but it's.. umm.. Haskell and one would be laughed out of the office if he suggested Haskell for implementing anything). > There is no replacement for lambda in sight, even though lambda is > arguably the ***largest single*** one of the functional constructs > that needs work, and has obviously needed work for a long time. Party line is that ppl should just define a function with a name. It might not be the most comfortable option at the time of writing the code, but it will make the program more readable. It is definitely not a big enough of a problem to switch the language. Hmm, I wonder if it is the time to start crossposting this to c.l.ruby and let the flamewar start. It's been a while already ;-). -- Ville Vainio http://www.students.tut.fi/~vainio24 From ameLista at telia.com Mon Dec 1 13:03:35 2003 From: ameLista at telia.com (Anders Eriksson) Date: Mon, 01 Dec 2003 18:03:35 GMT Subject: SGMLParser eats ä etc References: <87he0mn0c7.fsf@pobox.com> Message-ID: <19cbe1rfd2rx$.dlg@amez.homeip.net> On 30 Nov 2003 00:53:28 +0000, John J. Lee wrote: > You probably want to use HTMLParser.HTMLParser instead (NOT the same > thing as htmllib.HTMLParser, note). It knows about XHTML, sgmllib & > htmllib don't. å etc isn't XHTML, is it? AFAIK it is defined in HTML 4. the strange thing is that the Character entity (i.e. å) is stripped from the text. I don't want to change it since I'm feeding the output to a browser. I will try the HTMLParser instead but it seems to me that there is a bug in SMGLParser... // Anders From tim.one at comcast.net Fri Dec 19 23:34:44 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Dec 2003 23:34:44 -0500 Subject: What's going on with python.org In-Reply-To: <56f42e53.0312192013.333cfeef@posting.google.com> Message-ID: [sebb] > Just want to know why python.org is down. It's not down. The domain name is in the process of being transferred from CNRI to the Python Software Foundation, though, and maybe the nameservers along your network path need more time to see the changes in details. If so, it will fix itself soon by magic. From art at wiktorsadowski.com Thu Dec 18 22:30:53 2003 From: art at wiktorsadowski.com (Wiktor Sadowski) Date: Fri, 19 Dec 2003 04:30:53 +0100 Subject: pymozilla ([Python-Dev] RELEASED Python 2.3.3 (release candidate 1) - custom Py_Initialize()) Message-ID: <038901c3c5e0$81b7fa10$0201010a@kret> [Brad Clements wrote] >I'd like to find out more about pymozilla.. It sounds very interesting pymozilla is is a proprietary application so I can't share the code. It's a modified python.exe with builtin Browser module - Python wrapped Gecko engine. Custom nsIProtocolHandler and zip-file-system Python module is used to get and load files(html,xml,css,images,Python code) from zip and to resolve and process all ".py" links and html forms. It's pretty like CGI, but no server is required. The main problem was to have it run from CD (client requirement) without installing anything (Mozilla/Python) Wiktor From yan at NsOeSiPnAeMr.com Sat Dec 13 07:18:04 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 13 Dec 2003 07:18:04 -0500 Subject: "Do this, and come back when you're done" Message-ID: I have the following function which generates MD5 hashes for files on a local and remote server. The remote server has a little applet that runs from inetd and generates an MD5 hash given the file name. The problem is that it takes 2+ minutes to generate the MD5 hash, so this function takes about 5 minutes every time it is called. Since the first MD5 hash is generated on a remote machine, the local machine does nothing but wait for half that time. Is there any way to rewrite each half of the function to run in the background, so to speak, and then have a master process that waits on the results? This would cut execution time in half more or less. # checkMD5 def checkMD5(fileName, localDir): # get remote hash Socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) Socket.connect((MD5server,888)) #throw away ID string Socket.recv(256) Socket.send(fileName+'\n') remoteMD5hash = Socket.recv(256) # get local hash try: file=open(makeMovieName(localDir,fileName), 'r') except IOError: localMD5hash = '0' else: hasher = md5.new() while True: chunk = file.read(1024) if not chunk: break hasher.update(chunk) localMD5hash = hasher.hexdigest() if Debug: print "local:",localMD5hash, "remote:",remoteMD5hash return localMD5hash.strip() == remoteMD5hash.strip() -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From andymac at bullseye.apana.org.au Sun Dec 28 04:32:00 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 28 Dec 2003 20:32:00 +1100 (EST) Subject: 2.3 list reverse() bug? In-Reply-To: <200312280953.17500.aleaxit@yahoo.com> References: <20031228091057.V12838@bullseye.apana.org.au> <200312280953.17500.aleaxit@yahoo.com> Message-ID: <20031228201837.G26020@bullseye.apana.org.au> On Sun, 28 Dec 2003, Alex Martelli wrote: > Close enough, for me, that the words "essentially equivalent" appear > to be quite justified. I realised after sending that I should have qualified my comment, as the performance differential of course disappears into the noise as the number of elements increases. For lists of 10s of elements and fewer, the slice has a noticeable advantage over the other 2. It is also a fair question whether any useful algorithm would be noticeably affected by the performance difference. Raymond Hettinger's work on a function/method for returning sorted lists will further reduce the need for the shallow copy as a specific operation. Regards, Andrew. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bkc at Murkworks.com Mon Dec 8 11:28:45 2003 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 8 Dec 2003 11:28:45 -0500 Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: I used a cvs checking. py2exe/__init__.py has this: __version__ = "0.4.0" -- Novell DeveloperNet Sysop #5 _ "Thomas Heller" wrote in message news:fzfzt4zm.fsf at python.net... > "Brad Clements" writes: > > > "Rene Olsthoorn" wrote in message > > news:3fcf581e$0$200$e4fe514c at news.xs4all.nl... > >> Dear readers, > >> > >> py2exe has a problem including libxml2. Not at building time, but at > >> runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has > >> the problem? (and can you drop me your setup.py scipt, please). > >> > > > > Perhaps you hit the same problem I did when using libxml2 and libxslt in a > > service created by p2exe. > > > > Here are notes from my project diary (these notes are meant for my client to > > reconcile my bill vs. what I did) > > ----- > > The service builds, I can install it, but get an error when I run it: > > > > The instance's SvcRun() method failed > > File "win32serviceutil.pyo", line 663, in SvcRun > > File "UMXWIN32SVC.pyo", line 41, in SvcDoRun > > File "Rose\WebServer\UMXMServer.pyo", line 53, in ? > > File "Rose\WebServer\umx_handler.pyo", line 16, in ? > > File "Rose\WebServer\HTTPHandler.pyo", line 95, in ? > > File "Rose\WebServer\XMLProcessor.pyo", line 34, in ? > > > > exceptions.ImportError: dynamic module does not define init > > function (initlibxslt) > > > > This says that the service cannot import the libxslt module for some reason. > > > > I built a test script that py2exe runs in console mode, it also fails in the > > same way. > > > > I think libxml is using some kind of dynamic import mechanism, we need to > > work around. > > > > Aha, figured it out. example problem with libxml2. > > > > libxml2.py is a module that imports libxml2mod.pyd which imports libxml2.dll > > > > But, py2exe creates a default path like this: > > > > c:\\temp\\rose, c:\\temp\\rose\\library.zip > > > > This means that python tries to import from the directory first, before > > importing from library.zip. So, python imports libxml2.dll, not libxml2.py > > > > My workaround is to reverse the order of the imports in the startup script: > > > > zipfile = sys.path[-1] > > sys.path.insert(0,zipfile) > > Which version of py2exe are you using, and what is this libxml2? > > IIRC, in the latest version py2exe doesn't put the executable's > directory on the path anymore, but file names like libxml2.py, > libxml2.pyd, and libxml2.dll all at the same time have the potential to > confuse it! > > Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > From danmil at shore.net Wed Dec 10 17:13:27 2003 From: danmil at shore.net (Dan Milstein) Date: Wed, 10 Dec 2003 17:13:27 -0500 Subject: Experimental Macro System Message-ID: <3FD79A87.3060801@shore.net> As a way to learn more about Python (and for fun), I'm building an experimental Dylan- and Lisp-inspired Macro system for Python. I've just put up a 0.1 release on Sourceforge at: https://sourceforge.net/projects/pymac/ ...if anyone is interested. It's pretty primitive at the moment, but it is possible to write macros and use them to expand and run actual Python code. It's currently implemented as a preprocessor (written in Python). More details in the README file in the project. -Dan Milstein From paul at boddie.net Thu Dec 18 06:45:07 2003 From: paul at boddie.net (Paul Boddie) Date: 18 Dec 2003 03:45:07 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: <23891c90.0312180345.6cdda060@posting.google.com> "Brandon J. Van Every" wrote in message news:... > "Paul Boddie" wrote in message > news:23891c90.0312170334.2cee015 at posting.google.com... > > > > I'm no big fan of Sun or Java, but that's quite some industry > > leadership you're showing us, Brandon. ;-) > > *I'm* showing you? Since when was I Microsoft? Rephrasing: 1. That's quite some industry leadership you're revealing to us. 2. That's quite some industry leadership you're referring us to. 3. That's quite some industry leadership to which you're referring us. Suggestion #3 is for the "to boldly go" crowd. On the other hand, if Sherlock Holmes was in any sense accurate, perhaps you are Microsoft. ;-) > I guess your point is whether you think Java or .NET is responsible for the > interop principles of .NET. Not at all. My point was that .NET apparently got cooked up when Sun rained on Microsoft's J++ parade. A lot of old timers made comparable remarks when Java emerged back in the mid-nineties because the portable virtual machine thing has a long history and has produced a lot of compelling competitors to Java, although the Java security model does seem like a differentiator to me. > I'd say the latter, since otherwise, it would be Java and we'd all be > doing our language interop in Java. Well, I get a fair amount of mileage out of Jython, Apache Axis (SOAP) and so on, but I guess that this isn't your point. I think it is widely accepted that Java was never really made for in-process interfacing with other languages, or at least that JNI (or whatever they call it now) is "nasty". From what I see, Microsoft may have tried a bit harder on that front, and I can imagine that the Mono people have pushed it even further to leverage various components implemented in C/C++. Perhaps we will be doing all our development in .NET-related technologies in five years time. I just hope that if this is the case, Microsoft don't do a SCO and hit everyone up with $799 "licence" demands. Paul From newsgroups at jhrothjr.com Mon Dec 22 16:20:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Dec 2003 16:20:09 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <3fe7554d$0$1156$636a55ce@news.free.fr> Message-ID: "Bruno Desthuilliers" wrote in message news:3fe7554d$0$1156$636a55ce at news.free.fr... > John Roth wrote: > (snip) > > > > If a language makes opportunities for errors, then there is > > something wrong with the language that needs to be corrected. > > Lol ! Tell us when you'll find a language that do not "make > opportunities for errors". The non-existance of an example doesn't mean it isn't a goal worth striving for. John Roth > From bokr at oz.net Fri Dec 5 01:25:05 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 06:25:05 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On 04 Dec 2003 22:10:50 +0100, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >bokr at oz.net (Bengt Richter) writes: > >> >Yes, and no. Yes, characters in the source code have to follow the >> >source representation. No, they will not wind up utf-8 >> >internally. Instead, (byte) string objects have the same byte >> >representation that they originally had in the source code. >> Then they must have encoding info attached? > >I don't understand the question. Strings don't have an encoding >information attached. Why do they have to? Depends on what you mean by "strings" ;-) One way to look at it would be because they originate through choosing a sequence of glyphs on key caps, and there has to be an encoding process between that and a str's internal representation, something like key->scan_code->[code page]->char_code_of_particular_encoding. If you put a sequence of those in a "string," ISTM the string should be thought of as having the same encoding as the characters whose ord() codes are stored. If the second line of a Python source is # -*- coding: latin-1 -*- Then a following line name = 'Martin L?wis' would presumably bind name to an internally represented string. I guess right now it is an ascii string of type str, and if the source encoding was ascii, you would have to write that statement as name = 'Martin L\xf6wis' to get the same internal representation. But either way, what you wanted to specify was the latin-1 glyph sequence associated with the number sequence >>> map(ord, 'Martin L\xf6wis') [77, 97, 114, 116, 105, 110, 32, 76, 246, 119, 105, 115] through latin-1 character interpretation. You (probably, never say never ;-) didn't want just to specify a sequence of bytes. You put them there to be interpreted as latin-1 at some point. > >> Isn't that similar to promotion in 123 + 4.56 ? > >It is similar, but not the same. The answer is easy for 123+4.56. > >The answer would be more difficult for (4/5)+4.56 if 4/5 was a >rational number; for 1 < 0.5+0.5j, Python decides that it just cannot >find a result in a reasonable way. For strings-with-attached encoding, >the answer would always be difficult. Why, when unicode includes all? > >In the face of ambiguity, refuse the temptation to guess. > >> We already do that to some extent: >> >>> 'abc' + u'def' >> u'abcdef' > >Yes, and that is only possible because the system encoding is >ASCII. So regardles of what the actual encoding of the string is, Um, didn't you say, "Strings don't have an encoding information attached. Why do they have to?" ? What's this about ASCII? ;-) >assuming it is ASCII will give the expected result, as ASCII is a ^^^^^^^^ oh, ok, it's just an assumption. >universal subset of (nearly) all encodings. > >> But there is another question, and that is whether a concrete >> encoding of characters really just represents characters, or whether >> the intent is actually to represent a concrete encoding as such >> (including the info as to which encoding it is). > >More interestingly: Do the strings represent characters AT ALL? Some >strings don't represent characters, but bytes. Again it comes down to defining terms ISTM. > >What is the advantage of having an encoding associated with byte >strings? If e.g. name had latin-1 encoding associated with it by virtue of source like ... # -*- coding: latin-1 -*- name = 'Martin L?wis' then on my cp437 console window, I might be able to expect to see the umlaut just by writing print name # implicit conversion from associated encoding to output device encoding instead of having to write print name.decode('latin-1').encode('cp437') or something different on idle, etc. Instead, there is a you-know-what-you're-doing implicit reinterpret-cast of the byte string bound to name to whatever-type-the-output-device-currently-attached-is. Definitely that is necessary functionality, but explicit might be better than implicit. E.g., one might spell it print name.bytes() # meaning expose binary data byte sequence for name's encoding. # the repr format would be like current str ascii-with-escapes and bytes = name.bytes() would result in pure 8-bit data bytes with no implied 'ascii' association whatever. (The 7-bit-ascii-with-escapes repr would only be a data print format, with no other implication). This could be followed by s = bytes.associate('latin-1') to reconstitute the string-of-bytes-with-associated-encoding > >> 1. This is a pure character sequence, use the source representation >> only to determine what the abstract character entities (ACEs) are, >> and represent them as necessary to preserve their unified >> identities. > >In that case, you should use Unicode literals: They do precisely that. Why should I have to do that if I have written # -*- coding: latin-1 -*- in the second line? Why shouldn't s='blah blah' result in s being internally stored as a latin-1 glyph sequence instead of an 8-bit code sequence that will trip up ascii assumptions annoyingly ;-) > >> BTW, for convenience, will 8-bit byte encoded strings be repr'd as >> latin-1 + escapes? > >Currently, they are represented as ASCII+escapes. I see no reason to >change that. Ok, that's no biggie, but even with your name? ;-) > >> Still, they have to express that in the encoding(s) of the program >> sources, so what will '...' mean? Must it not be normalized to a >> common internal representation? > >At some point in time, '...' will mean the same as u'...'. A Unicode interesting. Will u'...' mean Unicode in the abstract, reserving the the choice of utf-16(le|be)/wchar or utf-8 to the implementation? >object *is* a normalized representation of a character string. Sure. But it will have different possible encodings when you want to send it to another system or store it etc. > >There should be one-- and preferably only one --obvious way to do it. > >... and Unicode strings are the one obvious way to do a normalized >representation. You should use Unicode literals today whereever >possible. > >> BTW, does import see encoding cookies and do the right thing when >> there are differing ones? > >In a single file? It is an error to have multiple encoding cookies in >a single file. I didn't mean that ;-) > >In multiple files? Of course, that is the entire purpose: Allow >different encodings in different modules. If only a single encoding >was used, there would be no need to declare that. Yes that seems obvious, but I had some inkling that if two modules m1 and m2 had different source encodings, different codes would be allowed in '...' literals in each, and e.g., import m1,m2 print 'm1: %r, m2: %r' % (m1.s1, m2.s2) might have ill-defined meaning, which perhaps could be resolved by strings carrying encoding info along. Of course, if all '...' wind up equivalent to u'...' then that pretty much goes away (though I suppose %r might not be a good short cut for getting a plain quoted string into the output any more). But if s = '...' becomes effectively s = u'...' will type('...') => ? What will become of str? Will that still be the default pseudo-ascii-but-really-byte-string general data container that is is now? Regards, Bengt Richter From __peter__ at web.de Tue Dec 23 04:17:56 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Dec 2003 10:17:56 +0100 Subject: return statement in functions References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: hokiegal99 wrote: > I was told earlier (w/o explanation) that functions should return > something. I was under the impression that it was OK with Python to > leave the return statement off. Could someone enlighten me on why or > why not to use a return statement when defining functions? Below is > the bit of code I was told should return something: > > def fs_object_count(path): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > file_count += len(files) > dir_count += len(dirs) > print "Number of Files Examined: ", file_count > print "Number of Folders Examined: ", dir_count > print "Total Number of FS Objects:", file_count + dir_count I think I was the guy who told that. I did not mean that you should always add an explicit return statement, you just posted a slightly different function [hokiegal99 in earlier post] > def fs_object_count(path): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > for fname in files: > file_count += len(fname) > for dname in dirs: > dir_count += len(dname) > fs_object_count() which attempted to calculate file and dir count but did neither return these values nor print them. Thus the file_count and dir_count were lost and the function useless. As to the advantage of returning the result instead of printing it, Francis Avila has already covered that. Peter From yan at NsOeSiPnAeMr.com Tue Dec 16 07:12:33 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Tue, 16 Dec 2003 07:12:33 -0500 Subject: Cropping log files In-Reply-To: References: Message-ID: Duncan Booth wrote: > > If you can modify your requirements to say that you need to keep 'at least > n records' then rotating file logger will do that, just make sure that the > size that is kept in all files is at least n times the largest record you > might log. Of course the records will then be split across multiple files. You know, that just might work. I need more-or-less n records; the number is not critical. So, if I allow the rotating logger a max file size that accomodates approx. n/4 records, tell it to keep older files to a depth of 6, then read older log files until I get some number of records greater than n.... I just have bad experience with letting log files get to infinite length... :-) -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From duncan at NOSPAMrcp.co.uk Wed Dec 3 09:14:52 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 3 Dec 2003 14:14:52 +0000 (UTC) Subject: Python mem leaks? References: Message-ID: tomas.bouda at systinet.com wrote in news:mailman.69.1070454775.16879.python-list at python.org: > Having the two methods: > > def do_smth1(panel): > pass > > def do_smth2(panel): > raise Exception() > > Calling do_smth1() will cause returning of Py_None, the PyCObject > is freed and the C finalizer (mentioned in no.2) is called. > Calling do_smth2() will case returning NULL a is not freed nor > finalizer is called. At this point I get a leak! > > Is it my fault? I didn't find anywhere in Python doc what should C app > to do if such memory isn't freed. Seems more likely to be the Python > leaking bug! It is not your fault, but neither is it a memory leak or a bug in Python. When your function throws an exception the stack frame is held in case whatever handles the exception wants to inspect it. This extends the lifetime of all the objects references within the function until the stack frame is discarded which is not usually until another exception is thrown. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From rainerd at eldwood.com Sat Dec 20 02:30:10 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 20 Dec 2003 07:30:10 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: <6USEb.437457$ao4.1393967@attbi_s51> Rainer Deyke wrote: > def draw_pixel(x, y, color, surface=screen): > screen[y][x] = color This should of course be: def draw_pixel(x, y, color, surface=screen): surface[y][x] = color -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From amk at amk.ca Thu Dec 25 11:15:02 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 25 Dec 2003 10:15:02 -0600 Subject: Socket Programming References: <3FEAC35F.C26A14B1@alcyone.com> Message-ID: <68adnfGlDo2bkHai4p2dnA@speakeasy.net> On Thu, 25 Dec 2003 11:01:37 GMT, Kamuela Franco wrote: > Sounds quite fun then. Now onto tutorials, got any? Gordon McMillan's tutorial at http://www.amk.ca/python/howto/sockets/ may be helpful. --amk From razor-report at daimi.au.dk Sun Dec 7 12:09:36 2003 From: razor-report at daimi.au.dk (Rasmus) Date: Sun, 7 Dec 2003 18:09:36 +0100 Subject: Thanks: Best structure for (binary) trees? References: Message-ID: Thanks to all of you. I have found several good answers of implementing trees from your postings. R -- PS: Due to heavy spam reception (20.000+/week), I use a fake sender address. Please answer in the newsgroup. Thanks "Rasmus" wrote in message news:jVGAb.13860$UV7.5376 at news.get2net.dk... > Hi. > > As partly novice in python I would like a piece of advise of how to > implement (binary) trees the best way? > > Thanks in advance, > > Rasmus > > PS: Due to heavy spam reception (20.000+/week), I use a fake sender address. > Please answer in the newsgroup. Thanks > > From newsgroups at jhrothjr.com Wed Dec 3 19:58:06 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 3 Dec 2003 19:58:06 -0500 Subject: String length ... len(str) References: <3fce7c40$0$1127$6c56d894@feed0.news.be.easynet.net> Message-ID: "Bernard Delm?e" wrote in message news:3fce7c40$0$1127$6c56d894 at feed0.news.be.easynet.net... > > Why is len(str1) = 4 and len(str2) = 3? > > Because str1 is a string whereas str2 is a tuple. > Both are sequences whose size is returned by len(). > You probably meant str2 = "here" + "we" + "are" > If you ask "type(str2)" at the python prompt, you'll > see exactly what's going on. Actually, you could also have said: str2 = "here" "we" "are" and gotten the concatination. Python automatically concatinates string literals that come together. That makes it a bit easier to split a literal across lines. Admittedly, it's not the most obvious behavior, although I believe it's faster since it happens in the lexer (or the parser, but anyway at compile time). John Roth > > Cheers, > > Bernard. > From martin at v.loewis.de Wed Dec 3 18:49:15 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Dec 2003 00:49:15 +0100 Subject: How to share 3rd-party modules between 2.2 and 2.3? In-Reply-To: References: Message-ID: <3FCE767B.7010603@v.loewis.de> Matthew Wilson wrote: > I want to write some CGI scripts that use pgdb. I want to write the > python scripts using python2.3, but the pgdb.py file is in > > /usr/lib/python2.2/site-packages > > which is not part of sys.path in python2.3. What is the best way of > sharing these modules? Put the code in /usr/lib/site-python. Regards, Martin From freak at yeah.com Sun Dec 14 11:10:26 2003 From: freak at yeah.com (Joe) Date: Sun, 14 Dec 2003 16:10:26 GMT Subject: Python Cookbook question re 5.6 Message-ID: The recipe in question is "Implementing Static Methods". It shows how to use staticmethod(). This sentence in the Discussion section isn't clear to me: "An attribute of a class object that starts out as a Python function implicitly mutates into an unbound method." I'm not sure what this means, exactly. Can anyone elaborate? Thanks, Chris From bvdpoel at kootenay.com Tue Dec 30 11:45:35 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Tue, 30 Dec 2003 09:45:35 -0700 Subject: When to put my modules In-Reply-To: References: <3ff0e744_1@dns.sd54.bc.ca> Message-ID: <3ff1ab8c_1@dns.sd54.bc.ca> Yermat wrote: > Hi, > > "Bob van der Poel" a ?crit dans le message de > news:3ff0e744_1 at dns.sd54.bc.ca > >>I'm working on a moderately sized application and I'm planning on >>having a fair number of modules. The only question in my mind is: >>where do I put the modules ... and how do I let python know about >>them? > > > see http://www.python.org/doc/current/tut/node8.html especially the 6.1.1 > Okay...so I just need to add paths to the sys.path variable. Seems simple enough. Thanks. >>I could put them with the rest of the python lib, but I'm not really >>presumtious to do that. > > > Not that good... > > >>I can keep them all in the current directory, but that forces the user >>to chd to a certain location all the time. >> >>Best, I think, is to put them in a program specific location. My >>program needs some other data files, etc. so I'm thinking that I can >>just put the python stuff in /usr/local/lib/MYPROGRAM/modules. > > > Not that good too. You may want to re-use your module later in another > program... > Well, probably not. The modules I'm talking about here are pretty specific to my program. >>Okay, but what about when I'm just working on them? In this case I'd >>like them to be in my current working dir. >> >>Is there a magic line I need to add to the top of the main module to >>set the path up? >> >>Apologies if this is covered in a document...but I can't see to find >>anything. Maybe this is a faq? > > > What I'm doing is something like this : > All my module are in a directory such as /home/loic/MyPython/. > I set the PYTHONPATH to that directory. > I've got for example a module rtf in /home/loic/MyPython/rtf/, another one > Heredis in /home/loic/MyPython/Heredis and my program is in > /home/loic/MyPython/Heredis2Gedcom for example. > In that way, I don't mix my module with standard one. Every program can > access all non program specific module. > > For other tips, look at sys.path too. > > Hope it help ! > Yermat Yes, it does help. Just to clearify, the program I'm working on will be distributed to other users. So, putting the modules in a my-personal-python-stuff directory isn't really an option. They most likely need to go in the main python tree (which, again, I don't like), or in a program specific directory. Setting PYTHONPATH is an option, but I don't like to force a user to set an env variable just to run my program. Yes, I could turn my prog into a shell script which sets the variable, and then runs the *real* program, but I always find that method to be a bit convoluted. > -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From birdiepageANTI at SPAMciudad.FILTERcom.ar Fri Dec 19 11:24:39 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Fri, 19 Dec 2003 13:24:39 -0300 Subject: dynamic typing questions In-Reply-To: References: Message-ID: Jason Tesser wrote: > OK what are your guys thoughts here? How have you all > overcome the lack of static typing? Is Python a > bad decision here? By the way we will be using > Postgres in the back if that matters to anyone. I have no problems with dynamic typing, but it seems that this comes as a big problem to you. My advice, since you are two, is that you agree on something that makes your life easier in the future, like to keep a record of every declared variable, or that you agree on a naming policy, like starting every int name with i (icounter) and every float with f (fmeasure) while you get used to the dynamic typing. This way you'll have an easier time catching and, more important, avoiding the errors. But I think that once you get used to Python and it style, you won't miss static typing at all. Gedece From kokoska.jan at globe.cz Fri Dec 5 09:46:30 2003 From: kokoska.jan at globe.cz (Jan Kokoska) Date: Fri, 05 Dec 2003 15:46:30 +0100 Subject: How to tell the difference between string and list Message-ID: <1070635589.841.8.camel@marigold> Hello, I need to recognize 'var' and ['var'], usually I would use: if a.__class__() == '': #string elif a.__class__() == []: #list But unfortunately in Zope PythonScripts, where I need to use this, one is not supposed to use underscore-prefixed methods as I just found out. I figure this is a question general enough to post here (and not on the Zope list), any clues? TIA Jan Kokoska From aahz at pythoncraft.com Tue Dec 2 21:14:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2003 21:14:46 -0500 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> Message-ID: In article <7xznedqxyx.fsf_-_ at ruckus.brouhaha.com>, Paul Rubin wrote: > >Can someone using spambayes tell me about how fast it runs? I'm using >Spamassassin right now but it takes around 1.5 seconds to process a >message on a 2 ghz Athlon. I believe part of that time is spent doing >network lookups to check the source addresses against various spam >blacklists. I want to crunch through several gigabytes of spam >folders to see if any legitimate messages got trapped, so need a fast >classifier with a low false negative rate (it's ok if the false >positive rate isn't so low, since almost all the messages in these >folders are already spam). Maybe I shouldn't tell you this so you're forced to use a Python app, but you can either disable the network checks or run spamd. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From anton at vredegoor.doge.nl Wed Dec 3 14:31:18 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 03 Dec 2003 20:31:18 +0100 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> <3fcc9577$0$7676$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <3fce3a5f$0$9539$3a628fcd@reader2.nntp.hccnet.nl> On 3 Dec 2003 09:07:04 -0800, lutz at rmi.net (Mark Lutz) wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:<3fcc9577$0$7676$3a628fcd at reader1.nntp.hccnet.nl>... >> there seems to be no such thing as Tkinter on any pda. > >Actually, I should have done a bit of googling on >this myself, before responding on the Tkinter issue >yesterday. You can find information about running >Tk on the Zaurus here: > >http://wiki.tcl.tk/zaurus > >Still not a simple task, but it looks possible. It looks >like you'll need to get X and Tk running in one of a variety >of ways, and will probably also need to compile Python's Tk >interface module to get Tkinter to work. Again, if I had an >infinite amount of time... Yes sorry, my statement was too strong. On Windows CE machines Tkinter seems to be even more common. Thanks to you and Rob for correcting me. Hmm, I seem to have a lot of time and very little money, maybe we can work something out? Just kidding :-) Anton From shuvit at 127.0.0.1 Tue Dec 2 14:42:40 2003 From: shuvit at 127.0.0.1 (David MacQuigg) Date: Tue, 02 Dec 2003 12:42:40 -0700 Subject: calling programs from python References: Message-ID: On Tue, 02 Dec 2003 16:02:26 GMT, Kristofer Wouk wrote: [...] >import os >os.popen('command > file') This is a little confusing. Do you intend the output from 'command' to go to 'file' or to the pipe you just opened? If you are opening a pipe (to be read as a file object) I would suggest something like this: >>> import os >>> file = os.popen('cat makefile | grep pyuic') >>> file.readlines() ['\tpyuic ModelSelector.ui > ModelSelector.py\n'] If you are just executing a command and not needing to process any output from the command (other than its completion status), I would stick with the more general: >>> import os >>> status = os.system('command > file') >>> status >>> 0 >>> --Dave From shuvit at 127.0.0.1 Mon Dec 1 23:13:45 2003 From: shuvit at 127.0.0.1 (David MacQuigg) Date: Mon, 01 Dec 2003 21:13:45 -0700 Subject: calling programs from python References: Message-ID: On Mon, 01 Dec 2003 19:27:34 -0500, "RR" wrote: >Hello, > >I am trying to call a program in python as I would call it in the command >line. For example I want to do the following from python: command > file. >Then read this file. How do I call "command > file" ? Much help >appreciated. Use os.system() For example, on Unix: >>> import os >>> os.system( 'command > file' ) and on Windows: >>> os.system('start C:\Python23\python.exe') -- Dave From donn at u.washington.edu Tue Dec 16 13:01:26 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 16 Dec 2003 10:01:26 -0800 Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: In article , "J.R." wrote: > Thanks for the response. > > I got following conclusion after reading your reply and other documents: > > Actually, the python is passing the identity (i.e. memory address) of each > parameter, and it will bind to a local name within the function. That should work. This notion of binding a object to a name or data structure is all over Python, as you have probably noticed, and it will be time well spent if you experiment with it a little. For example, how could you verify that arrays are passed without copying? Unless you are unusually dense for a programmer or have no access to a Python interpreter, that could be no more than a couple of minutes work. As penance for having failed to do this, I assign a more mysterious problem to you: def f(d=[]): d.append(0) print d f() f() Explain results. When is d bound? Here's an easier one: a = {'z': 0} b = [a] * 4 b[0]['z'] = 1 print b If the result is anywhere near a surprise to you, then you would do well to stick to this line of inquiry if you want to do anything more than the most trivial Python programming. Donn Cave, donn at u.washington.edu From vincent at visualtrans.de Mon Dec 22 16:31:23 2003 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 22 Dec 2003 22:31:23 +0100 Subject: Counting how many chars equal to a given char are in the beginning of a string References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: "Stormbringer" schrieb im Newsbeitrag news:21bb8d55.0312221204.51d86182 at posting.google.com... | Hi, | | Given a string s and a char c, is there a short & elegant way to | determine how many consecutive occurences of c are in the beginning of | s ? | | For example if s = ">>>>message1" and c = ">" then the number I am | looking for is 4 (the string begins with 4 '>'). How about: def getc(s, c): """ Get the number of consecutive occurrences of given char c at the beginning of given string s. """ cnt = 0 while 1: try: if s[cnt] == c: cnt += 1 else: return cnt except IndexError: return cnt c = '>' print getc(">>>>Message", c) #prints 4 print getc(" >>>>Message", c) #prints 0 print getc (">>>", c) #prints 3 Maybe not the most elegant or shortest, but it works... HTH, Vincent Wehren | | Thanks, | Andrei From pascal.parent at free.fr Wed Dec 3 06:17:54 2003 From: pascal.parent at free.fr (Pascal) Date: 3 Dec 2003 03:17:54 -0800 Subject: Remove no-printable characters in string Message-ID: Hello, What's the best way to delete or replace no-printable characters in a string. i.e.: "\x08toto\x00titi" -> "tototiti" or " toto titi" From tim.one at comcast.net Fri Dec 19 23:28:47 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Dec 2003 23:28:47 -0500 Subject: Zen of ... In-Reply-To: Message-ID: [Aahz] >> Actually, it should be called "20 Pythonic Theses", because that was >> Tim's original title. [Michael Hudson] > But there isn't a 20th thesis yet is there? I thought that was still > waiting on Guido... There are many 20th theses, but you surely don't think Guido's going to get pinned down by recording one in writing! Leaving the 20th thesis ineffable-- even unnumbered --is apparently part of God's Plan. divinely-inspired-ly y'rs - tim From http Tue Dec 23 07:59:57 2003 From: http (Paul Rubin) Date: 23 Dec 2003 04:59:57 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> Message-ID: <7x4qvrlmeq.fsf@ruckus.brouhaha.com> andreif at mail.dntis.ro (Stormbringer) writes: > I want to implement a fulltext search for messages in a forum. More > exactly for each message I store pairs (wordId, msgId) for each > identified word and when I search something I want to be able to > retrieve very quickly all msgId for a given wordId. Using any kind of database in a big message system may thrash your disk pretty badly if you update the database every time a new message is entered. That means making hundreds of new database entries, one for each word in the message, each entry needing a disk seek. If you're adding a few new messages a second, it will be hard for your disk to keep up. Anyway you don't need a real database. You're not doing that kind of accesses, you don't need multi-phase transactions, blah blah blah. I think the way to do it instead is keep several tables: 1) a static table on disk, simply (wordId, msgId) pairs of 4-bit binary ints, sorted on wordId. You can also have an index for it: a table with one entry for each wordId, saying where in the big table the msgId's for that word start. 2) an update log on disk, (wordId, msgId) pairs like above, but unsorted. 3) an in-memory table (Python dict) containing the same pairs as the update log, but using a dict structure for instant lookup. When a new message comes in, you just append all its (wordId,msgId) pairs to the update log (just append, no random seeking needed), and also update the in-memory table. Actually you don't need to store (wordId,msgId) for every pair. Just append a record that says "next nnn records are for msgId xxx" and then only store the wordId's. When a search query comes in, look in the in-memory table by hashing, and if the word isn't found, look in the static table by binary search. Then once a night, update the static table by running the update log through a sort utility and then merging it with the static table. Then you can delete the update log and in-memory table and begin them again. The sort-merge phase is relatively fast because sorting utilities are written to sling around large buffers, minimizing disk head motion. If the system crashes or you stop the server for some reason, on restart you can simply read the update log into memory. You probably don't even need the in-memory structure if you're not taking too many search queries--the update log should be small enough that you can just sequentially scan it when a query comes in. The main idea is that you replace a lot of random small updates with occasional big sorting operations. The big sorts are far more i/o-efficient than the small updates. These are the methods they always used in the old days, when even random-access disk space was very expensive, so big data sets were always stored on completely sequential media (magnetic tape). From m.dufour at student.tudelft.nl Tue Dec 16 09:26:25 2003 From: m.dufour at student.tudelft.nl (Mark Dufour) Date: Tue, 16 Dec 2003 15:26:25 +0100 Subject: Converting integer to binary representation Message-ID: <200312161526.25612.m.dufour@student.tudelft.nl> Hi all, I need to convert an integer into some binary representation. I found the following code in the online cookbook (adapted to return a list): binary = lambda n: n>0 and [n&1]+binary(n>>1) or [] This is sure nice, but I'm wondering why something like this doesn't seem to be in the standard library, for example by formatting with '%b' % number. I can't think of a any reason for not doing it this way, as working with binary representations is quite common in programming, but I guess I'm not a language designer.. (just yet ;)) Or is there another nice way of doing this which I overlooked? Thanks, Mark Dufour. -- "The employment agency has selected an immature and unproven software package and its functionality is at the best close to Office 97," said Microsoft representatives. From dman at dman13.dyndns.org Wed Dec 17 15:38:23 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Wed, 17 Dec 2003 20:38:23 GMT Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> <93f5c5e9.0312161912.3f5c5bc4@posting.google.com> Message-ID: On 16 Dec 2003 19:12:34 -0800, hokiegal99 wrote: > William Park wrote in message news:... >> Heike C. Zimmerer wrote: >> > William Park writes: >> > > FYI, in shell, you would go >> > > find . -type f -name '*.mp3' | xargs rm >> > >> > Which will fail if the file name contains any spaces or other special >> > characters (not too unusual for .mp3 - Files). >> >> In which case, you look up 'man find xargs' and edit the command to >> find ... -print0 | xargs -0 ... > > What would you man on a Windows box??? Start by clicking Start -> Programs -> Cygwin -> Bash Shell ;-) > Not everyone has a unix shell, True. > and not everyone wants/needs one. True too. > None of our users use Linux/Unix. > They all use Windows XP That means you are stuck writing simple system management programs for them because the system doesn't have them out-of-the-box. It's your [users'] choice. > or Mac OS X. OSX comes with a POSIX shell. > So, you shouldn't assume that I'm running Linux or some other type > of Unix. But you are :-). OSX is "some other type of Unix". > I do as an admin/developer, but that's not the point. Agreed. > The above python script will run on Windows, Linux, OS X, etc. Yeah, yeah. (for such a simple task I'm not impressed, but for non-trivial stuff (eg more complex "delete all files matching certain criteria) and the like I would be) > and it makes for much easier reading. I think the find(1) example is quite easy reading. It's one compact line, with all the detailed file handling taken care of automatically. > This is a python forum. So, you're off-topic. Not really off-topic. Many times a someone relatively new and/or inexperienced with computers posts a system admin type of question in this forum not knowing that the tools already exist. Pointing out some existing tools, rather than encouraging reinvention, is never a bad thing. Sometimes that education is invaluable for the OP or even for other lurkers. If the given solution doesn't apply to your environment, kindly pass on to the next suggestion or (nicely :-)) clarify if need be. -D -- [Perl] combines all the worst aspects of C and Lisp: a billion different sublanguages in one monolithic executable. It combines the power of C with the readability of PostScript. -- Jamie Zawinski www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From gandalf at geochemsource.com Thu Dec 4 04:12:47 2003 From: gandalf at geochemsource.com (Gandalf) Date: Thu, 04 Dec 2003 10:12:47 +0100 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> Message-ID: <3FCEFA8F.4060103@geochemsource.com> Use PySerial http://pyserial.sourceforge.net/ Laci Todd Gardner wrote: >--------------------------------------------------------------- >I would appreciate any ideas how to write to the parallel port (Mem >0x378) when runnning WinXP or Mandrake 9.2. > >In C and LabVIEW I use the OutP command to write to directly to a >memory address. > >Thank you >-- >Todd >piir at earthlink.net >--------------------------------------------------------------- > > From ora at iheg.arg.invalid Fri Dec 19 20:38:22 2003 From: ora at iheg.arg.invalid (Ben) Date: 20 Dec 2003 01:38:22 GMT Subject: semi-OT: DNS issues for python.org (re-send) Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, I'm seeing a lot of "lame server" messages from my name server when trying to resolve mail.python.org and neither my name server (devious.adversary.org) nor those of my upstream (yarrina.connect.com.au & warrane.connect.com.au). In fact, one of my upstream's caches (yalumba.connect.com.au) is locating what appears to be invalid nameservers for python.org. Yalumba believes python.org's nameservers are ns53.worldnic.com & ns54.worldnic.com. While tracking back from UltraDNS points to ns.xs4all.nl & ns2.xs4all.nl. So does anyone know if there are currently any registration or delegation issues with python.org or if they are seeing similar things elsewhere? Regards, Ben P.S. I tried to send this to the list a little while ago, but of course my system is having trouble reaching it. -----BEGIN PGP SIGNATURE----- Version: PGP 6.5.8 iQA/AwUBP+OnHzcaxb+gSuMTEQK9nQCglFtxnRqMa1DDnUcNy54Q8xru58cAn2uw ermzA282kdJyBQF9Qi9H+zBS =rGRG -----END PGP SIGNATURE----- From rmunn at pobox.com Mon Dec 29 10:01:51 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 29 Dec 2003 15:01:51 GMT Subject: indendation question References: Message-ID: Stephen Ferg wrote: > The official recommendation is to use 4 spaces, but... > > ... Using tabs seems much more natural to me. > > One level of indentation == one tab character. > What could be more natural? > > So I always use tabs, and that's what I recommend. The problem with tab characters is that it makes it very difficult to share your code with others. Everyone has different settings for their tab stops: some use 4, most use 8, a few heretics :-) use 3... Thus, your code, that you carefully arranged to be less than 80 characters wide, will someday be read by someone who has 8-space tabs (while you use 4-space tabs), and on his screen, it will wrap around most annoyingly. And if someone else is *editing* the same file as you, it will make matters even worse, because they're likely to be using spaces for indentation. So you've indented something with one tab, which on their screen looks like 8 spaces. They add a line at what they believe to be the same level of indentation: 8 spaces. Then you look at the file and see their line as being one step more indented than yours. Now try to guess what Python will do with that file. This isn't just a theoretical problem: I've personally cleaned up files (although they weren't written in Python) that had had exactly this happen to them. That's why I recommend space characters, not tabs. Yes, it may feel more natural to just hit the Tab key to indent -- but any decent programming editor can be set up to insert the right number of spaces when you hit the Tab key! In vim, for instance, look at the "shiftwidth" and "smarttab" options. On the other hand, read the rationale for PEP 666: http://www.python.org/peps/pep-0666.html -- Robin Munn rmunn at pobox.com From niemeyer at conectiva.com Tue Dec 16 11:52:03 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Tue, 16 Dec 2003 14:52:03 -0200 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: <20031216165203.GA5285@burma.localdomain> Hi Charles! > I could be wrong, but it looks to me like SIOD requires a C runtime > library to function. One of the big attractions of using Forth (at > least to me) is it's lack of reliance on a runtime library. Direct Oh, a Forth fan. Cool. :-) I confess I'm not confortable with the forth syntax (at least not yet), but even then, I've looked into Forth as well (namingly, FICL). OTOH, unlike you claim below, the FICL static library is larger than Lua's one, and it does link with the libc runtime. Perhaps I'm looking at the wrong direction. Can you please point me to the Forth implementation you're talking about? I'd like to have a look, just out of curiosity. > interfacing to the linux kernel should be possible in an > architecture-neutral manner, That's something I don't take as an advantage, for my usage cases. I'd rather keep away from kernel interfacing tasks (has anyone tried to compile something with videodev with 2.6 yet? :-). I'd rather stick with some minimal libc version, if needed. > and the ~10K overhead of a Forth kernel is very minimal when compared > to the ~75K overhead of SIOD (from the As I said, the forth implementation I've looked at, which looks like a rather common one, gave me different results. I haven't looked at SIOD, but will do. > website) + the hundreds of KBytes (if not MegaBytes) of overhead for > the runtime C library. [...] The same as two paragraphs above. Also, I should say that I have obvioulsy found some *very* minimal languages while I was doing the research, but these were either badly implemented or just didn't offer the basic stuff I was looking for (easy and elegant C extending, etc). -- Gustavo Niemeyer http://niemeyer.net From PeterAbel at gmx.net Sat Dec 13 06:31:26 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 13 Dec 2003 03:31:26 -0800 Subject: do this with list comp? References: Message-ID: <21064255.0312130331.7fdee240@posting.google.com> "Dave Brueck" wrote in message news:... > > I want to replace all empty fields in a CSV line with 'NULL'. > > > > Here is a brute force way > > > > def fixline(line): > > ret = [] > > for s in line.split(','): > > if not len(s): ret.append('NULL') > > else: ret.append(s) > > return ret > > > > line = 'John,Bill,,,Fred' > > print fixline(line) > > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > > > > I am wondering if there is a way to do it with list comprehensions. I > > know how I would do it with a ternary operator..... > > Prepare to be flooded with answers. ;-) > > >>> line = 'John,Bill,,,Fred' > >>> [x or 'NULL' for x in line.split(',')] > ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > > -Dave > > P.S. I guess you are sure that the fields themselves don't have commas and that > you don't therefore need a "real" CSV parser? And there was still a one-liner: >>> line = 'John,Bill,,,Fred' >>> map(lambda x:x or 'NULL',line.split(',')) ['John', 'Bill', 'NULL', 'NULL', 'Fred'] Regards Peter From dave at pythonapocrypha.com Fri Dec 12 12:51:20 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 12 Dec 2003 10:51:20 -0700 Subject: Recording web page URLs References: <20031212172718.26311.qmail@web41508.mail.yahoo.com> Message-ID: <023d01c3c0d8$8d12e300$891e140a@YODA> Phil wrote: > Hello everyone, > > I'm building a python application that will monitor a person's behavior with his mouse while surfing the web (probably > using Internet Explorer). I want to record the URLS of the pages he visits. Is there a simple way to do this in python? Hi Phil, This is really a two-part question: 1) Is there a simple way, on the Windows platform, to capture URLs visited? 2) How do I do this from Python? Unless someone here has specific experience solving #1, there will probably be other websites/newsgroups more knowledgeable in answering that question (but people here might still be able to help), but once you know the answer to #1 you will probably find lots of help here in answering #2. :) Here's my attempt at answering #1, but remember that I'm no Windows expert so there may be much better ways of doing this: a- configure the browser to access the internet through a local proxy b- use something like winpcap + urlsnarf to do packet & url sniffing c- implement an IE BrowserHelper object or use some other COM interface d- browse from inside an application that hosts an Internet Explorer object e- some win32API hackery wherein you figure out the location of the mouse when the click occurred, grab a handle to the appropriate window & the browser DOM, and do magic to walk the DOM and deduce what link was clicked (ok, I'm straining at ideas now, but you did say you were monitoring mouse behavior so maybe...) As far as question #2, all are possible from Python if they're possible in Windows, although option 'e' is almost too bizarre. Specifically, I've used options a, b, and d: a - there are several open source proxies written in Python, so this one might be easy. This works well as long as the proxy is written to gracefully handle bad data. The HTTP spec is complicated and there are oodles of HTTP servers that implement the spec in quirky ways. b - this one is more tedious to implement and raises some security questions, but is transparent to the user once installation has occurred. Unlike the proxy approach, a failure in your code shouldn't ever interrupt the user's browsing, which is nice. At home my Linux router runs urlsnarf and hands the data off to a little Python app that logs URLs. At the end of the week everyone in my family gets an email outlining sites visited from my computer, my wife's computer, and my kids' computer - sort of a self-monitoring thing to make sure we all behave. I'm in the process of moving it all to Windows, and it's definitely doable there. c - doable via ctypes or win32com, but I've never tried it. I know BrowserHelper objects let you integrate with IE to some extent. You need to find the same hook or API that download managers use when they "hijack" a download from a browser to handle it themselves. d - trivial (download wxPython, embed an IE instance, and capture the OnBeforeNavigate events IIRC) but really weird for the user, and probably not very useful except in some very controlled research project. :) If you do some digging around on some more general purpose Windows programming websites or lists and find something interesting, please let me know. :) HTH, Dave From spiffy at worldnet.att.net Tue Dec 9 17:06:32 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 22:06:32 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: "Dennis Lee Bieber" wrote in message news:ef9ha1-6p3.ln1 at beastie.ix.netcom.com... > Spiffy fed this fish to the penguins on Tuesday 09 December 2003 00:38 > am: > > > from the "Learning Python" book. When I run it, the dos command line > > appears with the message 'Bad command or file name". Both the .exe and > > the .mid file are in the python path and the spelling has been > > checked. What I expected to happen was that the os.system call would > > start the .exe and begin playing the .mid file. This does not happen. > > This is what I meant when I said I haven't been able to get this to > > work. > > > So include (don't retype or paraphrase, use cut&paste) the /exact/ > code which is failing, AND the exact command window output... > > Among other things, I don't think os.system() uses the /Python/ path > -- its the equivalent of opening a new command prompt and typing the > command; so it is the OS search path that is used. > > Open a command window, and type the exact command you think you are > using in os.system() > > -- > > In the command window the call to the program with the name of the .mid file to be played works just fine. Here is what it looks like....exactly: C:\Python22>playb Canyon.mid Here is the code used to call it from Python: import os filename = "C:\Python22\Canyon.mid" os.system("C:\Python22\playb.exe%s"%filename) ...this causes a dos box to appear which promptly hangs and does nothing, at which time Python stops responding. Vartiations on this will cause the dos box to appear with the message "Bad command or file name". ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: http://www.beastie.dm.net/ < > > Home Page: http://www.dm.net/~wulfraed/ < > From francisgavila at yahoo.com Mon Dec 22 19:07:41 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 19:07:41 -0500 Subject: list.index() like...but returning lists (for avoiding '0' on multiples hits) References: Message-ID: John Roth wrote in message ... > >But what does that have to do with the question? > >As far as I know, there is no such built-in for lists. >You can do something similar with the "re" module >for strings, but not for lists. > >John Roth More and more I am finding myself wishing for a neat way to *add* functionality to a builtin. Not subclass a builtin, but add methods to the builtin type. Like (the function does what the OP wants, btw): >>> def indices(self, value): ... return [i for i,v in enumerate(self) if v == value] ... >>> list.indexes = indexes >>> [0, 2, 2, 3].indexes(2) [1, 2] This currently gives: Traceback (most recent call last): File "", line 1, in ? list.indexes=indexes TypeError: can't set attributes of built-in/extension type 'list' Oh well. Anyway, the following might be faster: def indices2(L, value): res = [] last = -1 #below, last+1 to prevent infinite loop. try: while True: last = L.index(value, last+1) res.append(last) except ValueError: return res From fredrik at pythonware.com Tue Dec 16 04:56:34 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Dec 2003 10:56:34 +0100 Subject: Package organization References: <73b00f0c.0311181638.49a5997d@posting.google.com> <73b00f0c.0311191423.3c946fdc@posting.google.com> Message-ID: Robert Ferrell wrote: > > Also, because you're importing something from inside a module using the > > "from" style imports you're risking running into circular reference > > problems. In my experience from imports are best avoided, unless you're > > importing a module from a package. > > I don't understand this comment. How does "from" style importing > increase the risk of circular imports? python has no problem doing circular (or recursive) imports, but you're likely to run into problems if you're doing recursive imports and you're referring to stuff from one module on the *module-level* in another module. from-import does exactly that. for a diskussion, see the section on "recursive imports" on this page: http://www.effbot.org/zone/import-confusion.htm From EP at zomething.com Mon Dec 22 00:46:31 2003 From: EP at zomething.com (EP) Date: Sun, 21 Dec 2003 21:46:31 -0800 Subject: calling the function police In-Reply-To: Message-ID: <5.2.0.9.0.20031221212429.00b7a3d0@mail.zomething.com> Hi, "I'm new and confused" "Hello 'New and Confused'" TypeError: function1() got multiple values for keyword argument 'first' >>> def function1 (first='Jimminy Cricket', end='suffix', *extras): together, extra=' ',' ' for each in extras: try: extra+=each except TypeError: extra+=`each` together=first+extra+end return together >>> parameter='something' >>> result=function1(first=parameter, end='noodles','Jim Beam', 'Poker') TypeError: function1() got multiple values for keyword argument 'first' What rule have I violated? This seems to be associated with the assignment of a variable to a keyword argument in the function call. Is this illegal? If so, why is this a crime? The logic isn't popping out at me... Thanks.... Eric [I resorted to relying on order rather than keywords in the call to make it work] From ville.spammehardvainio at spamtut.fi Sat Dec 27 05:10:55 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 27 Dec 2003 12:10:55 +0200 Subject: Project dream References: Message-ID: hwlgw at hotmail.com (Will Stuyvesant) writes: > Suppose you have the time and the money to start a new project in > Python. What would you like to do? Well, not completely *in* python, but about Python anyway: - Rewrite Emacs (though this would probably need lots of C code for that extra snappiness). Make it extensible in Python (natively, i.e. w/o pymacs), use all the latest Gtk UI stuff, provide all the intellisense:ish features of commercial IDEs (yes, I know about Semantic). - Port Python to Symbian OS > 6.0 - Implement fast native code compilation for Python (though this is well beyond my capabilities). This might be interesting also in the sense of creating a compiler in Python, even though it might not be that fast... -- Ville Vainio http://www.students.tut.fi/~vainio24 From antonmuhin at rambler.ru Wed Dec 24 13:56:54 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Wed, 24 Dec 2003 21:56:54 +0300 Subject: ungetch in Python In-Reply-To: References: Message-ID: Scott Fenton wrote: > Hello and merry chrismas/new years/ everyone, > > I'm writing a small parser for a minilanguage in Python, > and I was wondering --- is there any equiv. of C's ungetch > or Scheme's peek-char in python? That is, is there a way to > look at a character without taking it off of the input stream > or is there a way to put it back on the input stream afterwards? > I googled around and didn't come up with anything that didn't > involve curses, which I don't want to use. Any help? > > TIA > -Scott Merry christmas & Happy New Year! First of all I'd rather suggest to use one of parsers for Python---there are plenty of them and they are really nice. To your question: I don't remember this kind of function is Standard Lib, but chances are it is there. But still you can emulate it with your own iterator class. Here comes an example: class UngetIter(object): def __init__(self, it): self.it_ = iter(it) self.hasUnget_ = False self.last_ = None def __iter__(self): return self def next(self): if self.hasUnget_: self.hasUnget_ = False return self.last_ return self.it_.next() def unget(self, o): assert not self.hasUnget_, 'Only one unget allowed!' self.hasUnget_ = True self.last_ = o i = UngetIter('abc') for n, e in enumerate(i): if n % 2 == 1: print 'unget', e i.unget(e) else: print e Warning: almost not tested. If you want to unget more than one char, you can just use a list of objects to unget. regards, anton. From jepler at unpythonic.net Wed Dec 10 18:41:23 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 10 Dec 2003 17:41:23 -0600 Subject: sys.argv with quoted strings as option argument In-Reply-To: <3FD818D9.40109@ttck.keio.ac.jp> References: <3FD818D9.40109@ttck.keio.ac.jp> Message-ID: <20031210234123.GA25397@unpythonic.net> It certainly doesn't work this way on my Unix system. [jepler at parrot jepler]$ ls -l printargs.py -rwxrwxr-x 1 jepler jepler 48 Dec 10 17:40 printargs.py [jepler at parrot jepler]$ cat printargs.py #!/usr/bin/env python import sys print sys.argv [jepler at parrot jepler]$ ./printargs.py --includedir="/usr/include /usr/local/include" --libdir="/usr/lib /usr/local/lib" ['./printargs.py', '--includedir=/usr/include /usr/local/include', '--libdir=/usr/lib /usr/local/lib'] Jeff From __peter__ at web.de Fri Dec 19 06:29:26 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 12:29:26 +0100 Subject: Sorting coordinates array References: Message-ID: Peter Otten wrote: > This is a highly unoptimized version, but at least seems to do the job. Slightly better: >>> lst = a.tolist() >>> lst [[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]] >>> for item in lst: item.reverse() ... >>> lst.sort() >>> for item in lst: item.reverse() ... >>> lst [[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]] >>> Peter From peter at engcorp.com Tue Dec 2 11:27:36 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Dec 2003 11:27:36 -0500 Subject: python's threading has no "interrupt"? References: Message-ID: <3FCCBD78.5A1153D2@engcorp.com> Jay O'Connor wrote: > > .... When the background > process would wake up, since it was a higher priority, it would > immediately take control. It's main job was to check the list of > handling processes for any that had been running too long (long running > processes in a web server meant that something had gone wrong) and > terminate them (freeing up the process and socket resources, etc..). Can you describe the nature of the "something had gone wrongs" that you were trying to handle? It's a very important point for a design like this. Could these processes launch external programs which might not exit in time? Were they possibly buggy, encountering for example endless loops? Were they dynamically loaded code written by others, which could mean malicious behaviour was possible? Or something else? Depending on the answer, it will be either very easy to handle in Python, or very hard, or potentially impossible in a straightforward fashion. -Peter From sombDELETE at pobox.ru Fri Dec 12 07:46:31 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Fri, 12 Dec 2003 15:46:31 +0300 Subject: seek in a zip file?? References: Message-ID: >"Enrique" wrote in message news:mailman.63.1071135997.9307.python-list at python.org... > hello all! > i?m working with big size files, to maintain them, it would be better to > compress the files. > to recover a little part of the big file, how can i extract that little > parte instead of the whole file that will bring a lot of time? It's impossible by design of zip compression algorithm. > Can i know the offset in a zip file?? i know the offset in the big one. > Any idea will be welcome. Pack your file in small chunks (for example 256K) and hide this fact from your main program using small wrapper. Or use file system compression (available on windows ntfs filesystem) Or find a compression library that allows random access and generate a wrapper for it using SWIG. From jsbenson at bensonsystems.com Sun Dec 7 17:50:55 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sun, 7 Dec 2003 14:50:55 -0800 Subject: entering the lists against CamelCase Message-ID: <056501c3bd14$9492a560$210110ac@jsbwxp3> I never cared for CamelCase because a lot of words in English are compounds, and remembering the right CamelCase rendition of them gets difficult. For example, an object attribute named HaveAMerryChristmas isn't too hard, but what about deciding between HaveAGoodWeekend and HaveAGoodWeekEnd? I think that most native English speakers would automatically chose the former, but others might tend to misremember the latter. And what about LaunchGoodyearBlimp versus LaunchGoodYearBlimp? A person without specific knowledge of the Goodyear company might easily fall into the error of choosing the latter. I'm sure that even better examples could be found, given billable time. As to the relative abundance of CamelCase, I've seen a potful of it. I remember seeing it in the Macintosh API, and it's all over Windows. I've also seen a lot of mostly-lowercase code, too, so in my experience you can't decide the case (pun intended) on the basis of popularity. I think CamelCase is a reaction against an unrelieved boredom with uppercase-only terminals and printer chains. When terminals and printers could do both upper- and lower-case glyphs, one group went almost all lowercase (except for C globals and object-like macros ) and another group went CamelCase, both in reaction against the former tyranny of uppercase. A holdout was the lone COBOL programmer I knew who refused to disengage her caps lock key in an effort to preserve the wierdly uncool all-uppercase style of old COBOL listings. Although I'm tempted to claim that all the cool guys and gals went mostly lowercase because that's my personal preference, I'm actually grateful for all the CamelCased good stuff available to me through Python. Case Dismissed! From thomas at esands.com Thu Dec 11 23:12:58 2003 From: thomas at esands.com (T. Schulz) Date: Fri, 12 Dec 2003 04:12:58 +0000 Subject: Linux GUI for python? In-Reply-To: References: Message-ID: I started with Tkinter and Tix. Always found it quite hard to read the Tk documentation. Now I moved to wxPython and I belive thats the way to go. Thomas Lord Jester wrote: > Looking for any suggestions for a GUI for python > under linux. Right now I'm just starting out but > latter on I want to get into building programs > that have GUIs. Any suggestions? From cr88192 at hotmail.com Thu Dec 25 19:06:47 2003 From: cr88192 at hotmail.com (cr88192) Date: Thu, 25 Dec 2003 16:06:47 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "Brandon J. Van Every" wrote in message news:bsflkg$coko2$1 at ID-207230.news.uni-berlin.de... > > "cr88192" wrote in message > news:vul2i238el9hda at corp.supernews.com... > > > > > > I am mostly responding because I found it amusing that I disagreed with > > nearly every point mentioned here, this is not meant as any kind of > > discouragement though... > > Different strokes for different folks! :-) > yes. > > it is quite likely that I just have a very much different set of ideals... > > Yes, given our previous discussions in > comp.games.development.programming.misc, I'd say your tastes run the > opposite for a number of significant things. Functional vs. imperative, > technology vs. Game Design. > quite agreed. From jfranz at neurokode.com Thu Dec 11 15:35:51 2003 From: jfranz at neurokode.com (Jon Franz) Date: Thu, 11 Dec 2003 15:35:51 -0500 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <20031211190954.GA54939@hishome.net> Message-ID: <05f701c3c026$5eb9c8f0$7401a8c0@voidmk9> > > What's wrong with Jython? I haven't used it myself, but have always wondered > > why it's not mentioned when different Python GUI:s are discussed. > > Jython + SWT is a pretty cool combination. SWT is a well-designed, high > performance portable toolkit using native widgets. Python is our favorite > language. If they could be married without Java it would be even better. > > Oren I use jython + java swing for a large, ongoing contract. The plugable look & feels allow you to add some nice UI skins to your application with 1 or two lines of code - I use the 'Alloy' look and feel from incors (http://www.incors.com/lookandfeel/index.php) - though it does cost. One nice thing with swing (and forgive me if SWT does this, I am not familiar with it) is that most widgets will allow html to be used within the text for simple markup - allowing for easy display of formatted paragraphs, bold text, etc. It also comes in handy when you want to throw an image onto a label widget. You can use sun's one-studio (netbeans) to design your gui, and then use the classes it generates within your jython code fairly easily. I find myself creating quick and dirty forms all the time by hand in jython (its just so fast - so few lines of code), but I am convert a lot of them to actual java classes later for increased speed. I'm off to look into SWT... ~Jon Franz NeuroKode Labs, LLC 513.260.5788 From fBechmann at web.de Mon Dec 29 02:16:18 2003 From: fBechmann at web.de (Frank Bechmann) Date: 28 Dec 2003 23:16:18 -0800 Subject: why does py_compile.compile() miss some errors in sourcefile? Message-ID: where can I find some documentation, which errors will be found by 'py_compile.compile' and which will not be found. # t1.py # ===== import os.path import py_compile py_compile.compile(os.path.join(os.path.dirname(__file__), "t2.py"), doraise=True) # t2.py # ===== # following line is found as an error: # Class C: # <== 'SyntaxError: invalid syntax' class C: pass c = CC() # <== not found as an error from py_compile # but found as an error from python-executable: # 'NameError: name 'CC' is not defined' thx in advance From http Thu Dec 11 07:49:04 2003 From: http (Paul Rubin) Date: 11 Dec 2003 04:49:04 -0800 Subject: What GUI toolkit looks the best? Message-ID: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> I've been approached about writing a Windows app which will need a really professional looking GUI. Forget TKinter, this has to actually look good (real artists will be available to get the visual stuff right). Assuming I write in Python, what's the best toolkit to use? Some cost in implementation pain is tolerable if the finished interface looks better as a result. It would be nice if the toolkit runs on multiple platforms rather than being Windows-only. I'm thinking Glade. Is that reasonable? I don't know squat about Windows and haven't done much fancy GUI programming since the early X days. Thanks. From noemail at noemail4u.com Fri Dec 5 07:44:38 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 05 Dec 2003 12:44:38 GMT Subject: Simple newbie question References: Message-ID: On Thu, 4 Dec 2003 15:36:11 +0100, Angelo Secchi wrote: >I'm trying to remove lines with zeros from a list "lista". >The code i'm using is the following: > >for line in lista: > if sum(line == 0) > 0: > lista.remove(line) > > >The problem is that the loop stops at the first line with zeros and it >doesn't remove the other lines with zeros (at least if I do not re-run >the loop). Probably I do not understand how the loop works. I see other's responses, but am wondering why the line if sum(line == 0) > 0: doesn't raise a "TypeError: iteration over non-sequence" for everyone else. line==0 is a single boolean, and a sum on that raises an exception for me. I'm also wondering why the program compiles, since the lista.remove(line) should be more indented. Thanks, --dang From antonmuhin at rambler.ru Tue Dec 30 13:32:34 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Tue, 30 Dec 2003 21:32:34 +0300 Subject: 'inverting' a dict In-Reply-To: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Hi > I have this dict that maps a name to a sequence of other names. > I want to have it reversed, i.e., map the other names each to > the key they belong to (yes, the other names are unique and > they only occur once). Like this: > > { "key1": ("value1", "value2"), "key2": ("value3,) } > > --> > > { "value1": "key1", "value2": "key1", "value3": "key2" } > > What I'm doing is using a nested loop: > > dict2={} > for (key,value) in dict1.items(): > for name in value: > dict2[name] = key > > which is simple enough, but I'm hearing this little voice in > the back of my head saying "there's a simpler solution". > Is there? What is it? ;-) > > Thanks > --Irmen. > It's seems like rather nice Python for me ;). Two more variants: inverted = {} for k, vs in d.iteritems(): inverted.update(dict([(v, k) for v in vs])) map( lambda (k, vs): inverted.update(dict([(v, k) for v in vs])), d.iteritems() ) happy new year, anton. From Pieter.Claerhout at Creo.com Thu Dec 18 08:43:12 2003 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Thu, 18 Dec 2003 14:43:12 +0100 Subject: Searching docs (was Re: Logging) Message-ID: <490316A24CC5D411ACD700B0D078F7F003915D1F@cseexch01.cse.creoscitex.com> You can search through the docs on: http://web.pydoc.org/ and on http://starship.python.net/crew/theller/pyhelp.cgi cheers, pieter Creo pieter claerhout | product support prinergy | tel: +32 2 352 2511 | pieter.claerhout at creo.com | www.creo.com IMAGINE CREATE BELIEVE(tm) -----Original Message----- From: Kamus of Kadizhar [mailto:yan at NsOeSiPnAeMr.com] Sent: 18 December 2003 14:20 To: python-list at python.org Subject: Searching docs (was Re: Logging) On Thu, 18 Dec 2003 23:40:33 +1100, Anthony Baxter wrote: > Did you look in the logging documentation? At the end of the > current docs, there's a simple example: Missed that. Is there a search on python.org that only searches docs? That would be really helpful.... I keep coming up with gobs of irrelevant stuff on my searches. I keep missing simple stuff like that. -Kamus -- http://mail.python.org/mailman/listinfo/python-list From mwh at python.net Mon Dec 29 05:49:29 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Dec 2003 10:49:29 GMT Subject: recursion in grammar? References: <34ea966a.0312270509.5ecc2095@posting.google.com> <3hvuuvgenp6tjvadovhfdckqdrmj1agv13@4ax.com> Message-ID: Stephen Horne writes: > ANTLR definitely uses LL parsing. I don't know about Pythons parsing > engine, though I suspect it uses LR-style parsing. Nope, LL(1). One thing you should note is that the grammar in the docs is *not* the grammar used by Python's parser generator -- that's Grammar/Grammar in the source distribution. I'm not sure, but I suspect that the grammar in the docs is nastily ambiguous. Certainly the actual Python parser lets through some stuff that get's thrown out in the compiler with SyntaxErrors. Cheers, mwh -- Good? Bad? Strap him into the IETF-approved witch-dunking apparatus immediately! -- NTK now, 21/07/2000 From j.r.gao at motorola.com Mon Dec 15 02:14:48 2003 From: j.r.gao at motorola.com (J.R.) Date: Mon, 15 Dec 2003 15:14:48 +0800 Subject: Beginner question - How to effectively pass a large list Message-ID: Hi folks, The python can only support passing value in function call (right?), I'm wondering how to effectively pass a large parameter, such as a large list or dictionary? It could achieved by pointer in C++, is there such way in Python? Thansk in advance. J.R. From francisgavila at yahoo.com Mon Dec 22 01:44:20 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 01:44:20 -0500 Subject: Singleton process References: Message-ID: Fortepianissimo wrote in message ... >Here is the situation: I have multiple processes of same Python script >fired, but I want *only one* of them to continue and all the others to >quit immediately. > >I can use a lock file, and the first process will get the necessary >lock. But if I do open(lockfile) all the other subsequent processes >will just wait there - instead I want them to quit immediately. > >Can someone give a simple outline of how to achieve this? Thanks a >lot. This seems like a very strange requirement. May I ask why you're doing this? Anyway, if you're using a lock file, how is 'open' going to help you? Open opens a file, creating it if it does not exist. Think about how a lockfile would work in your situation: - If the lockfile exists, terminate myself. - Otherwise, create the file (thus grabbing the lock). - Make sure somebody deletes the file when done. Do the first with os.access('filename', os.F_OK) Do the second with file('filename').close(). (or use os.open if you are worried about being atomic.) Do the third with os.unlink('filename'), if the Python process is supposed to clean up after itself. You might want to put this into the exit signal handler. -- Francis Avila From robin at jessikat.fsnet.co.uk Thu Dec 25 06:18:39 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 25 Dec 2003 11:18:39 +0000 Subject: 2.3 list reverse() bug? References: Message-ID: In article , Mark Carter writes >I did this: > >Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on >win32 > >>>> d1 = [1,2] >>>> d2 = d1 >>>> d2.reverse() >>>> print d1 #note: d1, not d2 >[2, 1] >>>> > >Surely that can't be right: d1 should still be [1,2]. If it is >"right", then I expect that many people are in for a suprise. Really need to get a life, but anyhow here goes. It's right. d1 & d2 both point to the same mutable object and sort is done in place. compare with this >>> d1=[1,2] >>> d2=d1 >>> d2[0]='a' >>> d1['a', 2] >>> -- Robin Becker From http Mon Dec 1 06:15:24 2003 From: http (Paul Rubin) Date: 01 Dec 2003 03:15:24 -0800 Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: <7x3cc4g56b.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > Not only is the lambda unattractive, it is slow. This situation is > not unique to sort(), it comes up with other functionals like map() > and filter(). A new itertool called groupby() also faces the same > situation. > > So, the idea was born to add a fast extract function maker to the operator > module: Better to improve the compiler so that lambda makes good code. From max at alcyone.com Wed Dec 24 04:07:15 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 24 Dec 2003 01:07:15 -0800 Subject: replace line #1 with "newline\n" in text file References: <3fe955b8.0@news1.mweb.co.za> Message-ID: <3FE95743.AB5B23F8@alcyone.com> bmgz wrote: > I am trying to replace the first line of a config file.. with a new > string > been googlizing and reading the python manual.. but can't find what I > need.. > it's all rubbish about bits and bytes etc.. You'll have to read in the file, write out a temporary one, and then move the new one over the old one. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ Once the people begin to reason, all is lost. -- Voltaire From martin at v.loewis.de Thu Dec 25 14:56:41 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 25 Dec 2003 20:56:41 +0100 Subject: OT: Why -g when compiling In-Reply-To: References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: Michael Hudson wrote: > True. I don't know if the various linkers around are smart enough to > not load debugging information until it's asked for... Atleast on Unix, not mapping debug information at run time has a long tradition. In ELF, each section has a LOAD flag indicating whether a section needs to be mapped or not. So the ELF dynamic loader does not specifically know to omit debug information, but only loads sections that the static linker told it to. Regards, Martin From __peter__ at web.de Sun Dec 7 04:26:17 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Dec 2003 10:26:17 +0100 Subject: New inited instance of class? References: Message-ID: Samuel Kleiner wrote: > So can I make all my classes derive from object without > doing so explicitly- IE, without having to change every > single top-level class definition? > You can do it on a per-file basis by putting __metaclass__ = type once before the class definitions. Peter From traveller3141 at att.net Tue Dec 30 22:13:49 2003 From: traveller3141 at att.net (traveller3141 at att.net) Date: Wed, 31 Dec 2003 03:13:49 +0000 Subject: Installing PyOpenGL - can't find libnumarray module Message-ID: <123120030313.19980.1fd8@att.net> Sorry, when I originally uninstalled numarray & entered from OpenGL.GL import *, the traceback I got was Traceback (most recent call last): File "C:\Python23\lib\site- packages\Pythonwin\pywin\scintilla\formatter.py", line 222, in OnStyleNeeded notify = self.scintilla.SCIUnpackNotifyMessage(extra) File "C:\Python23\lib\site-packages\Pythonwin\pywin\scintilla\control.py" , line 57, in SCIUnpackNotifyMessage margin = margin) ImportError: No module named numarray.libnumarray win32ui: Exception in OnNotify() handler This is what led me to think that I needed the numarray module, which is why I reinstalled it. I should have been more clear about that. So, that's what started me wondering about the .pyd extension. The numpy installer I used was Numeric-23.1.win32-py2.3.exe, and the PyOpenGL installer I used was PyOpenGL-2.0.1.07.py2.3-numpy23.exe. I think these are the correct installers. Anyway, that's where I am & how I got here. Thanks for all your help > Steven Gutstein wrote: > > >"Mike C. Fletcher" wrote in message > > > > > > > >>Basically, to fix the problem, uninstall NumArray and install NumPy 23.0. > >> > >> > >I tried this, without success. > >I also find I get the same error when I type > > > >from numarray import * > > > > > You are trying to import a package you just un-installed? Is this line > showing up from some other package you're trying to run and you're > debugging by trying it at the Python prompt? A Numpy import looks like > this: > > from Numeric import * > > AFAICS, there's nothing named numarray anywhere in a Numpy 23.0 > installation, so if you get that working, then you've not got NumArray > purged yet. > > However, since your original problem was an import error, "the same > error" probably (posting exception tracebacks is useful) indicates that > you're getting an ImportError saying that numarray doesn't exist. > That's what you *want* (since you don't want NumArray hanging around). > > >I'm wondering if there's some problem with the fact that libnumarray > >is a .pyd file. I came across a comment that for some reason .pyd > >files don't get found and what I should do is create the following > >setup.cfg file: > > > > > > > This is only for creating stand-alone executables, it has nothing to do > with just running PyOpenGL. It's also related to NumArray, *not* Numpy, > so again, not relevant. > > >Is there something > >obvious that I'm missing here ? > > > > > Hopefully not any more. > > Good luck, > Mike > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > From francisgavila at yahoo.com Wed Dec 24 22:57:33 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 24 Dec 2003 22:57:33 -0500 Subject: Unicode from Web to MySQL References: Message-ID: John Benson wrote in message ... >Making my way through the list, I was very happy to see Francis Avila's >discussion of Unicode. I was trying to work up enough courage to ask for >something like this, and was very happy to see it appear spontaneously. My Glad to help. >only quibble would be to characterize Unicode as a mapping from numbers to >glyphs (instead of letters), since symbols from foreign alphabets sometimes >look more like squashed bugs than letters. See, I think neither letter nor glyph is a good word for it. Letter is too narrow, since unicode contains much more than letters, namely numbers, symbols, diacriticals, presentation forms, etc. But "glyphs" is too specific because it refers only to the shape, and unicode isn't a mapping of numbers to meaningful shapes, but of numbers to the meanings those shapes have. Even if the standard representation of U+0041 LATIN CAPTIAL LETTER A were '%', or any other strange shape, unicode would still be valid. (The unicode code charts helpfully mention if a code point typically looks similar to another code point, but this is not core unicode.) So really, those all-caps code point descriptions are the essence of unicode: unicode is a mapping of numbers to whatever is represented by the corresponding description (so we see just how *abstract* unicode really is). I don't know what to call this essence that the code points are mapped to. Joel of joelonsoftware.com uses the analogy of unicode mapping numbers to the Platonic forms of letters/numbers/symbols, which is really the perfect analogy for what unicode does. However, sometimes unicode botches even the code point descriptions by making them too tied to the glyph. E.g., U+0028 LEFT PARENTHESIS should really be OPEN PARENTHESIS, because right-to-left text (Arabac or Hebrew) will have U+0028 on the right side, and the glyph will face the opposite direction.... -- Francis Avila From google at evpopov.com Wed Dec 10 05:01:54 2003 From: google at evpopov.com (popov) Date: 10 Dec 2003 02:01:54 -0800 Subject: In a function, how to get the caller object ? References: <7eecf173.0312030656.7aaf405e@posting.google.com> Message-ID: <7eecf173.0312100201.7f3fe53@posting.google.com> Thanks Bengt for your answer, it's really what I needed ! Regards, Popov From paul_rudin at scientia.com Tue Dec 9 05:44:53 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 09 Dec 2003 10:44:53 +0000 Subject: python com wrappers References: Message-ID: >>>>> "Paul" == Paul Rudin writes: > I'm having a problem with the python wrappers generated from a > type library. > The symptom is that I get failures to find connections points > inside the wrappers when called from DispatchWithEvents or > WithEvents - e.g. "com_error: (-2147220992, > 'CONNECT_E_NOCONNECTION', None, None)" > It seems that the coclass_clsid property of some classes is > incorrect. It seems that when a coclass in the type library has > multiple "[source] dispinterface" it can happen that this > coclass can end up as the one referenced by each of the > corresponding DispatchBaseClass subclasses via the coclass_clsid > property, whereas probably what should happen is that only ones > that are default should be so treated. > But maybe I'm misdiagnosing the problem; has anyone else seen > this and/or know what the problem is? To test this I had a quick look at the code that generates the wrappers. In win32com/client/genpy.py The class Generator has a method _Build_CoClassChildren. Replacing the line: dispItem.coclass_clsid = coclass.clsid with the lines: if flags & pythoncom.IMPLTYPEFLAG_FDEFAULT: dispItem.coclass_clsid = coclass.clsid seems to solve the problem, although perhaps this breaks something else? From mikit at zoran.co.il Sun Dec 7 15:22:46 2003 From: mikit at zoran.co.il (Miki Tebeka) Date: 7 Dec 2003 12:22:46 -0800 Subject: Some problems for exercises References: Message-ID: <6250403b.0312071222.3bfc53e0@posting.google.com> Hello Vivek, > 1. Basic Language facilities : (Data structures, control structures, > input/output, object oriented programming etc.) > > 2. A brief (rather very brief) Introduction to GUI programming with Tkinter > > 3. CGI programming in Python > > 4. Database programming with PostgreSQL > So, as usual I have turned to you u people for help :). Please suggest me some > such problems and where to look for it. I suggest an electronic phonebook. The 1'st command line version should be enough for 1 (open file, go over lines, use regexps, people as classes and save them using pickle ...). Then add GUI for 2, web interface for 3 and database for 4. It is also nice to see a program evolving and you don't have to explain too much time describing the problem when moving from one area to the other. HTH. Miki. From news at grauer-online.de Tue Dec 9 08:27:42 2003 From: news at grauer-online.de (Uwe Grauer) Date: Tue, 09 Dec 2003 14:27:42 +0100 Subject: Reading and writing Mozilla-mail in python Message-ID: Hi all, who can help on reading and writing mozilla-mail folders with python? I wanted to implement something like an email-sync for mozilla-mail in python. I did some tests, but something is strange with the email (rfc822) modules in python. (The output of parsed messages is different from the original input) Any hints of how (what modules) this could be done in a portable manner? Thanks, Uwe From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 08:33:31 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 14:33:31 +0100 Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> Message-ID: EsC: >is it possible to pass function-arguments by reference? This is a FAQ. http://www.python.org/doc/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference -- Ren? Pijlman From markus.vonehr at ipm.fhg.de Thu Dec 4 04:44:36 2003 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 04 Dec 2003 10:44:36 +0100 Subject: scipy for Python 2.3 on win? Message-ID: Hi, is there already a scipy windows binary for Py2.3? Thanks for any hint, Markus From hokiegal99 at hotmail.com Tue Dec 16 08:10:09 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 16 Dec 2003 05:10:09 -0800 Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> Message-ID: <93f5c5e9.0312160510.4354814e@posting.google.com> > On 15 Dec 2003 13:28:01 -0800, hokiegal99 wrote: > > How can I make this script run w/o seeing a cmd popup window on the > > screen? The script works well, but each hour (when the task scheduler > > runs it) a brief cmd window appears and then goes away. It's only on > > the screen for a second or two, but it's noticable. > > Use a better OS? <0.5 wink> > > Run it with pythonw.exe instead of python.exe. How can I specify pythonw.exe over python.exe? The task scheduler has no place for this sort of thing. From piir at earthlink.net Sun Dec 7 15:46:52 2003 From: piir at earthlink.net (Todd Gardner) Date: 7 Dec 2003 12:46:52 -0800 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> Message-ID: <9b849915.0312071246.48284f78@posting.google.com> Chris Liechti wrote in message news:... > Gandalf wrote in > news:mailman.100.1070529056.16879.python-list at python.org: > > > Use PySerial > > > > http://pyserial.sourceforge.net/ > > thanks for recomending it :-) as a little clarification: > the link to pyparallel is here: > http://pyserial.sourceforge.net/pyparallel.html > > (its only a small note on the mainpage) > > currently i have only py2.2 versions available for download, but i can > easily build the 2.3 version upon request, or you can build it on your own > with mingw32 or cygwin installed: python setup.py build --compiler=mingw32 > install > > you will need giveio.sys, also available in the downloads section, that > allows programs to access the io ports on Win NT/2k/XP > > chris > I think all I have to do is figure out how to use the outp(...) command. Pardon my ignorance here but how do I figure out the syntax of this command? This is my first project in python and it seems a bit daunting. I am trying to communicate to a custom device via the parallel port. At this point I only want to write data to the data port. In my case the memory address is x378. I installed: Python 2.2, giveio_setup.exe and pyparallel-0.1.win32-py2.2.exe. I was running Python2.3 but I don't think that it will matter for this newbie project. Many thanks for all of your pointers! Todd > > > Laci > > > > Todd Gardner wrote: > > > >>--------------------------------------------------------------- > >>I would appreciate any ideas how to write to the parallel port (Mem > >>0x378) when runnning WinXP or Mandrake 9.2. > >> > >>In C and LabVIEW I use the OutP command to write to directly to a > >>memory address. > >> > >>Thank you > >>-- > >>Todd > >>piir at earthlink.net > >>--------------------------------------------------------------- From mir4uu at yahoo.com Thu Dec 11 01:14:50 2003 From: mir4uu at yahoo.com (mir nazim) Date: 10 Dec 2003 22:14:50 -0800 Subject: online examination system References: <425cc8d1.0312090932.697fd6c6@posting.google.com> <412aa581e375edd3be954b4d3a293ef1@news.teranews.com> Message-ID: <425cc8d1.0312102214.6e45e979@posting.google.com> Dang Griffith wrote in message news:<412aa581e375edd3be954b4d3a293ef1 at news.teranews.com>... > Does it need to be free also? > --dang of course it should be free . From dman at dman13.dyndns.org Thu Dec 11 20:03:55 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Fri, 12 Dec 2003 01:03:55 GMT Subject: Linux GUI for python? References: Message-ID: <0mgna1-qv1.ln1@dman13.dyndns.org> On Thu, 11 Dec 2003 23:20:01 GMT, Lord Jester wrote: > Looking for any suggestions for a GUI for python > under linux. Right now I'm just starting out but > latter on I want to get into building programs > that have GUIs. Any suggestions? I like wxPython or PyGTK. You'll have to investigate each and decide what you want in terms of API and Look-and-Feel. -D -- Q: What is the difference between open-source and commercial software? A: If you have a problem with commercial software you can call a phone number and they will tell you it might be solved in a future version. For open-source sofware there isn't a phone number to call, but you get the solution within a day. www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From removeahmed.mohamed.edigramremove at wanadoo.frremove Tue Dec 23 04:38:45 2003 From: removeahmed.mohamed.edigramremove at wanadoo.frremove (Ahmed MOHAMED ALI) Date: Tue, 23 Dec 2003 10:38:45 +0100 Subject: print before sleep in python References: <32098fec.0312222255.655750c3@posting.google.com> Message-ID: Hi avik, it works for me.Here's the code that i tried >>> import time >>> def test_sleep(): >>> print "before sleep" >>> time.sleep(5) >>> print "after sleep" >>> test_sleep() >>> before sleep and after the period >>> after sleep "Avik Ghose" wrote in message news:32098fec.0312222255.655750c3 at posting.google.com... > Hi All, > What I am trying to acheive is very simple. I want to print something > to the screen(sys.stdout) and then go to sleep (time.sleep) for a some > duration. Now, I want the thread to print the message first and then > go to sleep. But what actually happens is that it prints after coming > back to ready state. I have tried to flush the stdout > (sys.stdout.flush) but it did not work. I hope many of you will be > able to help me out. Thanks a lot in advance. > Regards, > Avik From grey at despair.dmiyu.org Tue Dec 23 20:03:32 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 24 Dec 2003 01:03:32 -0000 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <3FE8652D.2E8F21A8@engcorp.com> <3FE889D3.368E3AF5@engcorp.com> Message-ID: On 2003-12-23, Aahz wrote: > You could read the whole book on-line, of course, but if you want to > read the whole book, I agree that paper is better. I dunno. I've read a couple of books from Baen on my Axim and found it comparable to paper. It's portable, easy to read, easy to maintain my place, could use it pretty much everywhere and, the best part, I have ~6 large mass media books in about 1/15th the size. ;) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From http Sat Dec 6 00:48:06 2003 From: http (Paul Rubin) Date: 05 Dec 2003 21:48:06 -0800 Subject: min and max id numbers References: <0_dAb.983$_r6.908@newsread1.news.pas.earthlink.net> Message-ID: <7xhe0ejy3t.fsf@ruckus.brouhaha.com> "r.e.s." writes: > Still, if it were a game played on one machine, surely > some of the experts around here could come pretty close > to finding a LO and a HI object. No? The id of an object in CPython is just its memory address. Obviously you could not guarantee the HI object staying higher than all the other objects since the interpreter can always allocate more memory. To do what you're asking you'd have to modify the interpreter to have a new kind of sentinel object and have ident return special values for those objects. I guess you could do that if you really wanted, but it would be a crazy crock. From missive at frontiernet.net Sun Dec 28 08:13:15 2003 From: missive at frontiernet.net (Lee Harr) Date: Sun, 28 Dec 2003 13:13:15 GMT Subject: sys.path[0] in IDLE References: Message-ID: On 2003-12-27, Gabriel Genellina wrote: > At 26/12/2003 22:25, you wrote: > >>Am I reading this correctly? >> >>http://python.org/doc/current/lib/module-sys.html >> >>""" >>As initialized upon program startup, the first item of this list, >>path[0], is the directory containing the script that was used to >>invoke the Python interpreter. >>""" >> >> >>So, sys.path[0] should be the directory that my script is in? >> >>Even if running the script from IDLE? >> >>Has anyone else had problems with this? Especially on windows? > > (Read the remaining of the paragraph too) > When using IDLE, the "script" is really idle.py. If you start IDLE with > another script as an argument, its dir is prepended in sys.path > > So, are you saying you do not see your script as sys.path[0] also? That seems like a bug to me. It works fine for me on FreeBSD 4.9 with python 2.3, so it can't be that IDLE needs to have its own directories in the path before mine. What do others get saving this script in IDLE and running it? # /usr/home/lee/python/idle_test/foo/bar.py import sys print sys.path IDLE 1.0.2 >>> import sys >>> print sys.path ['/usr/home/lee', '/usr/local/bin', '/usr/local/lib/python23.zip', ...] >>> # now open /usr/home/lee/python/idle_test/foo/bar.py and run the script >>> ================================ RESTART ================================ >>> ['/usr/home/lee/python/idle_test/foo', '/usr/home/lee', '/usr/local/bin', ...] >>> From bhan at andrew.cmu.edu Thu Dec 25 13:07:49 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Thu, 25 Dec 2003 13:07:49 -0500 (EST) Subject: Socket Programming In-Reply-To: References: Message-ID: On Thu, 25 Dec 2003, Kamuela Franco wrote: > Can someone give me some general information on socket programming in > Python. > > trainee http://www.amk.ca/python/howto/sockets/sockets.html From max at alcyone.com Thu Dec 25 14:45:04 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 25 Dec 2003 11:45:04 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: <3FEB3E40.9564964A@alcyone.com> Mark Carter wrote: > > > - FWIW I'm a proponent of MIT / BSD style "do whatever you want with it" > > open source licenses, not GPL. I believe if you're going to give something > > Microsoft have always complained that GPL-ish licences "infect" > everything they touch (yes, yes, I'm perfectly aware of the irony). I > was thinking that, if more stuff was released into the Public Domain - > then that would be a good thing. It might actually be a benefit for > Microsoft to rip off good quality PD work. If they got it for free, > then they might be less inclined to roll there own "feature rich" > solutions, and instead opt for a more conventional approach. There's plenty of MIT, BSD, and public domain code which Microsoft has "appropriated" for their own purposes. It's a part of why they're so successful. > There might be a chance - and of course I emphasis the word "might" - > that they would contribute, in some small way, to ongoing PD efforts. That chance is about as close to zero as you can get, since they're already have no problem using public domain and the like code and have made no effort of ever releasing something back. Part of their business model is to buy software, buy the rights to software, or use public doman/MIT/BSD software, modify it by adding their own lock-in features, then sell it. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ I have not yet begun to right! -- John Paul Jones From tim.golden at viacom-outdoor.co.uk Tue Dec 30 08:51:04 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 30 Dec 2003 13:51:04 -0000 Subject: Monitoring an MS Exchange mailbox Message-ID: >From: Lindstrom Greg - glinds [mailto:Greg.Lindstrom at acxiom.com] > [... snip 3 possibilities ...] >Thank-you! This fixes the problem; I'm off and running. Glad to hear it. Sometimes it's the small things... >one of the reasons I prefer Python over Perl >is that the Python community does not appear >to be as hostile towards MS I'm not familiar with the Perl community, but my experience of the Python one is that it is just about as sane and helpful as you're going to get anywhere. That's not to say that you won't get acerbic responses to foolish questions; but you'll probably find that someone will answer them anyway! >I'm assuming MSDN is Microsoft Developer's Network? >Is that a subscription service? Sorry. I assumed... It probably exists in some enhanced form if you pay, but for most of us, it's the result of Googling, eg, for MAPI CDO session, and hitting [I'm Feeling Lucky]. (This URL may get truncated/wrapped; it's 109 chars long). http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdo/html/_o lemsg_starting_a_cdo_session.asp > Now that I can monitor the mailbox, I'd like to delete message > once they've been processed and would like to see the documentation > on how to do it as well as other things. Googling for CDO delete message gives this as the second hit (again, a long URL): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdo/html/_o lemsg_delete_method_message.asp If you need examples, let me know. I'm trying to put together a Python CDO examples webpage, but keep getting sidetracked. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From sminni_spam_diverter at planage.com Sat Dec 6 11:01:25 2003 From: sminni_spam_diverter at planage.com (Sanjay Minni) Date: Sat, 6 Dec 2003 21:31:25 +0530 Subject: wxPython 2.4.2.4 segmentation fault on (Python 2.2.2 SuSE 8.2) References: <4fe109d.0312060045.484de598@posting.google.com> Message-ID: Note that we used GTK1 i.e. compiled without the GTK2 option on SuSE 8.2 Thanks Sanjay Minni From skip at pobox.com Wed Dec 3 16:37:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Dec 2003 15:37:55 -0600 Subject: reloading modules In-Reply-To: <022d01c3b9e1$4349dc40$8f0a500a@jsbwxp3> References: <022d01c3b9e1$4349dc40$8f0a500a@jsbwxp3> Message-ID: <16334.22451.222696.345764@montanaro.dyndns.org> John> Reload will reload the specified module, but will not recursively John> reload modules imported by the specified module, sorry. Nor adjust references to objects in the reloaded module. % python Python 2.4a0 (#6, Dec 2 2003, 13:06:05) [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import foo >>> from foo import a >>> foo.a, a (42, 42) >>> [1]+ Stopped python montanaro:tmp% cat > foo.py a = 99 montanaro:tmp% fg python reload(foo) >>> foo.a, a (99, 42) Skip From edreamleo at charter.net Tue Dec 2 09:48:50 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 2 Dec 2003 08:48:50 -0600 Subject: wxPython / styles and marks in TextCtrl References: Message-ID: > Yes, StyledTextCtrl is a wrapper for Scintilla; the wxPython > documentation for it can be found here: > > http://www.pyframe.com/wxdocs/stc/index.html Thanks for this link. I'll be using it soon to give a wxPython look to Leo. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From edvard+news at majakari.net Thu Dec 11 14:54:28 2003 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 11 Dec 2003 21:54:28 +0200 Subject: Python code to replace shell scripts References: Message-ID: <87d6av3zbf.fsf@titan.staselog.com> "Daven Nair" writes: > > I would like to know if Python supports codes similar to shell scripts: > > count=`ps -ef|grep "pattern"|wc -l` > for count in `echo $count` > do > done > fi See 'pydoc commands'. You could probably do with pattern = "" cmd_status, count = commands.getstatusoutput("ps -ef|grep -c %s" % pattern) for i in range(count): # do something count times Note: you don't need wc -l after grep, because grep has '-c' switch. Note2: not tested, some typos etc may be present. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From phil.hornby at accutest.co.uk Mon Dec 29 17:04:29 2003 From: phil.hornby at accutest.co.uk (Phil Hornby) Date: Mon, 29 Dec 2003 22:04:29 -0000 Subject: argument list In-Reply-To: <87zndcmlp8.fsf@pobox.com> Message-ID: >> I am working on a solution embedding Python in an app that will looks for >> specific string combination within the function names to determine if a >> handler for an event exists; I have been able to extract the function names >> and find all of the 'fields' of interest. What I am concerned about, >> however, is that they could have the wrong argument profile, as specific >> handlers will have specific function arguments - can I find out what >> arguments a specific functions takes from the C-API? As I don't seem to be >> able to find anything...but I could be just being blind... >[...] > >First, maybe what you really want is just the equivalent of >func(*args, **kwds)? (don't remember off the top of my head how to do >that) > >Or maybe what you're missing is that you can just use different method >naming conventions for different kinds of handler? What I am doing is basically looking for a function with a name like: def on_canmsg( id, dlc, data, time ): ## catch all for CAN messages ## do something def on_canmsg_100( id, dlc, data, time): ## message id 100 handler ## do something different Based on the function name I know that the first is a catch all for CAN messages and the second is for handling a message with an identifier of 100. The big BUT that I have is what if they define the functions like below: def on_canmsg( a, b ): ## catch all for CAN messages ## incorrect arguments Then when the function is called from the C-API it would not do as it should. So what I want to do is to inspect the list of argument names, I know I can't check what types the function composer uses/assumes but if I can atleast check the names they use then I will have atleast some confidence in the function being correct. I need to do this from the C-API and would rather avoid having to call a script to check a script. So any suggestions? TIA Phil From roy at panix.com Fri Dec 5 11:18:00 2003 From: roy at panix.com (Roy Smith) Date: Fri, 05 Dec 2003 11:18:00 -0500 Subject: Lists and Tuples References: Message-ID: I just stumbled upon an interesting tuple/list dichotomy. The new isinstance() function can take a tuple (but not a list) as its second argument. Why? Logically, it should take any sequence. The operation it's doing is essentially: for aType in sequence: if isinstance (thing, aType): return True return False I don't see any reason it should reject a list, but it does: >>> isinstance (1, [str, int]) Traceback (most recent call last): File "", line 1, in ? TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types This is documented, but it still seems strange. Why go out of your way to reject a list when a list is really a perfectly reasonable thing to pass in that context? Same deal with issubclass(). From bokr at oz.net Sun Dec 7 13:34:32 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Dec 2003 18:34:32 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On 07 Dec 2003 10:08:37 +0100, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >bokr at oz.net (Bengt Richter) writes: > >> Ok, I'm happy with that. But let's see where the errors come from. >> By definition it's from associating the wrong encoding assumption >> with a pure byte sequence. > >Wrong. Errors may also happen when performing unexpected conversions >from one encoding to a different one. ISTM that could only happen e.g. if you explicitly called codecs to convert between incompatible encodings. That is normal, just like >>> float(10**309) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to float is a normal result. Otherwise "unexpected conversions" must happen because of some string expression involving strings of different encodings, in which case it is like >>> 10**308 * 10.0 1.#INF (Which BTW could be argued (but I won't ;-) should also be the result of float(10**309)). So here is a case where information was lost, because there was no information-preserving representation available. If we used an exact numeric form, e.g., and exact decimal I was experimenting with, we can do >>> from ut.exactdec import ED >>> ED(10**308) * ED(10.0, 'all') ED('1.0e309') (The 'all' is a rounding parameter indication to capture all available accuracy bits from a floating point arg to the constructor and call the result exact. Integers or longs are naturally exact, so don't require that parameter). Anyway, that's analogous to an expression involving, e.g., s1 = u'abc'.encode('utf-8') and s2 = u'def'.encode('latin-1') In my scenario, you would have assert s1.coding == 'utf-8' assert s1.bytes() == a'abc' # bytes() gets the encoded byte sequence as pure str bytes assert s2.coding == 'latin-1' assert s2.bytes() == a'def' so s3 = s1 + s2 would imply s3 = (1.bytes().decode(s1.coding) + s2.bytes().decode(s2.coding)).encode(cenc(s1.coding, s2.coding)) where lcenc is a function something like (sketch) def cenc(enc1, enc2): """return common encoding""" if enc1==enc2: return enc1 # this makes latin-1 + latin-1 => latin-1, etc. if enc1 is None: enc1 = 'ascii' # notorios assumption ;-) if enc2 is None: enc2 = 'ascii' # ditto if enc1[:3] == 'utf': return enc1 # preserve unicode encoding format of s1 preferentially return 'utf' # generic system utf encoding which in the above example would get you assert s3.coding == 'utf-8' > >> 1a. Available unambiguous encoding information not matching the >> default assumption was dropped. This is IMO the most likely. >> 1b. The byte sequence came from an unspecified source and never got explicit encoding info associated. >> This is probably a bug or application design flaw, not a python problem. > >1b. is the most likely case. Any byte stream read operation (file, >socket, zipfile) will return byte streams of unspecified encoding. But this is not an error. An error would only arise if one tried to use the bytes as characters without specifying a decoding. > >> IMO a large part of the answer will be not to drop available >> encoding info. > >Right. And this is very difficult, making the entire approach >unimplementable. ISTM it doesn't have to be all or nothing. > >> I hope an outline of what I am thinking is becoming visible. > >Unfortunately, not. You seem to assume that nearly all strings have >encoding information attached, but you don't explain where you expect >this information to come from. Strings appearing as literals in program sources will be assumed to have the same encoding as is assumed or explicitly specified for the source text. IMO that will cover a lot of strings not now covered, and will be an improvement even if it doesn't cover everything. > >> >As I said: What would be the meaning of concatenating strings, if both >> >strings have different encodings? >> If the strings have encodings, the semantics are the semantics of character >> sequences with possibly heterogenous representations. > >??? What is a "possibly heterogenous representation", how do I >implement it, and how do I use it? See example s3 = s1 + s2 above. > >Are you suggesting that different bytes in a single string should use >different encodings? If not, how does suggesting a heterougenous >implementation answer the question of how concatenation of strings is >implemented? See as before. > >> The simplest thing would probably be to choose utf-16le like windows >> wchar UIAM and normalize all strings that have encodings to that > >Again: How does that answer the question what concatenation of strings >means? See as before. > >Also, if you use utf-16le as the internal encoding of byte strings, >what is the meaning of indexing? I.e. given a string s='Hallo', >what is len(s), s[0], s[1]? If s.coding is None, it's the same as now. Otherwise len(s) <-> len(s.decode(s.coding)) e.g. >>> s = 'L\xf6wis' >>> s8 = s.decode('latin-1').encode('utf-8') >>> s8 'L\xc3\xb6wis' >>> len(s8) 6 >>> len(s) 5 >>> len(s8.decode('utf-8')) 5 s[0] and s[1] create new encoded strings if they are indexing encoded strings, and preserve the .coding info. So e.g., in general, when .coding is not None, s[i] <-> s.decode(s.coding)[i].encode(s.coding) (This is semantics, let's not prematurely talk about optimization ;-) >>> s8 # current display of the bytes of utf-8 encoding in s8 'L\xc3\xb6wis' >>> s8[0] # wrong when .coding is not None 'L' >>> s8_0 = s8.decode('utf-8')[0].encode('utf-8') >>> s8_1 = s8.decode('utf-8')[1].encode('utf-8') >>> s8 'L\xc3\xb6wis' >>> s8_0 'L' >>> s8_1 '\xc3\xb6' and assert s8_0.coding == s8_1.coding == 'utf-8' would hold for results. > >> Instead, the latter could become explicit, e.g., by a string prefix. E.g., >> >> a'...' >> >> meaning a byte string represented by ascii+escapes syntax like >> current practice (whatever the program source encoding. I.e., >> latin-1 non-ascii characters would not be allowed in the literal >> _source_ representation even if the program source were encoded in >> latin-1. (of course escapes would be allowed)). > >Hmm. This still doesn't answer my question, but now you are extending >the syntax already. > >> IWT .coding attributes/properties would permit combining character >> strings with different encodings by promoting to an encoding that >> includes all without information loss. > >No, it would not - atleast not unless you specify further details. If >I have a latin-1 string ('\xf6'), and a koi-8r string ('\xf6'), and >concatenate them, what do get? An sequence of bytes that is an encoding of the _character_ sequence, such that the encoding is adequate to represent all the characters, e.g., >>> latkoi = ('\xf6'.decode('latin-1') + '\xf6'.decode('koi8_r')).encode('utf') >>> latkoi '\xc3\xb6\xd0\x96' with assert latkoi.coding == 'utf-8' since 'utf' seems to be an alias for 'utf-8' And since .coding is not None, the resulting string length is >>> len(latkoi.decode('utf-8')) 2 > >> Of course you cannot arbitrarily combine byte strings b (b.coding==None) >> with character strings s (s.coding!=None). > >So what happens if you try to combine them? > >> >2. Convert the result string to UTF-8. This is incompatible with >> > earlier Python versions. >> Or utf-16xx. I wonder how many mixed-encoding situations there >> are in earlier code. Single-encoding should not require change >> of encoding, so it should look like plain concatenation as far >> as the byte sequence part is concerned. It might be mostly >> transparent. > >This approach is incompatible with earlier Python versions even for a >single encoding. If I have a KOI-8R s='\xf6' (which is the same as >U+0416), and UTF-16 is the internal represenation, and I do s[0], what >do I get, and what algorithm is used to compute that result? if you have s='\xf6' representing a KOI-8R character, you have two pieces of info. The bare bytes would have s.coding == None. (I suggested a literal format a'\xf6' for pure bytes, so let's say s = a'\xf6' but you want that interpreted as KOI-8R, so we have to decode it according to that, and then re-encode to get a byte string with .coding set: s = s.bytes().decode('koi8_r').encode('koi8_r') e.g. >>> '\xf6'.decode('koi8_r').encode('koi8_r') '\xf6' (which seems like it could be optimized ;-) But you mention an "internal representation" of UTF-16. I'm not sure what you mean, (though I assume unicode is internally handled for u'...' strings in utf-16le/wchar_t format in most PCs) except you could certainly have a string with that explicit .coding format, e.g., >>> s16 = '\xf6'.decode('koi8_r').encode('utf-16') >>> s16 '\xff\xfe\x16\x04' and then assert s16.coding == 'utf-16' would pass ok. Note the BOM. Still the length (since s16.coding is not None) is >>> len(s16.decode('utf-16')) 1 If s.coding is None, you could say length was len(s.bytes().decode('bytes')) and say it was optimized away, I suppose. In other words, when s.coding is not None, you can think of all the possibilities as alternative representations of s.bytes().decode(s.coding) where .bytes() is a method to get the raw str bytes of the particular encoding, and even if s.coding is None, you could use the virtual 'bytes' character set default assumption, so that all strings have a character interpretation if needed. > >> socket_or_file.read().coding => None >> >> unless some encoding was specified in the opening operation. > >So *all* existing socket code would get byte strings, and so would all >existing file I/O. You will break a lot of code. Why? > >> Remember, if there is encoding, we are semantically dealing with >> character sequences, so splicing has to be implemented in terms of >> characters, however represented. > >You never mentioned that you expect indexing to operate on characters, >not bytes. That would be incompatible with current Python, so I was >assuming that you could not possibly suggest that approach. It would normally be transparent, I think, and mostly optimize away, except where you have programs with mixed encodings. > >If I summarize your approach: >- conversion to an internal represenation based on UTF-16 Only as needed. Encodings would not arbitrarily be changed. >- indexing based on characters, not bytes if the bytes represent an encoded character sequence as indicated by s.coding, yes, but the result is another (sub)string with the same s.coding, and might be encoded as a single byte or several (as sometimes in utf-8). I.e., from above, semantically: s[i] <-> s.decode(s.coding)[i].encode(s.coding) # with result having same .coding value > >I arrive at the current Unicode type. So what you want is already >implemented, except for the meaningless 'coding' attribute (it is >meaningless, as it does not describe a property of the string object). > >> >No, in current Python, there is no doubt about the semantics: We >> >assume *nothing* about the encoding. Instead, if s1 and s2 are > ^^^^^^^^^^^^^^^^-- If that is so, why does str have an encode method? > >By mistake, IMO. Marc-Andre Lemburg suggested this as a generalization >of Unicode encodings, allowing arbitrary objects to be encoded - he >would have considered (3).encode('decimal') a good idea. With the >current encode method on string objects, you can do things like >s.encode('base64'). I can see the usefulness of that. I guess you have to envisage a hidden transparent s.decode('bytes') before the .encode('base64') so we have a logical round trip. s.decode('bytes') could be conceptualized as producing unicode in a private range U+E000 .. U+E0ff and encoding that range of unicode "characters" could do the right thing. Re-encoding as 'bytes' would restore the original byte sequence, just like any other 1:1 encoding transformation. You could even design a font, like little boxes with the hex values in them ;-) > >> That's supposed to go from character entities to bytes, I thought ;-) > >In a specific case of character codecs, yes. However, this has >(unfortunately) been generalized to arbitrary two-way conversion >between arbitrary things. Well, maybe it can be rationalized via the virtual 'bytes' character encoding (and which in some contexts might make a better default assumption than 'ascii'). > >> Which is why I thought some_string.coding attributes to carry that >> information explicitly would be a good idea. > >Yes, it sounds like a good idea. Unfortunately, it is not >implementable in a meaningful way. I'm still hoping for something meaningful. See above ;-) I'm tempted to subclass str, to play with it, but not right now ;-) Regards, Bengt Richter From jmdeschamps at cvm.qc.ca Sun Dec 21 21:02:54 2003 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 21 Dec 2003 18:02:54 -0800 Subject: The Truth? References: Message-ID: <3d06fae9.0312211802.66ad7944@posting.google.com> "TyBriD" wrote in message news:... > i have 100% no programming experience but i have read some VB6 and parts of > C++ books never stuck with it because it was to confusing, but i was told > python is a great place to start is that true?. if so is there specifi parts > to learn and start off with n why links would be great thanks. try http://honors.montana.edu/~jjc/easytut/easytut/easytut.html also included in the help from ActiveState's ActivePython, happy programming, jean-marc From aahz at pythoncraft.com Sun Dec 21 11:01:17 2003 From: aahz at pythoncraft.com (Aahz) Date: 21 Dec 2003 11:01:17 -0500 Subject: What's going on with python.org References: <56f42e53.0312192013.333cfeef@posting.google.com> Message-ID: In article , Ben McGinnes wrote: >Aahz(aahz at pythoncraft.com)@Sat, Dec 20, 2003 at 12:20:46AM -0500: >> In article <56f42e53.0312192013.333cfeef at posting.google.com>, >> sebb wrote: >>> >>>Just want to know why python.org is down. >> >> Tell your DNS provider to do a reload. > >Given it was just a slightly broken re-delegation, it's more feasible >for most people to have waited for usual DNS propagation than try to >convince their upstreams/ISPs to reload their DNS servers for one >non-local domain's benefit. Most ISP staff would take one look at >such a request and snicker. Yes. It was a joke. Guess I shoulda been clearer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From ville.spammehardvainio at spamtut.fi Sat Dec 20 07:36:41 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 20 Dec 2003 14:36:41 +0200 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" writes: > > > a third is the ability to forget the empty parenthesis after > > > a function/method call that doesn't require parameters. > > Doesn't this suck big time? How can the interpreter tell whether you > > are trying to call a function or just want a reference to a callable > > object? > That's the crux of the implementation issue, and I, for one, > haven't got an answer that doesn't look real ugly (let alone > break backwards compatability.) That's why I'm not pushing > this particular issue seriously - I don't see a way of doing it, > given the rest of Python, and completely independently of any > "Python philosophy" issues. Most importantly, why would anyone even care? Ability to optionally invoke a "call" operation on an object implicitly seems utterly worthless to me. It has the feel of perl philosophy (regexps in language syntaxm anyone? ), and it's not the only instance in Ruby. I don't really like the Perl philosophy (like most of the people who "get" Python), and I don't really believe a language whose designers appreciate the perlisms poses a serious threat to Python. Not even if they got some things right. > to Python. Maybe the fact that such industry heavy hitters as Robert > Martin, David Thomas, and any number of others have switched Frankly, I don't know who these "heavy hitters" are, but they probably have their reasons. Quick googling didn't turn out any useful articles explaining why either of them has switched from Python to Ruby. > As far as doing the "right" thing, check the partial list of Ruby > features I gave, and ask yourself how much each of them would > break the "feel" of Python. I am yet to see a feature list that would inspire me to switch, or even consider switching. The little advantages Ruby has over Python are dwarfed by the advantages of Python (of which the least is not maturity, community and documentation). -- Ville Vainio http://www.students.tut.fi/~vainio24 From stuart.b at commonground.com.au Tue Dec 9 21:00:51 2003 From: stuart.b at commonground.com.au (Stuart Bishop) Date: Wed, 10 Dec 2003 13:00:51 +1100 Subject: Speed: bytecode vz C API calls In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 10/12/2003, at 8:55 AM, Jacek Generowicz wrote: > Peter Otten <__peter__ at web.de> writes: > >> Jacek Generowicz wrote: >> >>> aahz at pythoncraft.com (Aahz) writes: >>> >>>> I think you're going to need to write a solution that doesn't call >>>> functions (function unrolling, so to speak). Instead of returning a >>>> memoizer function, just use a dict of dicts. >>> >>> Sounds interesting. But how do I get the dictionary to use the >>> function which it is memoizing, to calculate values which haven't >>> been >>> cached yet? >> >> Guessing into the blue: >> >> try: >> result = cache[fun, args] >> except KeyError: >> result = cache[fun, args] = fun(args) > > Allow me to remind you of the memoizer I posted at the top of the > thread: > > def memoize(callable): > cache = {} > def proxy(*args): > try: return cache[args] > except KeyError: return cache.setdefault(args, > callable(*args)) > return proxy > > One key feature of this is that I can use it to replace any[*] > function with a functionally equivalent but faster one, without having > to change any of the call sites of the original. > proxy does. However, it's the "almost" that creates the problem. If > I'm prepared to mess around with the calls to the original functions > and replace them with your suggestion, then, of course the problem is > solved ... however, I _really_ do not want to replace the calls to the > original ... About the only thing that could be done then is: def memoize(callable): cache = {} def proxy(*args, _cache=cache): try: return _cache[args] except KeyError: return cache.setdefault(args, callable(*args)) return proxy Might help a little bit, although probably not enough. - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (Darwin) iD8DBQE/1n5TAfqZj7rGN0oRAlSQAJ9WZe39F8L1KECCMTS3HxUnWKGx8wCgjZ8P 68pLTP33rlFI0eSEHK8FVXY= =25Fx -----END PGP SIGNATURE----- From jsbenson at bensonsystems.com Mon Dec 8 22:07:30 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Mon, 8 Dec 2003 19:07:30 -0800 Subject: drag-and-drop GUI interface builder for Tkinter? Message-ID: <077f01c3be01$968b4460$210110ac@jsbwxp3> I was looking at the Scriptics/Tcl website and followed a link to a Tk GUI builder called Gypsy. I'm just curious to know if there's any Tk GUI builder utility available to me in the Python environment. From charles at steinkuehler.net Tue Dec 16 07:49:46 2003 From: charles at steinkuehler.net (Charles Steinkuehler) Date: Tue, 16 Dec 2003 06:49:46 -0600 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: <7xwu8xes00.fsf@ruckus.brouhaha.com> References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > claird at lairds.com (Cameron Laird) writes: >> I think your decision in favor of Lua's a good one. Guile and >> Scheme, from the last I saw of them, are *not* slender enough to >> compete. Forth is the one other serious language that can be tiny >> enough to make Lua look stout; while Forth hasn't made a good >> impression on me as a "configuration language", that might reflect >> my limits more than Forth's. > > There are Scheme subsets like SIOD which are much smaller than either > Guile or Lua. Forth is a little bit too contorted for my tastes, but > there was once an Emacs-like editor that used something close to it as > an extension language. PostScript, of course, also strongly resembles > Forth. A minimal Forth can be even smaller than SIOD, but SIOD is > pretty small and I'd probably use something like it in preference to > Forth in any but the tiniest environments. I could be wrong, but it looks to me like SIOD requires a C runtime library to function. One of the big attractions of using Forth (at least to me) is it's lack of reliance on a runtime library. Direct interfacing to the linux kernel should be possible in an architecture-neutral manner, and the ~10K overhead of a Forth kernel is very minimal when compared to the ~75K overhead of SIOD (from the website) + the hundreds of KBytes (if not MegaBytes) of overhead for the runtime C library. The firewall oriented linux distribution I work with uses a shell-script based linuxrc to build an initial root ramdisk. Currently this requires ash (~90K), busybox (~125K as configured), and ~625K for an old (and smallish) version of glibc. Using a forth-based solution to create the root ramdisk image would drastically reduce the footprint of the initial ramdisk image, remove reliance on a particular C runtime library (allowing folks to build runtime root images based on uClibc, glibc, or whatever), and provide a *VERY* powerful yet tiny runtime scripting/programming language for extending the system. The main utilities/functionality needed to bootstrap should be pretty simple, likely 10-15 'standard' linux commands (like mkdir, mknod, tar, gzip, etc), and a scripting language (forth itself). I hope to get around to implementing something like this in Forth "one of these days", but with 4-1/2 month old twins, my free time for open-source projects has pretty much evaporated, so I'm sort of hoping someone else beats me to it! :) -- Charles Steinkuehler charles at steinkuehler.net From fumanchu at amor.org Fri Dec 19 13:24:26 2003 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 19 Dec 2003 10:24:26 -0800 Subject: dynamic typing questions Message-ID: John Roth wrote: > Look into Test Driven Development (see Kent > Beck's book by that title.) As Jason says, unit testing > will pretty much eliminate any advantages of static typing, > leaving only the disadvantages. > > Also, pervasive testing has so many other advantages > that I'm beginning to think that debuggers were the > single worst invention in history. Zuh? Unit testing doesn't replace a good debugger; they work together. Unit testing can only show you THAT a test has failed--it can't show you where, how, or why. Think of exception handling (and especially tracebacks) as a mini-debugger. FuManChu From newsgroups at jhrothjr.com Sun Dec 28 13:48:36 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Dec 2003 13:48:36 -0500 Subject: pointers References: Message-ID: "km" wrote in message news:mailman.142.1072628533.684.python-list at python.org... > Hi all, > > may i know if there is any plans of introducing the concept of pointers into python language as in C ? (atleast in future versions ?) Outside of the sheer, unadulterated wrongheadedness of the idea, it occured to me to wonder. How would one do this, and what benefit would it serve? Today, one can bind anything to almost anything, so I'm having some inability to see what one would do with pointers. John Roth > > regards, > thanks > KM > > > From niemeyer at conectiva.com Tue Dec 16 12:25:51 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Tue, 16 Dec 2003 15:25:51 -0200 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: <7xwu8xes00.fsf@ruckus.brouhaha.com> References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: <20031216172551.GB5781@burma.localdomain> >There are Scheme subsets like SIOD which are much smaller than either >Guile or Lua. I have just downloaded SIOD and after fixing several compilation bugs (it looks awfuly linux-unfriendly), I got a 145kb shared library. The language also seems to be unmaintained since 96. >Forth is a little bit too contorted for my tastes, but Agreed. I could even manage to learn it, but my main problem, at least while looking for an embeddable language for APT-RPM, was that the choosed language should be friendly to the users, not just to myself. >there was once an Emacs-like editor that used something close to it as >an extension language. PostScript, of course, also strongly resembles >Forth. A minimal Forth can be even smaller than SIOD, but SIOD is >pretty small and I'd probably use something like it in preference to >Forth in any but the tiniest environments. I'm aware that Forth has large usage cases in very small embedded systems. This fact certainly increases my interest in the language. -- Gustavo Niemeyer http://niemeyer.net From cartermark46 at ukmail.com Tue Dec 30 14:05:53 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 30 Dec 2003 11:05:53 -0800 Subject: twisted mail server - SMTP AUTH extension not supported Message-ID: I'm trying to create a mail server in Twisted. I either get SMTPSenderRefused or SMTPException: SMTP AUTH extension not supported by server. What do I need to do to get it to work? --- Here is the server: from twisted.internet import reactor from twisted import mail import twisted.mail.mail import twisted.mail.maildir service = mail.mail.MailService('ExampleMail') smtp = service.getSMTPFactory() pop3 = service.getPOP3Factory() domain = mail.maildir.MaildirDirdbmDomain(service, '/temp') domain.addUser('salvador', 'gala') service.addDomain('dali', domain) reactor.listenTCP(25, smtp , interface='dali') reactor.listenTCP(110, pop3 , interface='dali') reactor.run() --- Here is the client that tries to send an email: import smtplib from email.MIMEText import MIMEText addr = 'salvador at dali' msg = MIMEText('Body of message') msg['From'] = addr msg['Subject'] = 'Note to myself' msg['To'] = addr server = smtplib.SMTP('dali') server.login('salvador', 'gala') # see note 1 server.sendmail(addr, addr ,msg.as_string()) server.quit() --- Notes: 1. If I keep in the line: server.login('salvador', 'gala') # see note 1 the client complains: server.login('salvador', 'gala') File "C:\Python23\lib\smtplib.py", line 546, in login raise SMTPException("SMTP AUTH extension not supported by server.") SMTPException: SMTP AUTH extension not supported by server. If I comment it out, the client complains: SMTPSenderRefused: (451, 'Requested action aborted: error in processing', 'salvador at dali') and the server prints the message: Failure: twisted.cred.error.UnhandledCredentials: No checker for twisted.cred.credentials.IAnonymous, twisted.cred.credentials.ICredentials ... smtp.py:553: DeprecationWarning: Returning None from validateFrom is deprecated. Raise smtp.SMTPBadSender instead "Raise smtp.SMTPBadSender instead", DeprecationWarning" From fredrik at pythonware.com Wed Dec 17 08:50:01 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Dec 2003 14:50:01 +0100 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: Paul Boddie wrote: > >From "Contracts and Interoperability - A Conversation with Anders > Hejlsberg, Part V" [1]: > > "Anders Hejlsberg, a distinguished engineer at Microsoft, > led the team that designed the C# (pronounced C Sharp) > programming language... In 1996, after 13 years with > Borland, Hejlsberg joined Microsoft, where he initially > worked as an architect of Visual J++..." > > I'm no big fan of Sun or Java, but that's quite some industry > leadership you're showing us, Brandon. ;-) eh? are you saying that all Hejlsberg knows about programming language design is stuff he picked up while working on a Java implementation? From http Wed Dec 10 07:19:53 2003 From: http (Paul Rubin) Date: 10 Dec 2003 04:19:53 -0800 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: <7xwu94sw46.fsf@ruckus.brouhaha.com> Aaron Watters writes: > The xsdb package is implemented in Python, and the server mode > requires stackless python. What is it doing with stackless? From aaron at reportlab.com Thu Dec 4 13:56:54 2003 From: aaron at reportlab.com (Aaron Watters) Date: 4 Dec 2003 10:56:54 -0800 Subject: graphs in python... References: Message-ID: <9a6d7d9d.0312041056.760fefde@posting.google.com> "Diez B. Roggisch" wrote in message news:... > Douglas F. Calvert wrote: > > > Hello, > > I read "Python Patterns: Implementing Graphs" ... > > Maybe its faster to store the adjacences in a matrix (e.g. Numeric array) - > some graph ops then are simple matrix ops. That will work if the graph is extremely dense. If it is not I don't think it is a good idea. Please also look at kjbuckets available as part of the gadfly package as either kjbuckets0.py or kjbucketsmodule.c. http://gadfly.sourceforge.net http://cvs.sourceforge.net/viewcvs.py/gadfly/gadfly/kjbuckets/ http://cvs.sourceforge.net/viewcvs.py/gadfly/gadfly/gadfly/kjbuckets0.py --Aaron Watters ps: off topic http://xsdb.sourceforge.net === An apple every 8 hours will keep 3 doctors away. --kliban From duncan at NOSPAMrcp.co.uk Mon Dec 1 04:02:16 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 1 Dec 2003 09:02:16 +0000 (UTC) Subject: Using and Implementing iterators with classes such as linked lists References: Message-ID: Adelein and Jeremy wrote in news:mailman.1210.1070252201.702.python-list at python.org: > AFAIU, in my LinkedList class, I can either have the LinkedList be > its > own iterator by making its __iter__() method return self and defining > a next() method, or I can have a separate iterator called from > LinkedList's __iter__(). My view is that it would be best to have the > LinkedList be its own iterator - is that the case? Or is an external > iterator preferable in this case? > It sounds a very bad idea to have LinkedList be its own iterator. If you did that then you could only have one iteration over each list at a time. In practical use, you will find that you want to iterate over a list, and you don't know or care whether another piece of code is already iterating over the same list. The easiest way to handle it here is to use a generator to do the actual iteration: def __iter__(self): def iterate(current): while current.next is not None: next = current.next yield current current = next return iterate(self) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bignose-hates-spam at and-benfinney-does-too.id.au Thu Dec 4 22:11:52 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 5 Dec 2003 14:01:52 +1050 Subject: regexp question References: Message-ID: On Fri, 05 Dec 2003 02:26:53 -0000, python_charmer2000 wrote: > re1 = > re2 = > re3 = > > big_re = re.compile(re1 + '|' + re2 + '|' + re3) > > Now the "match.re.pattern" is the entire regexp, big_re. But I want > to print out the portion of the big re that was matched -- was it re1? > re2? or re3? Is it possible to determine this, or do I have to make > a second pass through the collection of re's and compare them against > the "matched text" in order to determine which part of the big_re was > matched? That will work no matter what your regexes hapen to be, and is easily understood. Implement that, and see if it's fast enough. (Doing otherwise is known as "premature optimisation" and is a bad practice.) In fact, it may be better (from a readability standpoint) to simply compile each of the regexes and match them all each time. An alternative, if it's not fast enough: Group the regexes and inspect them with the re.MatchObject.group() method. >>> import re >>> regex1 = 'abc' >>> regex2 = 'def' >>> regex3 = 'ghi' >>> big_regex = re.compile( ... '(' + regex1 + ')' ... + '|(' + regex2 + ')' ... + '|(' + regex3 + ')' ... ) >>> match = re.match( big_regex, 'def' ) >>> match.groups() (None, 'def', None) >>> match.group(1) >>> match.group(2) 'def' >>> match.group(3) >>> -- \ "As the evening sky faded from a salmon color to a sort of | `\ flint gray, I thought back to the salmon I caught that morning, | _o__) and how gray he was, and how I named him Flint." -- Jack Handey | Ben Finney From lkcl at lkcl.net Tue Dec 16 16:23:12 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 21:23:12 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> Message-ID: <20031216212312.GL17021@lkcl.net> On Tue, Dec 16, 2003 at 09:14:40PM +0100, Martin v. L?wis wrote: > Luke Kenneth Casson Leighton writes: > > > > Also, it seems that nowhere in your proposal you state how ACLs should > > > be integrated into Python: I.e. what objects are protected by ACLs, > > > > all objects - if an acl is non-null. > > Does this include functions and bound and unbound methods? if it's a function, it can potentially have an ACL (or a better description is CCL - capabilities control list) added, and that CCL applies to all sub-objects of the function. same with objects, classes - everything. > > > 3 * 4 > > > > > > Is that read, write, execute, and which ACL(s) is(are) considered? > > > > execute, and execute only, because there's no I/O involved. > > > > on the multiply operation. > > So what operations require read or write access? short answer: all of them. longer answer: just like with exceptions, that has to be classified according to conventions that are yet to be decided. i propose that, for example, a capability be created to control _file_ read access and _file_ write access, with large provisos on the documentation attached to these two capabilities that ensure they are distinguished from the right to _modify_ an object. basically it's all conventions, just like exceptions are conventions. all i can do is recommend a framework and some guidelines on what conventions could be fitted over that framework. heck, it may even be worthwhile defining a low-level object, named a Capability, just like an Exception is defined, and then expect people to create their own, and recommend the creation of certain Capabilities that are inherited from the Capability base class. > > but _only_ if there's an actual ACL set _on_ the multiply function. > > > > if there's no acl set on the multiply function, there's no > > restrictions on the multiply function. > > So ACLs on the objects 3 and 4 would be irrelevant? well... actually.... no :) but are such ACLs relevant? can you do 3 += 5? no you can't: python throws up a SyntaxError: can't assign to a literal. so, whilst the answer is yes, you _can_ associate an ACL [or better-named, a CCL] with the object "3" and the object "4", i would be surprised if there were any situations where they got... hang on... >>> dir(3) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] yes, i believe it _might_ be relevant to set a CCL on an object "3" because someone might want to restrict how... oh, i dunno... mmm. __setattr__ gets used. >>> 3.__xor__ ^ SyntaxError: invalid syntax oh. maybe not :) however, a UserLong or a UserInt is a different matter. [btw, change of subject: why is there no __eq__, no __gt__, no __le__ in that list above?] > Generalizing this, given a class Foo, with a method bar(), and two > instances foo1 and foo2: > > foo1 = Foo("/etc/passwd") > foo2 = Foo("/tmp/nonexistant.yet") > > and considering the calls foo1.bar() and foo2.bar(): > > Given that *only* the ACL on the operation bar matters: Does that mean > that the calls either both succeed or both fail, for a given caller? i'm not entirely sure what you mean, but let's assume that objects (and their instances!) all have an __set_ccl__() function. let's also define a CCL: deny_ccl = [('all functions', DENY, 'execute')] then, let's try this: foo2 = Foo("/etc/passwd") Foo.bar.__set_ccl__(deny_ccl) foo1 = Foo("/etc/passwd") foo2.bar() // executed okay foo1.bar() *** EXCEPTION: execute capability barred to "all functions". okay, let's try this, first making sure there's no ambiguity by re-setting the CCL on the Foo class: Foo.bar.__set_ccl__(None) okay, now we go: foo3 = Foo("/etc/passwd") foo3.bar() // executed okay foo3.bar.__set_ccl__(deny_ccl) foo3.bar() *** EXCEPTION: execute capability barred to "all functions". note that there are three separate uses of __set_ccl__(). first is to set a CCL on the _class_ Foo. second is to clear a CCL the class Foo. third is to set a CCL on an instance of a Foo object. just to clarify: i _may_ have just violated my own proposal by not setting an "inherited-on-create" capability on the CCL named deny_ccl. the reason for needing to have such a capability is to be able to distinguish between setting CCLs on a class and a CCL being created on an object when an instance _of_ that class is created. this is part of the lesson learned from NT's security model (and originally VMS's) and its implementation. i won't go into more details on this inherit-on-create thing until the rest of the stuff sinks in :) l. From ptmcg at austin.rr.com Mon Dec 29 02:10:15 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 29 Dec 2003 07:10:15 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: wrote in message news:6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com... > Hi, > I've been using constructs(?) like the below. > > def display(instance, start = None, end = None): > > if instance.__class__.__name__ == 'UPCA': > do some UPCA stuff > if instance.__class__.__name__ == 'UPCE': > do some UPCE stuff > > launched by: > > lx = UPCA(sx), where sx is a string > then: > display(lx) > Why don't you just define a display() method on the UPCA and UPCE classes, and instead of display(lx), call lx.display(). If UPCA and UPCE inherit from a common base class (presumably with an abstract or default display() method, but not necessarily), this is called "polymorphism". Something like this: class StringDisplayer(object): def __init__(instance, instring ): instance.dispString = instring class UPCA(StringDisplayer): def display(instance, start = None, end = None): # UPCA-specific display stuff goes here class UPCE(StringDisplayer): def display(instance, start = None, end = None): # UPCE-specific display stuff goes here sx = "abc" lx = UPCA(sx) lx.display() Your example also uses "instance" for the pointer to self, which works okay, but is non-traditional; the conventional name for the self pointer is "self". In general, any time you are if-testing on the class of an object, you are probably doing something polymorphic. If there is common behavior also, put this in the base StringDisplayer class, and invoke it using "super(UPCA,instance).display()" in the display() method of the UPCA class, and likewise in the UPCE class. From dman at dman13.dyndns.org Mon Dec 8 17:24:12 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Mon, 08 Dec 2003 22:24:12 GMT Subject: help with awt and jython References: Message-ID: <24afa1-lej.ln1@dman13.dyndns.org> On 5 Dec 2003 19:01:18 -0800, dave wrote: > Hi, how do you close a program in jython using awt. I get the following error: > > TypeError: windowClosing() too many arguments; expected 1 got 2 > Traceback (innermost last): > (no code object) at line 0 > > when I called System.exit(0) in an event handler from jython. What object is the name 'System' bound to at that point in your program? sys.exit() ought to work just as well, too. -D -- (E)ventually (M)allocs (A)ll (C)omputer (S)torage www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From python at rcn.com Wed Dec 31 16:27:46 2003 From: python at rcn.com (Raymond Hettinger) Date: 31 Dec 2003 13:27:46 -0800 Subject: Newbie: sort list of dictionaries References: <7xy8su7a1k.fsf@ruckus.brouhaha.com> <5b4785ee.0312301440.72fd9348@posting.google.com> Message-ID: <5d83790c.0312311327.16ca75da@posting.google.com> [Sven Brandt] > > > I have a list of dictionaries. I want the elements of the list to be > > > sorted by the value of a key of the dict . > > > > > > Excample: > > > my_list=[{'title': 'foo', 'id': 5, 'text': 'some text'}, > > > {'title': 'bar', 'id': 3, 'text': 'my text'}, > > > {'title': 'bla', 'id': 6, 'text': 'any text'}, ] > > > > > > my_list.sort("by the id value") [Paul Rubin] > > The Pythonic way to do it may not be what you're used to, but once you > > understand it you'll be able to apply the understanding to other areas > > of programming. > > > > The list sort method lets you pass an optional comparison function, > > that takes two items and returns -1, 0, or 1, depending on what order > > the items are supposed to appear in. The comparison function takes > > exactly two args (the items to be compared). You can't pass a third > > arg to specify the field name. You could do something ugly like use a > > global variable, but the preferred way given a field name is to > > construct a brand new comparison function just for that name: > > > > def compare_by (fieldname): > > def compare_two_dicts (a, b): > > return cmp(a[fieldname], b[fieldname]) > > return compare_two_dicts [Wade Leftwich] > Another way to do it, also Pythonic I think, is with the > Decorate-Sort-Undecorate (DSU) pattern: > > unsorted_list = [{'id':99, 'title':'a'},{'id':42, 'title':'b'}, ... ] > decorated_list = [(x['id'],x) for x in unsorted_list] > decorated_list.sort() > sorted_list = [y for (x,y) in decorated_list] > > If performance is a consideration, this is supposed to be much faster > than providing a comparison function to list.sort(). FWIW, direct support for DSU is built into Py2.4: >>> from operator import itemgetter >>> sorted(my_list, key=itemgetter('text')) [{'text': 'any text', 'id': 6, 'title': 'bla'}, {'text': 'my text', 'id': 3, 'title': 'bar'}, {'text': 'some text', 'id': 5, 'title': 'foo'}] Raymond Hettinger From hans at zephyrfalcon.org Thu Dec 11 20:39:48 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 11 Dec 2003 20:39:48 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3FD91C64.4050207@zephyrfalcon.org> Brian Kelley wrote: > I hate wxPython's text widget for most of the reasons you described. > Plus, since we are using python, why isn't there a .write(...) method > for these widgets? Why can't I use a text widget like: > > sys.stdout = TextCtrl(parent) The Wax TextBox (which is based on wxTextCtrl) has had a write() method for a while, for exactly this purpose. (http://zephyrfalcon.org/labs/, look for Wax) > I had to make a wrapper around the text widget to make it behave like a > StringIO() class. It internally did all the necessary conversions to > the strings, but now I can use > > widget.write() > widget.read() > widget.readlines() > widget.seek() > > for line in widget: > pass The TextBox control doesn't have the other methods, mostly because I've never felt the need to do these things. :-) The iterator idea is interesting, though. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From km at mrna.tn.nic.in Thu Dec 18 04:11:18 2003 From: km at mrna.tn.nic.in (km) Date: Thu, 18 Dec 2003 14:41:18 +0530 Subject: documentation Message-ID: <20031218091118.GA3296@mrna.tn.nic.in> Hi all, i am coming from a Perl background. i am now learning python. suppose in Perl, to look at the perdocumentation page for variables in perl one can get the info by invoking perldoc perlvar. how to search for same in Python ? kindly enlighten, thanks, KM From sudipto at alumnux.com Wed Dec 10 03:48:58 2003 From: sudipto at alumnux.com (Sudipto Biswas) Date: Wed, 10 Dec 2003 14:18:58 +0530 Subject: multi-threaded app hangs Message-ID: <013101c3befa$73cbbfa0$3f0aa8c0@arindamlap> Hi, I have written a multi-threaded (about 8 threads) networking application with a text-mode interface. It writes to a trace-file in the background. Additionally I have also given some debug prints to STDOUT from different threads. The program runs fine on Python-2.2.2/RH 8.0. But when I move to Python-2.2.2/RH-9.0 the program behaves oddly. It stops suddenly and *does not* give the continueous stream of expected output in STDOUT and tracefile. On pressing ctrl-Z the hanged program gets suspended. On giving 'fg' command the suspended program comes to foreground, AND AGAIN RUNS FOR SOMETIMES (generates stream of text in STDOUT and tracefile) before it hangs again. This way ctrl-Z and 'fg' if pressed on hang, helps the program to run further. I am using the 'Thread' class to create objects which run as separate threads. Has anybody faced a similar problem? Rgds, Sudipto -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Thu Dec 25 12:14:03 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Dec 2003 17:14:03 GMT Subject: help, function to get variable type References: Message-ID: iip wrote: > Hi All, > > What is the function to check the varible type, for example, below is like > in my clipper language: > > x = valtype(m) > > x will be "N", "C", "A", etc... type(x) will return the type object itself (not a string representing it, but really the type object). If you need to map type objects to strings, there are several ways to do that, of course (e.g., each type object has an attribute __name__ which is just the kind of string one would expect -- 'int', 'str', and so on -- so type(x).__name__ may be a first approximation to the kind of string you're looking for). Alex From http Thu Dec 4 20:23:40 2003 From: http (Paul Rubin) Date: 04 Dec 2003 17:23:40 -0800 Subject: Web authentication References: <7xn0a8qsao.fsf@ruckus.brouhaha.com> <878ylsdu5o.fsf@pobox.com> Message-ID: <7x3cc0dplv.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > Doesn't/shouldn't http://user:passwd at example.com/blah.html work? It ought to but I don't know if urllib supports it. I've always done it the other way, with that FancyURLOpener subclass. > I don't know where that syntax is specified (if anywhere) -- do you > know, Paul? Part of the http spec. From phil.hornby at accutest.co.uk Sun Dec 28 16:10:33 2003 From: phil.hornby at accutest.co.uk (Phil Hornby) Date: Sun, 28 Dec 2003 21:10:33 -0000 Subject: argument list Message-ID: Dear Python List, I am working on a solution embedding Python in an app that will looks for specific string combination within the function names to determine if a handler for an event exists; I have been able to extract the function names and find all of the 'fields' of interest. What I am concerned about, however, is that they could have the wrong argument profile, as specific handlers will have specific function arguments - can I find out what arguments a specific functions takes from the C-API? As I don't seem to be able to find anything...but I could be just being blind... Thanks... -- Phil Hornby From jacek.generowicz at cern.ch Tue Dec 9 05:17:59 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 11:17:59 +0100 Subject: Turning builtin functions into methods. References: Message-ID: Jacek Generowicz writes: > Functions defined in Python have type types.FunctionType, and are > descriptors whose __get__ method turns them into bound or unbound > methods. Functions defined in extension modules have type > types.BuiltinFunctionType, and have no __get__ method. Adding them as > attributes to classes and calling them through an instance of the > class does not result in them being called as methods: self is lost. > > What's the simplest way of getting around this ? By trial and error, I seem to have found that passing None as the second argument (the instance) to new.instancemethod, does the trick. The library reference manual confirms that it is actually supposed to work this way. It's a pity that the builtin documentation does not: Help on built-in function instancemethod: instancemethod(...) Create a instance method object from (FUNCTION, INSTANCE, CLASS). (END) From richardshea at fastmail.fm Mon Dec 29 08:03:41 2003 From: richardshea at fastmail.fm (Richard Shea) Date: 29 Dec 2003 05:03:41 -0800 Subject: strftime - %a is always Monday ? Message-ID: <282f826a.0312290503.398d72cd@posting.google.com> Hi - I'm trying to use strftime to output the day of the week but I find that I always get told it's Monday. I have tried day, month, year etc and all come out correctly but as soon as I use %a I get 'Mon'. I'm running Python 2.3.2 on a Windows 98 machine. Can anyone suggest what the problem might be please ? This is a segment of the code which is manfests the behaviour ... >>> from time import localtime,strftime,time >>> lst1 = ['2003','12','27'] >>> strftime("%A,%d (%w %y %m)",[int(lst1[0]),int(lst1[1]),int(lst1[2]),0,0,0,0,0,0]) 'Monday,27 (1 03 12)' >>> ... whereas the 27th was a Saturday ? thanks richard shea. From thomas.dorn at phreaker.net Mon Dec 29 10:20:56 2003 From: thomas.dorn at phreaker.net (Thomas Dorn) Date: Mon, 29 Dec 2003 16:20:56 +0100 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: On Mon, 29 Dec 2003 15:35:56 +0200, Ville Vainio wrote: > Thomas Dorn writes: > >> In your situation (i.e. trying to build a Windows application which >> is "standard in every conceivable way"), I would not use Python. > > Doesn't using the mfc library (like PythonWin does) enable creating > applications that are "standard in every conceivable way"? Even if there are wrappers for things like the MFC library, I would not say that Python is a "good choice" for writing Windows applications as defined by Pjer (and Pjer was asking whether it Python is a "good choice" for his kind of projects or not). I use Python for 80%+ of my projects (mostly cross-platform) and would normally recommend it for almost any project; but considering the various Microsoft OS (incl. Longhorn) and their differences, I think using C#/.NET (or maybe even C++) is a better choice for some- one in Pjer's situation. From RAPHAELD at Amdocs.com Thu Dec 4 05:17:28 2003 From: RAPHAELD at Amdocs.com (Raphael Drai) Date: Thu, 4 Dec 2003 12:17:28 +0200 Subject: Python Embedding in C++ Message-ID: Hi, Does it is possible to have a Python embedded C++ sample that invokes a Python method by sending my own C++ class. Into the Python script a sample of how to work with the received C++ class (Invoke the object methods or manipulate the class attributes). Thanks a lot for your help. Raphael. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- ------------------------------------------------------------------------------------- The information contained in this message is proprietary of Amdocs, protected from disclosure, and may be privileged. The information is intended to be conveyed only to the designated recipient(s) of the message. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, use, distribution or copying of this communication is strictly prohibited and may be unlawful. If you have received this communication in error, please notify us immediately by replying to the message and deleting it from your computer. Thank you. ------------------------------------------------------------------------------------- From maxm at mxm.dk Mon Dec 22 09:11:55 2003 From: maxm at mxm.dk (Max M) Date: Mon, 22 Dec 2003 15:11:55 +0100 Subject: How do I test if an object is a sequence? Message-ID: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Is there a common idiom for testing if an object is a sequence? Both list, tuple and non-standard objects etc. I have Googled, but didn't find a usable answer. There are a few direct approaches: def is_sequence(unknown): return type(unknown) = type([]) or type(unknown) = type(()) Which is basically the old-school version of: from types import TupleType, ListType def is_sequence(unknown): return isinstance(unknown, (TupleType, ListType)) But they only check for built in objects. Then there is the approach of testing for a method that they all share. The only one that springs to mind is the slice operation. def is_sequence(object) try: test = object[0:0] except: return False else: return True But it has the disadvantage that string also are sequences. But not exactly the kind I am interrested in. So it will need to be expanded to: from types import StringTypes def is_sequence(unknown): if isinstance(unknown, StringTypes): return False try: test = object[0:0] return True except: return False But that looks kind of ugly for a "simple" type check. There must be a better way? regards Max M From chouyiyu at hotmail.com Sun Dec 14 17:03:24 2003 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Sun, 14 Dec 2003 22:03:24 +0000 Subject: How to integrate python, vtk and C++ object ? Message-ID: Dear all, I need to integrate python, vtk and my own C++ object. Is it possible to do it by using python/C API ? Or there is a more efficient way to do it. Where can I find the examples taking about that ? Thanks in advance !!! Best, YY _________________________________________________________________ ????????MSN ?????? Match.com ???????????????? ? http://match.msn.com.tw From nospam at nopes Mon Dec 15 21:47:17 2003 From: nospam at nopes (Steve) Date: Tue, 16 Dec 2003 13:47:17 +1100 Subject: 'piping' output In-Reply-To: <3fde6b27$1@clarion.carno.net.au> References: <3fde6b27$1@clarion.carno.net.au> Message-ID: <3fde720e$1@clarion.carno.net.au> Steve wrote: > Hi, > > I want to know if I can 'pipe' output from a program into a python > script. Is that possible? I need to pipe some output at runtime from a > program written in C and I want to parse it/use it in a python script. > I'm new so please bear with me. thanks > > > Steve > Just figured it out using popen2() :) Steve From http Tue Dec 30 08:27:34 2003 From: http (Paul Rubin) Date: 30 Dec 2003 05:27:34 -0800 Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> Message-ID: <7xhdzijv09.fsf@ruckus.brouhaha.com> "EsC" writes: > is it possible to pass function-arguments by reference? > (for example in PHP you can use the "&" operator ... ) No. If there's a specific situation you want to handle, say what it is and someone will say how to deal with it in Python. For example if you want a function that returns multiple values, just return a list: def get_three_nums (): return (2, 3, 5) a, b, c = get_three_nums () sets a=2, b=3, and c=5. You don't have to do anything kludgy like "get_three_nums (&a, &b, &c)" or whatever. If you want to swap two variables, you can just use a list assignment like in perl: (x, y) = (y, x) From jay at jaydorsey.com Wed Dec 3 16:11:15 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Wed, 3 Dec 2003 15:11:15 -0600 Subject: Python bounties Message-ID: <20031203211115.GA4262@gentoo.Earthlink.net> Just read this page linked from http://slashdot.org/: http://www.markshuttleworth.com/bounty.html The /. article mentions bounties for the completion of tasks related to the Mozilla project. I actually decided to *read* the article this time, and came across the following snippets: "I'm a great fan and heavy user of Python. I prefer to fund work done in Python" "I'm open to requests for funding work that needs to be done to make Python the most widespread common scripting language on the net" Mr. Shuttlesworth has apparently earmarked USD 100,000 for programming milestones reached in 2004. -- Jay Dorsey jay at jaydorsey dot com From yan at NsOeSiPnAeMr.com Fri Dec 5 05:50:13 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Fri, 05 Dec 2003 05:50:13 -0500 Subject: Yet another newbie question - standard or built-in methods Message-ID: OK, I've been playing with the snippets of code posted earlier. Among them are things like allmovies[movie] = allmovies.get(movie, 0) + 1 From reading the docs, I've gathered that the '.get(xxx,yyy)' part is a method that operates on the dictonary allmovies. (Sorry if I have the terminology wrong). But nowhere can I find a list of 'standard' or 'built-in' methods, or methods that can be used with various variable classes. What exactly does 'get' do? This seems to be so basic to python that it's not explained anywhere, but that's no help to me.... Is there a list with explanations somewhere? I've been through the tutorials and guides, and all just start using these with no explanation of what they do and how they work. Maybe I've missed it somewhere; just point me to the right FM, so I can RTFM. help is no help: help> get no Python documentation found for 'get' So what's a newbie to do? -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From eric.brunel at N0SP4M.com Mon Dec 8 04:12:52 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 08 Dec 2003 10:12:52 +0100 Subject: Tkinter binding list References: <3fd0a76a$1_2@nova.entelchile.net> Message-ID: Rodrigo Benenson wrote: > Hi, > > I have a weird need in tkinter. If I have a widget I can *set* a binding > > .bind("", the_callback) > > > I also can *append* a binding > > .bind("", the_second_callback, "+") > > but now, I need to *replace* a callback. What's the difference between "setting" and "replacing" for you? If you set a callback doing a "return 'break'" at the end, the event should execute your binding and nothing else. Can you post a script showing exactly what you want to do and what problems you have? -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nagylzs at enternet.hu Thu Dec 4 03:18:00 2003 From: nagylzs at enternet.hu (=?ISO-8859-2?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Thu, 04 Dec 2003 09:18:00 +0100 Subject: [Boa Constr] Download of 0.2.7 Available References: Message-ID: <3FCEEDB8.6010709@enternet.hu> Here is what you need to do: 1. Download SmartCVS. Here is a link: http://www.smartcvs.com/download/setup-jre-2_4_2.zip 2. Install it 3. When you start it for the first time, please add a new repository. 4. Give these parameters: - Connection type: Password-Authentication (pserver) - User name: anonymous - Server name: cvs.sourceforge.net - Repository path: /cvsroot/boa-constructor Then you can 'Checkout' to a directory (which you can select). After download 'boa', please replace your old boa folder with the one you just checked out. That's all. Cheers, Laci 1.0 Howard Dunlavy wrote: > Thanks for the response. > > I am using Windows XP. > > -Howard > > > ----Original Message Follows---- > From: Nagy L?szl? Zsolt > To: Howard Dunlavy , Boa-users > > Subject: Re: [Boa Constr] Download of 0.2.7 Available > Date: Thu, 04 Dec 2003 08:03:18 +0100 > > I just downloaded it with CVS and that was easy, almost trivial. > What OS do you use? > > Howard Dunlavy wrote: > >> Is there a non-CVS way to download version 0.2.7? I don't know >> anything about how to do it directly from CVS and everything I have >> read about it makes it sound non-trivial. >> >> So I was looking for an easier way to get the latest version. >> >> Thanks. >> >> -Howard >> From johnp at reportlab.com Mon Dec 1 11:47:11 2003 From: johnp at reportlab.com (John Precedo) Date: Mon, 01 Dec 2003 16:47:11 +0000 Subject: ReportLab sponsor the XML Conference 2003 Message-ID: <0urmsvstdnhkr8fl4slbosophnb1vc4urf@4ax.com> ReportLab is happy to announce that it is a major sponsor of the XML Conference 2003, taking place in Philadelphia PA on December 7th to 12th. We'd love to see friends and associates of ReportLab there. You can register online at http://www.xmlconference.org/xmlusa/2003/ - and Public Expo passes are still free if you're quick (deadline Dec. 1st). -- Reportlab Europe Ltd (http://www.reportlab.com) From nessus at mit.edu Sun Dec 7 21:05:33 2003 From: nessus at mit.edu (Douglas Alan) Date: Sun, 07 Dec 2003 21:05:33 -0500 Subject: Case sensitive and ludicrous statements References: Message-ID: "Robert Brewer" writes: > Douglas Alan wrote: >> IfCamelCaseWereAGoodIdeaEvenInACaseSensitiveLanguage,thenPeopl >> eWouldWriteLike >> ThisAllTheTime. > The Greeks did that quite often. Some ideas take time. Yeah, well they couldn't even tell the difference between a "U" and a "V". Oops, that was the Romans. My bad. |>oug From j.r.gao at motorola.com Tue Dec 16 20:51:42 2003 From: j.r.gao at motorola.com (J.R.) Date: Wed, 17 Dec 2003 09:51:42 +0800 Subject: execl difficulty References: Message-ID: Sorry for the typo. The path delimiter on windows should be double backslash, the first one is for escape. os.execl("c:\\WINDOWS\\system32\\xcopy.exe", "E:\\MainWeb\\dreampics\\*.*","E:\\MainWeb\\dp") J.R. "Fredrik Lundh" wrote in message news:mailman.187.1071569341.9307.python-list at python.org... > "J.R." wrote: > > > You may try > > os.execl("c:\\WINDOWS\system32\xcopy.exe", "E:\\MainWeb\\dreampics\\*.*", > > "E:\\MainWeb\\dp") > > that's a rather verbose way to get a compilation error: > > ValueError: invalid \x escape > > > > > > From nospam at nopes Mon Dec 15 23:17:38 2003 From: nospam at nopes (Steve) Date: Tue, 16 Dec 2003 15:17:38 +1100 Subject: Advice for PostgreSQL Message-ID: <3fde873c$1@clarion.carno.net.au> Hi, Can someone please point me out to some module/library for using PostgreSQL from python? Perhaps a tutorial as wel? Thanks! Steve From __peter__ at web.de Fri Dec 5 07:51:14 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Dec 2003 13:51:14 +0100 Subject: Yet another newbie question - standard or built-in methods References: Message-ID: Kamus of Kadizhar wrote: > OK, I've been playing with the snippets of code posted earlier. > > Among them are things like > > allmovies[movie] = allmovies.get(movie, 0) + 1 > > From reading the docs, I've gathered that the '.get(xxx,yyy)' part is a > method that operates on the dictonary allmovies. (Sorry if I have the > terminology wrong). > > But nowhere can I find a list of 'standard' or 'built-in' methods, or > methods that can be used with various variable classes. What exactly > does 'get' do? This seems to be so basic to python that it's not > explained anywhere, but that's no help to me.... Is there a list with > explanations somewhere? I've been through the tutorials and guides, and > all just start using these with no explanation of what they do and how > they work. > > Maybe I've missed it somewhere; just point me to the right FM, so I can > RTFM. > > help is no help: > > help> get > no Python documentation found for 'get' > > So what's a newbie to do? Raymond Hettinger has already pointed you to the relevant part of the documentation. I will add that help *is* helpful. You just need to provide some context: >>> allmovies = {} >>> help(allmovies.get) will show you a short explanation of the dict.get() method. Unfortunately help({}) does not come up with the help for dictionaries, but it does mention the class (dict), so that the next step should work to your satisfaction: >>> help(allmovies) # not very informative >>> help(dict) # nice help() has the additional benefit of working for third party (or your own) code that provides docstrings: >>> def foo(bar): ... "Reliably foo any bar you care to mention" ... >>> help(foo) Or, more likely: >>> import otten.statistics >>> help(otten.statistics) # and old module, hope I threw in some doc :-) Peter From luigipaioro at libero.it Thu Dec 4 09:23:41 2003 From: luigipaioro at libero.it (luigipaioro) Date: Thu, 04 Dec 2003 14:23:41 -0000 Subject: Web authentication Message-ID: Good morning to all! I'm trying to access on a web page that needs user and password authentication. I'm enabled to access there (I mean that I have an user name and a password to access via web), but I cannot access using an automatic procedure (that is what I need to make a daemon that downloads weekly an ASCII file from that site). I've tried using urllib: import urllib conn = urlib.urlopen("http://user:password at www.mysite.com") print conn.read() But it doesn't work (it asks me again user and password). Does anybody know how can I acces to my site with authentication? I think that urllib2 can help me but I don't undestand how!!! Thaks Luigi From 9974331 at cvm.qc.ca Wed Dec 31 08:55:13 2003 From: 9974331 at cvm.qc.ca (Askari) Date: Wed, 31 Dec 2003 13:55:13 GMT Subject: Try - Except : ignored! References: <104c369a.0312310225.551d4d16@posting.google.com> Message-ID: 9974331 at cvm.qc.ca (Askari) wrote in news:104c369a.0312310225.551d4d16 @posting.google.com: > Hi, > > In my program (too long for cut-paste) : > http://www.cvm.qc.ca/9974331/Temp/crypte.py > > When I run and click on the button "Crypter!", a thread is run for the > method "def crypte():" (line 118). After, because the field "txtCode" > is blank, I raise a error (line 136). The code continu in the except > at line 353. In this except block, Python ignore (I don't know how!) > one of two "try - except" (line : 354-360 or 362-365) and raise a > error and go out of try-except (but it's in a try except!). > > When I run my code with no change, this error come : > ============ > Traceback (most recent call last): > File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", > line 363, in crypte > os.remove(destination) > OSError: [Errno 2] No such file or directory: '' > ============ > > and if I remove the second try-except (lines 362-365), I have this > error message : > ============ > Traceback (most recent call last): > File "C:\Documents and Settings\Assembleur_Man\Bureau\Crypte.py", > line 355, in crypte > fileDest.close() > NameError: global name 'fileDest' is not defined > ============ > > Askari > > Note : I try my code with python 2.3.3, 2.3.2 and 2.2.3. I have always > this bug. > Batheme! I didn't know that the exception rest in memory after a "catch". Finaly, it's my mistake with use of "sys.exc_info()"... From tzot at sil-tec.gr Mon Dec 29 10:05:51 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 29 Dec 2003 17:05:51 +0200 Subject: Best match searching References: Message-ID: On Mon, 29 Dec 2003 12:14:42 +0000, rumours say that "Daniel Pryde" might have written: >Hi everyone. >I was wondering if anyone might be able to help me out here. I'm currently >looking to find the quickest way to find a best fit match in a large array. [snip] >It's basically some euclidean distances that I've >calculated, and I need to be able to find the best matches over a large >number of input values, so I was looking for a speedy solution to this. These might be helpful: http://groups.google.com.gr/groups?selm=JGWa8.159434%24XZ1.6306345%40typhoon.austin.rr.com or http://groups.google.com.gr/groups?threadm=mailman.411.1067919450.702.python-list%40python.org&rnum=1 groups.google.com is your friend :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From Kyler at news.Lairds.org Sat Dec 27 11:12:13 2003 From: Kyler at news.Lairds.org (Kyler Laird) Date: Sat, 27 Dec 2003 16:12:13 GMT Subject: Zope: failed kludge around Plone hardcoding Message-ID: <8mk0c1-rh8.ln1@jowls.lairds.org> I'm trying to use Plone again. I do this every few months and usually drop it after a few days. I keep getting a little closer though. I'm documenting one of my attempts to make Plone more palatable in case someone else comes this way (and so that I'll remember). Plone uses random capitalization everywhere but the place that bothers me most is "Members". While other uses can be changed or hidden, "Members" is hardcoded all over and it's likely to appear in URLs I want to share. I decided that getting rid of "Members" is not an option. It'll break way too many things that I don't even want to consider. Instead, I am trying to work around it with a PortableHole. http://www.zope.org/Members/TheJester/PortableHole/ To do this, I created a PortableHole in my Plone folder. It's called "members" and points to "/portal/Members". (Make sure to specify the full path even from within a VirtualHost.) Next I edited portal_actions, changing "Members" to "members". That changes the tab along the top, but I found that when I visited /members without authenticating, I received an error. I could still get to individual member folders, but I couldn't generate the member_search_form. Unauthorized: You are not allowed to access meta_type in this context As a test, I gave Members/index_html some proxy roles. That didn't help. Next I changed it to call the form in Members/. That did work. At least it generated the form and the form did get results. The problem is that the results point to "Members/" URLs. So...I decided to take another approach. I removed my "members" PortableHole and renamed "Members" to "members". I then created a new PortableHole named "Members" that points to "members". (This is just the opposite of the way it had been.) I returned members/index_html to its default setting and now the form worked, but the results had URLs of the form "Members/members/kyler". Ug. It looks like getHomeUrl() is to blame. Also, I tried adding a new member and the new person was created but the default folders were not created (correctly). I'm giving up for now. As a temporary workaround I added RewriteRule ^/members(.*)$ /Members$1 to my Apache configuration so that I can at least post reasonable URLs. For my next attempt I suspect that I should use "Members" as the real folder and overload getHomeUrl() to use "members". I'm not sure how to do that reasonably. --kyler From try_vanevery_at_mycompanyname at yahoo.com Tue Dec 16 17:05:04 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 16 Dec 2003 14:05:04 -0800 Subject: Is anyone using Python for .NET? Message-ID: Is anyone using Python for .NET? I mean Brian's version at Zope, which simply accesses .NET in a one-way fashion from Python. http://www.zope.org/Members/Brian/PythonNet Not the experimental ActiveState stuff, which tried to compile IL and apparently didn't succeed. Two motives for the question: 1) whether to use it for my C++ / C# / .NET / Python (?) game project. It's a prototype, so in this context a "mostly working beta" is acceptable. I won't need "ready for prime time" for another year yet. 2) whether it's viable at this time to consult Python + .NET interop as a business model to various Suits. I'm gathering that due to lack of resources on Brian's webpage, and lack of responses on their mailing list, that it isn't. Suits need to perceive support, after all. So I'm wondering who's kicking Python for .NET's tires, as that would be part of the agenda of getting Python development to be .NET friendly. Why have that agenda? Well, Microsoft does generally succeed at out-marketing everybody, so if you're with them rather than against them, you have a much better chance of having your technology widely adopted. Also, people actually like .NET language interop for its technical merits alone. It's a rare case where Microsoft is actually leading the industry rather than cloning and conquering. The clone is now Mono, in the Unix world. I hope that eventually, at least the IL components of .NET are not a Microsoft thing per se. Programmers need easy language interop solutions. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA Brandon's Law (after Godwin's Law): "As a Usenet discussion grows longer, the probability of a person being called a troll approaches one RAPIDLY." From gumuz*NOSP at M*looze.net Thu Dec 11 18:13:30 2003 From: gumuz*NOSP at M*looze.net (Guyon Morée) Date: Fri, 12 Dec 2003 00:13:30 +0100 Subject: HalfLife/Cstrike monitorring References: <3fd84154$0$251$4d4ebb8e@news.nl.uu.net> <3FD8C79C.D7166008@alcyone.com> Message-ID: <3fd8fa1c$0$154$3b62cedd@news.wanadoo.nl> Thanx for the tip, but actually I wanted to make something, which shows the stats of a match a bit 'flashy arcade style'. perhaps i'll use pygame for that part. In other words: it should look cool on a beamer :) anyway, the decoding stuff I've managed, but I'm still stuck with the UDP (i think) because somehow no response is given. maybe someone can show me the light. thanx, Guyon "Erik Max Francis" schreef in bericht news:3FD8C79C.D7166008 at alcyone.com... > "Guyon Mor?e" wrote: > > > I want to write a HalfLife/CStrike monitor, to make some nice > > statistics for > > an upcoming LAN-party. I've found some pointers on how to use the > > protocol, > > but now I have to do the following: > > > > 1. make an UDP connection > > 2. send a string(?) like '\xFF\xFF\xFF\xFFdetails\x00' > > 3. translate the response into bytes and strings :-s > > > > for more details on this protocol see: > > http://dev.kquery.com/index.php?article=31 > > > > I hope someone can help me with at least the first 2 steps. > > It sounds like you just want a server statistics package, of which there > are many available. See Google; a good one is PsychoStats. There's > really no need for you to reinvent the wheel here. > > -- > __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > \__/ Dead men have no victory. > -- Euripides From ajsiegel at optonline.com Sat Dec 13 09:28:26 2003 From: ajsiegel at optonline.com (Arthur) Date: Sat, 13 Dec 2003 14:28:26 GMT Subject: ANN: lunatic-python 0.1 References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> <5iiltv4pf107ubuck3kqk6ob2d1jj3kvn4@4ax.com> Message-ID: On Sat, 13 Dec 2003 11:55:12 -0200, Gustavo Niemeyer wrote: >> But you left out the most important question: WHY? > >That's *exactly* the second topic in the web page, but since you >obviously haven't looked at it, why do you care? Keep your >arrogance for yourself please. I found the recent thread on Prototype based programming (I don't really know what that means, BTW) interesting enough to follow the thread to the IO Language site: http://www.iolanguage.com/ Which mentions Lua as an influence. Which led me to the fact the Steve Dekorte (the IO BDFL) most recent project before IO was Yindo: http://www.yindo.com/ "Next generation web apps" which was (its abondoned) browser plug-in enabled Lua with built in 3d and sound. Simple download of plug-in and do the demos - and its nice. Connecting this up with Python sures sounds very intriguing to me. And I am going to have a play. Art From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 26 18:39:47 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 27 Dec 2003 00:39:47 +0100 Subject: Project dream References: Message-ID: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Aahz: >You mean something like Chandler? >http://osafoundation.org/Chandler_Compelling_Vision.htm Yes, that's what I meant. Although Chandler seems much more ambitious. Very interesting project. -- Ren? Pijlman From timr at probo.com Sat Dec 20 18:18:36 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 20 Dec 2003 15:18:36 -0800 Subject: linux wine py2exe ?? References: Message-ID: duikboot wrote: > >I've tried to create a .exe file on linux (Fedora). > >So in installed wine, python2.3 with wine and py2exe (with wine ofcourse) > >I made a setup file (setup.py) and ran >>wine python.exe setup.py py2exe > >Does anybody know what I've done wrong? Or is it just not possible Before folks spend a lot of time giving the answer, I would just like to confirm something. Are you REALLY trying to create a Windows executable on Linux? Or are you actually wanting to make a Linux executable, and you have been misled into thinking that py2exe is the only way to do that? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhammond at skippinet.com.au Mon Dec 1 06:42:29 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 01 Dec 2003 22:42:29 +1100 Subject: How to delete this file ??? In-Reply-To: References: Message-ID: DCK wrote: > Hello > > I've path to file, which look like this: > \\COMPUTER\D$\C++\FILE_TO_DELETE.JPG > This path was generated by os.path.walk() function. When i try to delete > this file, os.remove() can't find it, os.path.fileexists() can't find it :( > I can delete other files (i.e. \\COMPUTER\D$\C\FILE_TO_DELETE.JPG). I guess > there's a problem with this C++ directory (++ exacly). I tried to change it > to C\+\+, but this still not work. I've no idea how to delete this file. > > I work under WinNT 4.0 with sp6, python 2.3 with unicode support. I have > adminstrator rights. > Can somebody help me ? Are you sure you have quoted your back-slashes correctly? It works for me: python -c "import os;print os.path.exists(r'\\eden\e\temp\delme')" True Mark. From david.g.morgenthaler at comcast.net Sun Dec 14 21:38:15 2003 From: david.g.morgenthaler at comcast.net (david.g.morgenthaler at comcast.net) Date: Sun, 14 Dec 2003 19:38:15 -0700 Subject: Using PIL with py2exe References: Message-ID: <6c7qtv0blppda689cpjbv9mi175sdpql2a@4ax.com> On Wed, 10 Dec 2003 16:04:41 +0000, John Carter wrote: >Does anyone know how to embed PIL into a py2exe program. > >As far as I can tell PIL is not finding its plugins for Image I/O, >they are imported dynamically as required. So I cant load or save >pictures > >I tried making a copy of the plugin files to the application >directory, but I've had no luck in making the code see the files >I'd be grateful for any suggestion. > >Please e-mail me, as well as posting a reply. > >John Carter >jnc at ecs.soton.ac.uk PIL imports the drivers dynamically, so py2exe doesn't find them. Including these lines should solve your problem. ## Static imports from PIL for py2exe from PIL import GifImagePlugin from PIL import JpegImagePlugin From bikeracer2000 at hotmail.com Thu Dec 4 02:15:57 2003 From: bikeracer2000 at hotmail.com (BikeRacer) Date: 3 Dec 2003 23:15:57 -0800 Subject: Tkinter widget that functions like Explorer "Details" mode? References: Message-ID: Douglas Alan wrote: > Does anyone know if there is a widget for Tkinter available somewhere > that implements something like the Microsoft Explorer View->Details > mode, or the Apple iTunes track browser, or the Nautilus View as List > mode? I.e., rows and colums of text, where the column widths can be > adjusted by the user, and the user can click on a column header to > sort the rows by that column? Thanks. Perhaps you could build something out of the tkTable widget? http://sourceforge.net/projects/tktable/ There is a Python wrapper, but it is incomplete and out of date. Easy to correct though. From scott at fenton.baltimore.md.us Wed Dec 24 12:41:13 2003 From: scott at fenton.baltimore.md.us (Scott Fenton) Date: Wed, 24 Dec 2003 11:41:13 -0600 Subject: ungetch in Python Message-ID: Hello and merry chrismas/new years/ everyone, I'm writing a small parser for a minilanguage in Python, and I was wondering --- is there any equiv. of C's ungetch or Scheme's peek-char in python? That is, is there a way to look at a character without taking it off of the input stream or is there a way to put it back on the input stream afterwards? I googled around and didn't come up with anything that didn't involve curses, which I don't want to use. Any help? TIA -Scott From wtrenker at hotmail.com Sun Dec 21 10:10:34 2003 From: wtrenker at hotmail.com (William Trenker) Date: Sun, 21 Dec 2003 15:10:34 +0000 Subject: memory overhead using from-import? In-Reply-To: <3FE62032.619D0D46@alcyone.com> References: <20031221102848.4f901801.wtrenker@shaw.ca> <3FE62032.619D0D46@alcyone.com> Message-ID: <20031221151034.68b9be67.wtrenker@hotmail.com> Erik Max Francis wrote: > Consider that the objects created in a module can be highly > interdependent on each other Yes, you are right. Usually it makes no sense to import one "piece" of a module because of the inter-connectedness. > The bigger question here is why you think you really should be > avoiding the full importation of the module. In this case, the "piece" is totally independent of anything else in the module. And this piece (cgi.escape) is a very small function. I was hoping to "lift" just this one, small independent function since it's functionality is quite common. > The overhead involved in an interpreted language like > Python for importing the cgi module and only using one function inside > it vs. avoiding the importation at all is extremely minimal. The cgi module adds 1.46 megabytes to the virtual memory size of the process into which it is imported. That seems excessive considering I only want access to a small, independent function. Yes, on today's gigabyte computers a megabyte isn't worth worring about. But on old systems and on embedded processors, the memory size can be important. Thanks for replying, Bill From peter at engcorp.com Tue Dec 23 10:37:23 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Dec 2003 10:37:23 -0500 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> <3FD9D4E9.FE199F61@engcorp.com> <7xfzfphdzt.fsf@ruckus.brouhaha.com> <3FDDC1FD.6687FD2@engcorp.com> <874qw0zxzw.fsf@pobox.com> Message-ID: <3FE86133.ADF4810F@engcorp.com> "John J. Lee" wrote: > > Peter Hansen writes: > [...] > > > Cookies aren't insane in concept, but their implementation leaves some > > > things to be desired. > > > > Agreed... especially with IE6.1, where I still have an incredibly annoying > > problem with a Zope-based Intranet where my cookies are being forgotten > > periodically, which among other things has led to repeated data loss > [...] > > Do you know why / when / which? Are these cookies in your browser or > your users' browsers? Third party? Session or persistent? Unfortunately, I don't know any of the above or I would definitely have fixed it by now. It's intermittent, though at least after two years I've found a way to reproduce it fairly reliably with an adequate number of clicks between a particular set of links I use often. The cookies that are lost are both session and persistent: in fact all cookies pertaining to one particular domain are lost simultaneously, it seems. My own browser (IE). Using a home-brew issue tracker that was written largely with DTML about three years ago... at the moment I'm still assuming it's a problem only with that product, but it does not affect Mozilla at all so it's clearly linked to IE-specific behaviour. > Of course, cookies are "allowed" to vanish at random times. I > remember reading something about servers telling browsers which > cookies are important to users and shouldn't be thrown away, but I've > completely forgotten where that was... Hmm.... I doubt they're supposed to vanish if there is not too much data stored in them, and as there are no reports that I can find on the web about similar behaviour, I suspect they _don't_ vanish, even if they're allowed to. -PEter From opengeometry at yahoo.ca Tue Dec 23 22:52:02 2003 From: opengeometry at yahoo.ca (William Park) Date: 24 Dec 2003 03:52:02 GMT Subject: nonlinear least square References: <87ptefi9qj.fsf@pobox.com> Message-ID: Dmitry Rozmanov wrote: > John J. Lee wrote: > > Thank you for the suggestion. > > Yes, I do not like to have to install Scientific Python just for this > purpose. As I understand it has some modules which have to be compiled > anyway. > > I would be really grateful for any example code you provide. > > BWT do you know such a standalone code for nonlinear equations set > solving? Newton's method or something. I mean in Python only. Efficiency aside, it's easy to write them in Python. You can practically copy C-code line for line. Or, write algorithm from books. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 23 09:14:03 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 23 Dec 2003 15:14:03 +0100 Subject: global and None References: Message-ID: Leo Yee: >Does anyone know what I should do to solve this problem? What problem? -- Ren? Pijlman From guettli at thomas-guettler.de Tue Dec 9 10:39:39 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 09 Dec 2003 16:39:39 +0100 Subject: invalid time - why ? References: Message-ID: Am Tue, 09 Dec 2003 15:14:51 +0100 schrieb fowlertraine: > Hello python-list, > starttime=time.time() > .... process .... > endtime=time.time() > dtime=endtime-starttime > print "Started at:", time.strftime("%H:%M:%S",time.localtime(starttime)) > print "Ended at:", time.strftime("%H:%M:%S",time.localtime(endtime)) > #print time.localtime(dtime) > print "Deltatime: ", time.strftime("%H:%M:%S",time.localtime(dtime)) Python like most operating system use seconds since 1970 for storing the time. If you do "endtime-startime" your result will surely by in the year 1970. You could do: print "Deltatime %s hours" % float(dtime)/(60*60) thomas From dave at pythonapocrypha.com Sat Dec 13 09:28:28 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 13 Dec 2003 07:28:28 -0700 Subject: do this with list comp? References: <21064255.0312130331.7fdee240@posting.google.com> Message-ID: <00d601c3c185$62196b30$6400000a@YODA> Peter wrote: > > > I want to replace all empty fields in a CSV line with 'NULL'. > > > > > > Here is a brute force way > > > > > > def fixline(line): > > > ret = [] > > > for s in line.split(','): > > > if not len(s): ret.append('NULL') > > > else: ret.append(s) > > > return ret > > > > > > line = 'John,Bill,,,Fred' > > > print fixline(line) > > > # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] > > > > > > I am wondering if there is a way to do it with list comprehensions. I > > > know how I would do it with a ternary operator..... > > > > Prepare to be flooded with answers. ;-) > > > > >>> line = 'John,Bill,,,Fred' > > >>> [x or 'NULL' for x in line.split(',')] > > ['John', 'Bill', 'NULL', 'NULL', 'Fred'] [snip] > And there was still a one-liner: > >>> line = 'John,Bill,,,Fred' > >>> map(lambda x:x or 'NULL',line.split(',')) > ['John', 'Bill', 'NULL', 'NULL', 'Fred'] Uh, the listcomp way was a one-liner too. Or do I misunderstand your comment? From yan at NsOeSiPnAeMr.com Tue Dec 16 06:08:22 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Tue, 16 Dec 2003 06:08:22 -0500 Subject: Cropping log files Message-ID: Yet another possible newbie question. I'm tyring to figure out how to best crop a log file. I have a file that grows infinitely in length. I want to keep only the last n entries in the file. I've been looking for some sort of ascii-database or log file management python module that lets me say: how many records in the file? and then say: delete the first nr - n records. No joy. I don't want to suck the whole file into memory if I can help it, and I can't help thinking that doing a for line in file(logfile) nr += 1 to count the number of lines, then reading the file again, discarding the first nr - n records, writing the rest to a temp file, and then renaming the files is the most efficient way to go. Not only that, but what happens if the logfile is written to while I'm doing all of this - I may lose log file entries.... I found FLAD, even that seems to be overkill for what I need. So, any modules out there for log file management? The logging module lets me log events, but there aren't any tools for managing the log files created in the way I need.... The RotatingFileHandler rotates logs in the sense of logrotate, but what I need is to keep only the last n records in one file. -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From jdhunter at ace.bsd.uchicago.edu Thu Dec 4 11:47:53 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 04 Dec 2003 10:47:53 -0600 Subject: returning a list of tuples -- C API Message-ID: I am writing a python extension module and have a reference counting question My function looks like static PyObject * pokereval_seven_cards(PyObject *self, PyObject *args) { int i; PyObject * tup; PyObject * list; // ... snip ... list = PyList_New(HandType_LAST+1); for (i = HandType_FIRST; i <= HandType_LAST; i++) { tup = Py_BuildValue("(s,h)", handTypeNamesPadded[i], totals[i]); PyList_SetItem(list, i, tup); totals[i] = 0; } Py_INCREF(list); return list; } Should I be incrementing the ref of tup each time I call Py_BuildValue? Is it correct to increment the ref of list before I return it? Does it make a difference vis-a-vis ref counting if I create the tuple with Py_BuildValue or PyTuple_New? Thanks, John Hunter From ny_r_marquez at yahoo.com Tue Dec 9 15:32:28 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 9 Dec 2003 12:32:28 -0800 Subject: Explorer Shell extensions are here! References: <8a27e309.0312081137.18c2810b@posting.google.com> Message-ID: <8a27e309.0312091232.6779a4fd@posting.google.com> Great! That is just what I needed. Thank you, M.H. and all other Pythonistas for all your great work and generous spirit. -Ruben Joe Francia wrote in message news:... > R.Marquez wrote: > > I just happened to bump into this today when I went to the Win32 > > Python Extensions page. I think the M.H. and his team are a bit too > > modest. > > > > Quote: > > "win32com.shell grows many more interfaces, allowing Python to operate > > as a nearly complete shell extension, and to interact with the shell > > interfaces. See the win32comext\shell\demos\server directory for > > examples." > > > > This is something I had been waiting for a while, and even submited a > > "feature request" about it. So, since I hadn't heard any thing about > > it, I figure there may be a few more like me that would enjoy knowing > > about this. > > I _do_ enjoy knowing about this ;>) Thanks for the tip. > > > (Now, if I could only figure out how to make a context menu that would > > show up for any file of folder... ;) > > In the demo "context_menu.py", replace the register and unregister bits > with the code below. Run context_menu.py with either the --register or > --unregister switch, as appropiate. > > def DllRegisterServer(): > import _winreg > folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, > "Folder\\shellex") > folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers") > folder_subkey2 = _winreg.CreateKey(folder_subkey, "PythonSample") > _winreg.SetValueEx(folder_subkey2, None, 0, _winreg.REG_SZ, > ShellExtension._reg_clsid_) > > file_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, > "*\\shellex") > file_subkey = _winreg.CreateKey(file_key, "ContextMenuHandlers") > file_subkey2 = _winreg.CreateKey(file_subkey, "PythonSample") > _winreg.SetValueEx(file_subkey2, None, 0, _winreg.REG_SZ, > ShellExtension._reg_clsid_) > > print ShellExtension._reg_desc_, "registration complete." > > def DllUnregisterServer(): > import _winreg > try: > folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, > > "Folder\\shellex\\ContextMenuHandlers\\PythonSample") > file_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, > > "*\\shellex\\ContextMenuHandlers\\PythonSample") > except WindowsError, details: > import errno > if details.errno != errno.ENOENT: > raise > print ShellExtension._reg_desc_, "unregistration complete." > > Peace, > Joe From ababo_2002 at hotmail.com Mon Dec 29 07:14:42 2003 From: ababo_2002 at hotmail.com (Daniel Pryde) Date: Mon, 29 Dec 2003 12:14:42 +0000 Subject: Best match searching Message-ID: Hi everyone. I was wondering if anyone might be able to help me out here. I'm currently looking to find the quickest way to find a best fit match in a large array. My problem is that I have an array of, say, 600*400, which contains a value at each point, and I need to find the value in that array which is closest to the input value. It's basically some euclidean distances that I've calculated, and I need to be able to find the best matches over a large number of input values, so I was looking for a speedy solution to this. The array is implemented simply using a list of lists. The only solution I could think of is to use some for statements, but that seems to take a while, even for just one search. Any hints or tips would be really helpful. :-) Daniel _________________________________________________________________ Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo From tjreedy at udel.edu Sun Dec 21 22:11:15 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 22:11:15 -0500 Subject: How do I really delete an imported module? References: Message-ID: <-5idnY4aZ99P_XuiRVn-gw@comcast.com> "Robin Becker" wrote in message news:mGZIGKA10i5$Ewob at jessikat.fsnet.co.uk... > ....well you have to delete all references to the module before it goes > away. There are references to re in other library modules, but I suspect > that most of re is in an extension (or built in). re is a relatively short Python wrapper module (see the Lib directory) that imports the current preferred re implementation written in C -- now _sre, previously _pcre (or something like that). TJR From bokr at oz.net Sat Dec 20 08:37:49 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Dec 2003 13:37:49 GMT Subject: string parsing screwing up on large files? References: <75765317.0312191855.6ce6f4d2@posting.google.com> Message-ID: On 19 Dec 2003 18:55:29 -0800, danl_kramer at yahoo.com (Daniel Kramer) wrote: >Hello, I'm fairly new to python but I've written a script that takes >in a special text file (a renderman .rib to be specific).. and filters >some of the commands. The .rib file is a simple text file, but in >some cases it's very large.. can be 20megs or more at times. > >The script steps though each line looking for keywords and changes the >line if nessisary but most lines just pass in and out of the script >un-modified. The problem is sometimes the lines aren't written out >correctly and it's an intermittent problem. If I re-run the script >again on the same input usually it works fine. After filtering about >100 files i might get 4 or 5 that come out bad.. simply re-running >those fixes them. > >Anyone know what I might look for? It's possible that the machine is >under a lot of i/o load and/or cpu load when it happens, but not sure >about that.. I normally send this processing to a render farm, so it's >hard to predict exactly what sort of load is going on at that time. It >feels like a buffer isn't getting flushed before the text is written >out.. or something like that. > >Any suggestions where I might look? > What is telling you that some lines aren't correct? Renderman syntax errors? Maybe if you saved the bad file(s) and re-ran the changes until you got a good one, and then ran diff -u goodfile badfile to see how things were actually changing, it would become clear. Or if not, you could post some diffs and the code that should be accomplishing the changes, and we could go from there. Is the code threaded? Are you perhaps clobbering something across threads occasionally? Accidental name collisions? Unsychronized accesses? You might also want to mention what platform and python version etc you are running. Maybe there is a file system bug that an upgrade would fix? It doesn't happen often, but it might be worth googling for for your platform. Regards, Bengt Richter From __peter__ at web.de Tue Dec 9 12:38:29 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 18:38:29 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Jacek Generowicz wrote: > aahz at pythoncraft.com (Aahz) writes: > >> Waitasec .... okay, I see what your problem is, assuming you're >> describing it correctly. The problem is that you're calling Python >> functions in an inner loop. > > ... indeedy ... > >> I think you're going to need to write a solution that doesn't call >> functions (function unrolling, so to speak). Instead of returning a >> memoizer function, just use a dict of dicts. > > Sounds interesting. But how do I get the dictionary to use the > function which it is memoizing, to calculate values which haven't been > cached yet? Guessing into the blue: try: result = cache[fun, args] except KeyError: result = cache[fun, args] = fun(args) should make a fast inner loop if cache misses are rare. > > Hmm ... maybe by subclassing dict, I can add the necessary > functionality ... but even then I don't see how to avoid wrapping the > dictionary access in a function call ... and then we're back to square > one. Subclassing dict will not make it faster. Maybe it's time to show some inner loop lookalike to the wider public for more to the point suggestions... Peter From thomas at esands.com Thu Dec 11 01:19:18 2003 From: thomas at esands.com (T. Schulz) Date: Thu, 11 Dec 2003 06:19:18 +0000 Subject: check disc space In-Reply-To: <99dce321.0312102124.3d54354e@posting.google.com> References: <99dce321.0312102124.3d54354e@posting.google.com> Message-ID: Thanks for that. I wonder if it would be worthwhile to have such a functionality somewhere in the os module? Thomas David M. Wilson wrote: > Thomas Schulz wrote... > > >>Any ideas how to check for free disc space from Python. Platform >>independent? > > > Fortunately for you, my bad stomach will not allow me but a precious > hour of sleep this fine morning. :) > > http://botanicus.net/dw/tmp/DiskFree.py > > Tested: Win32, Linux, FreeBSD. I'm going to work in about 3 hours. > This _really_ sucks. :( > > > David. From python-url at phaseit.net Tue Dec 30 08:28:19 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Tue, 30 Dec 2003 13:28:19 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) Message-ID: QOTW: There are probably many less productive ways to spend your time than studying Mark Pilgrim's code. -- Skip Montanaro QOTW: 'enumerate'...? As in, enumerate(n*[0]) ... ? -- Alex Martelli, a complete response quoted! Stephen Ferg announces a Python Language Reference, his produce a complete, alphabetized reference of all of Python's language features.=20 http://groups.google.com/groups?selm=b16e4ef7.0312260911.42e26052 at posting.google.com Ralf Wieseler gets help getting tkinter going on Mac OS X http://groups.google.com/groups?threadm=bsedqg$rf$00$1 at news.t-online.com Aahz asks if anyone is using Tkinter and OS X 10.3 and hears that it does work, even though that may mean it can be made to work. http://groups.google.com/groups?threadm=bs7pt0$a98$1 at panix1.panix.com Kamuela Franco asks for general information on socket programming in Python. http://groups.google.com/groups?threadm=KdzGb.23400$NZ1.18286 at nwrddc02.gnilink.net Ryan Spencer gets help with his pygame based pong test. http://groups.google.com/groups?threadm=pan.2003.12.22.07.59.49.651699 at earthlink.net Andrei is looking for an appropriate embedded storage mechanism to support fulltext search for messages in a forum. http://groups.google.com/groups?threadm=21bb8d55.0312230435.49cad73c at posting.google.com Matt Whiteley wants to update the A record on a DNS server using Python. http://groups.google.com/groups?threadm=OVkGb.5263$Y45.175 at news-binary.blueyonder.co.uk Andre Brightway asks about non-X based linux GUIs. http://groups.google.com/groups?threadm=88f9e356.0312162305.58718893 at posting.google.com Bill Sneddon gets tips on using Google's API from within python. http://groups.google.com/groups?threadm=brv88k$kkq$1 at ngspool-d02.news.aol.com Art Decco asks for help creating a little database-backed CGI application using Python on a server with no real database available. http://groups.google.com/groups?threadm=UQRFb.115936$8y1.365571 at attbi_s52 Rene Pijlman seeks clarification on how delegation works in python. http://groups.google.com/groups?threadm=jr5muvcajluhq4u41nk0fduj99kfjdaqjb at 4ax.com John J. Lee gets feedback on the naming of iterators. http://groups.google.com/groups?threadm=87fzfch0bu.fsf at pobox.com Ahmad wants to print Arabic characters right to left. http://groups.google.com/groups?threadm=3014031e.0312220305.c38ffa3 at posting.google.com Will Stuyvesant asks what you would write if you have the time and the money to start a new project in Python. http://groups.google.com/groups?threadm=cb035744.0312261236.11d785ac at posting.google.com John J. Lee announces the initial release of mechanize 0.0.1a, providing stateful programmatic web browsing after Andy Lester's Perl module. http://groups.google.com/groups?selm=mailman.1072191603.27380.clpa-moderators at python.org ... and the first beta release of pullparser, a simple "pull API" for HTML parsing, after Perl's HTML::TokeParser. http://groups.google.com/groups?selm=mailman.1072191603.27381.clpa-moderators at python.org Adam Souzis announces Rx4RDF and Rhizome 0.1.3. Rx4RDF is used for building RDF-based applications and web sites, and Rhizome is a Wiki-like content management and delivery system built on Rx4RDF http://groups.google.com/groups?selm=mailman.1072275003.22292.clpa-moderators at python.org The revised and updated 2nd edition of "Learning Python" by Mark Lutz and David Asher is now available from O'Reilly. http://www.oreilly.com/catalog/lpython2/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From ajsiegel at optonline.com Fri Dec 26 14:04:15 2003 From: ajsiegel at optonline.com (Arthur) Date: Fri, 26 Dec 2003 19:04:15 GMT Subject: 2.3 list reverse() bug? References: <26vmuvooh62ko48t7m8n2cumg0se7dd7v5@4ax.com> Message-ID: <8p0puvoj1rsvprocukgl61dot6m5dlvet4@4ax.com> > >Hm, made sense to me. Well I don't mean to make a big thing of it, but mostly because it was in response to a poster asking whether it was him or Python. I think the better answer is neither. His intuition is informed by ealrier experiences which presumably does not include vast experience with Python, and Python is as it is. And certainly a lack of intuitiveness is not a general reproach that can be made in respect to Python, IMO. Though it is mortal. >When introduced to a system that follows different rules, our >intuition will occasionally be at fault when it contributes to >an invalid assumption. I guess. I came to Python with little previous programming experience. And chose, for example, not to study operator precedence. But to rely on what made sense based on "intuition". And was OK, 95% of the time. The other 5% was just learning what I might have otherwise learned by a more deliberate contemplation of the documentation - which is certainly clear and thorough enough on the general subject. In some sense, making any assumption is a fault. On the other hand, I guess I am here because my approach worked for learning Python much better than it did when making false starts at learning other languages. >Seems to me it couldn't be otherwise I agree, But as a matter of degree, I like where Python is. > >Or better informed. If you mean that in cases like the one that >started this thread, one would just have to learn to ignore one's >intuition, that doesn't sound like a happy state to me! Better informed, in respect to the workings of Python. Which in the case of operator precedence is probably generically better informed. In the case of mutablility, I am not sure. Art From milas_gi at hotmail.com Wed Dec 24 10:41:50 2003 From: milas_gi at hotmail.com (tutu) Date: 24 Dec 2003 07:41:50 -0800 Subject: writing recursive lambda functions References: Message-ID: <5d1dd116.0312240741.4dcaadb@posting.google.com> ??? Is this what you need? def mapp(f): lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l)))) print mapp(lambda x: x*x) => None (can't call it) def mapp(f): return lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l)))) print mapp(lambda x: x*x) => at 0x0267ED30> print "mapQuad([1,2,3,4]): ", mapQuad([1,2,3]) => mapQuad([1,2,3,4]): [1, 4, 9] From aahz at pythoncraft.com Sun Dec 21 10:59:50 2003 From: aahz at pythoncraft.com (Aahz) Date: 21 Dec 2003 10:59:50 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: In article , John Roth wrote: > >I'm not likely to do that for two reasons. One is that, at this point >in my life, I'm not a C programmer. I don't even have a functional C >compiler on my machine. The other is that I don't particularly like >the notion of adding more and more options to the mix. I'm much more >concerned with the social issue of how software development is done, >and another variation on a good idea simply isn't my way of approaching >the issue. That's why ``import this`` is about the only good answer you'll get. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From francisgavila at yahoo.com Sat Dec 20 16:12:05 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 20 Dec 2003 16:12:05 -0500 Subject: Unicode from Web to MySQL References: Message-ID: Bill Eldridge wrote in message ... >etc., etc., but after numerous tries in the end I still keep getting >either SQL errors or >the dreaded 'ascii' codec can't decode byte ... in position ...' errors. Here's your clue: your string contains a byte which is not representable by ascii. >Can someone give me any explanation of how to do this easily? Quickstart guide: You first need to decode your string to unicode. You do this by 'stringfromweb'.decode('encoding-of-the-string'). So if you grab a web page that's in latin-1, you do 'stringfromweb'.decode('latin-1') and get unicode. If you later want utf-8 (to plunk into SQL), take that unicode and .encode('utf8'). Path-to-understanding: You need to understand how unicode plays in to this first. Unicode is not an encoding. Unicode is an abstract mapping of numbers (called code points) to letters. Pure, undistilled "Unicode" is what you see in those huge charts which show a number on the left and a long uppercase letter/symbol description on the right. Unicode itself has nothing to do with bytes, or even with computers. A Python Unicode object is just that: an ordered sequence of unicode code points. It has no natural byte representation. If you want that, you need to encode it. Note that unicode objects have no "decode" method. This is because unicode is a LACK of encoding! Encoding maps symbols to byte representations, and a unicode object is the explicit lack of a byte representation. So there are no bytes to decode from. (Now of course the computer needs *some* representation, becuase all it knows is bytes, but that could be anything, and is entirely an implementation detail that you don't need to know about. But you can see it with the 'unicode-internal' codec.) A Python str object is an ordered sequence of 8-bit bytes. It is not really a string--that's a holdover from the bygone days of pre-unicode Python. When you encode a unicode object, you get raw bytes in some representation of unicode characters, which are held by a str. When you want a unicode object, you give it a str and a *known encoding*. Now, what is the encoding of a str? You see this is like a strange Koan, because bytes is bytes. Bytes have no intrinsic meaning until we give them some. So whenever you decode a string to get unicode, you MUST supply the encoding of the string! There are ways to specify a default encoding for strings in Python (see your site.py and sys.get/setdefaultencoding), but the default default is ascii. Hence if byte '\xef' is found in a str, any attempt to encode it will choke, because that byte is not in the 'ascii' encoding and thus the claim that this str is encoded in ascii is false. (str.encode(codec) is really shorthand for str.decode(default-encoding) -> unicode.encode(codec) ) Now, lets examine: >>> 'abc'.decode('utf8') u'abc' "Take three bytes 'abc', and decode it as if it were a unicode string encoded as utf8." >>> '\xef'.encode('utf8') Traceback (most recent call last): ... UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) What you really need to do, then, is: >>> PureUnicodeUnsulliedByBits = stringfromtheBADBADweb.decode('latin-1') Or: import MySQLdb, re,urllib data = urllib.urlopen('http://localhost/test.html').read() data2 = data.decode().encode('utf8') ... c.execute(''' INSERT INTO junk ( junklet) VALUES ( '%s') ''' % data2 ) Finding the encoding of that string from the web is where the tears come in. If you're lucky, urllib.urlopen('http://....').info().getencoding() will give it to you. However, this gets its info from the http headers, and if they don't specify encoding, it defaults to '7bit'. But the html page itself *might* have a different idea about its own encoding in the element, 'content' attribute, which may be of the form "text/html; charset=ISO-8859-1". Or it might not, who knows? In other words, there is no standard, 100% reliable method of getting the encoding of a web page. In an ideal world, the http header would have it, and that's that. In the real world, you have to juggle various combinations of information, missing information, and disinformation from the http protocol header's info, the html file's meta info, and charset guessing algorithms (look for Enca). There might be a way to get urllib to request an encoding (as browsers do), so that the http header will at least give some slightly more useful information back, but I don't know how. As it is, it will almost always not specify the charset if urllib is used, forcing you to look in the html file itself. But once you get the encoding, everything is fine.... -- Francis Avila From bokr at oz.net Tue Dec 16 20:48:11 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Dec 2003 01:48:11 GMT Subject: I see advice on how to debug a python module that hangs up the process References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: On Tue, 16 Dec 2003 15:37:22 -0800, JD wrote: > >On Dec 16, 2003, at 2:45 PM, Robin Munn wrote: > >> The first step I'd suggest is to sprinkle print statements all around >> your code: >> >> print "About to call some_func()..." >> some_func() >> print "Returned from calling some_func()..." >> >> Then you can watch the console output (or redirect it to a file for >> later perusal) and see when the thing hangs. > >We already know the function it hangs up at. It's a Python function >we defined. > >Obviously, we put a print statement right at the beginning of the >errant >function, but it doesn't appear to be getting there. > >IE: > >print "before function call" >my_function(some_arguments) >print "after function call" > >def my_function(some_arguments): > print "start of function call" <--- this never gets called, or >we don't see the output > > >So when this piece of code is called, we get: > >before function call > > >Then, we have to do a "kill -9" the process. > It would be more interesting if the above was real code instead of prose ;-) If you know the failing function, and the place where it's being called as above, what about actually copy/pasting the few lines instead of ad-libbing? Also, as paul says, what are the arguments? What happens if you change -- print 'before function call' my_function(some_arguments) print 'after function call' -- to -- print 'before argument evaluation' the_arg_tuple = (arg_expr1, arg_expr2, etc.blah) # i.e., whatever "some_arguments" is, in parens print 'before function call' my_function(*the_arg_tuple) print 'after function call' -- If that hangs during some_expression tuple evaluation, you can do the expressions one at a time, e.g. the_arg_tuple = (arg_expr1,) print 'first ok' the_arg_tuple = the_arg_tuple + (arg_expr2,) print 'second ok' etc. **** But show us a real session copy/pasted, not code-prose, please. **** You could also run python with -u so you're sure to get all the output flushed immediately, just in case. And just after the first before print, you could also use sys.settrace to hook in a debugging trace that can at least trace non-C python stuff. It might get you closer. E.g., (quick hack) >>> import sys >>> def ptrace(frame, event, arg): ... sys.stdout.write('%7s %5s: %10s %r\n' % ( ... event, ... frame.f_lineno, ... frame.f_code.co_name, ... frame.f_code.co_filename)) ... sys.stdout.flush() ... if event != 'return': return ptrace ... >>> sys.settrace(ptrace) >>> def foo(x): ... return x*2 ... call 1: ? '' line 1: ? '' return 1: ? '' >>> foo(foo(3)) call 1: ? '' line 1: ? '' call 1: foo '' line 2: foo '' return 2: foo '' call 1: foo '' line 2: foo '' return 2: foo '' 12 return 1: ? '' Maybe it will give more clues. Regards, Bengt Richter From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Dec 8 20:24:19 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 09 Dec 2003 02:24:19 +0100 Subject: Building a new app in python and need some architecture advice. In-Reply-To: <2v7atvkja4e7gd54sualt1d1jjprh9v0sg@4ax.com> References: <3fd51ecb$0$210$e4fe514c@news.xs4all.nl> <2v7atvkja4e7gd54sualt1d1jjprh9v0sg@4ax.com> Message-ID: <3fd52443$0$210$e4fe514c@news.xs4all.nl> Sam Watson wrote: >>What do you mean exactly with "across the web"? Over HTTP? Port 80? >>"in a secure fashion": SSL? Encrypted? Authentication? Authorization? >>So many options ;-) >> > > I dont know exactly what i mean :) It doesnt matter to me as long as > its secure. I dont really need stateless because this thing aint > gonna scale past 10 users and keeping state solves a bunch o problems. Well you have to define what "secure" is for you. Secure can mean a lot of things. > It sounds like pyro may do the trick here. The thing it would seem I > would be losing with pyro is the ease of iterating and linking maps > and lists of objects. Can I do this transparently with pyro? What makes you think you would lose that with Pyro? (and not with other IPC protocols) Pyro's goal is to make the network as transparent as possible for the application programmer. So yes, you will be able to access remote objects as lists etc. But it won't be very fast if you iterate a 20,000 node list over the network. Better grab the list as a whole over the network and iterate the list locally. >>>Twisted (Is this overkill?) >> >>Don't know, depends on your type of server application I guess. >> > > its nothing special. your basic data entry app with some minor > reporting. Simple as it gets. IMHO Twisted is overkill then. And you would still have to decide on the actual communication protocol you'd be using... >>>Pure sockets (a lot of infrastructure to write but im pretty >>>experienced with it) >> >>Why write it when you don't have to (see other options). >> > > The only reason I would write it myself would be control, performance, > and ultimate flexibility. It doesnt seem very pythonish tho. For the kind of app that you described it seems to me as if you wouldn't want to spend a big chunk of your development time on the communication stuff, and about performance: does a data entry app have to shove 50Mbit/s over the network? Cheers, --Irmen. From peter at engcorp.com Sun Dec 7 21:38:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 07 Dec 2003 21:38:27 -0500 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> Message-ID: <3FD3E423.B53D23DE@engcorp.com> Todd Gardner wrote: > > I would like to graph two columns of x,y numbers? I would greatly > appreciate any pointers or suggestions. Yes, include more detail about what you want to do. Specifically, what platform, do you care if it's wxPython, or Tkinter, or something else, etc. There are about a zillion possible answers to your question as it stands, and "python graphing" or something on Google would likely get you a lot of mileage right now. Maybe after you do a little research there you can come back with a more detailed question? -Peter From bokr at oz.net Fri Dec 19 20:27:39 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Dec 2003 01:27:39 GMT Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: On Fri, 19 Dec 2003 14:49:10 -0800, David Eppstein wrote: >In article , bokr at oz.net (Bengt Richter) >wrote: > >> Here is one that works also for negative numbers (includes the least >> significant >> of the arbitrarily extended sign bits): >> >> >>> def bitnos(self): >> ... """Little-endian bit number generator""" >> ... bits = long(self) >> ... sign = bits<0 >> ... bitno = 0 >> ... while bits>0 or sign and bits!=-1L: >> ... if bits&1: yield bitno >> ... bitno += 1 >> ... bits >>= 1 >> ... if sign: yield bitno >> ... > >I'm not sure I would call that working -- what I'd expect for a negative >number is to generate an infinite sequence. > Hm, yeah, if you don't know the sign, there's obviously an ambiguity. Maybe I should flag by making the last line if sign: yield -bitno. With that change we can get the number back: >>> for i in range(-3,4)+[0x16,-0x16]: ... print '%3s => %s' % (i, sum([p>=0 and 2**p or -2**-p for p in bitnos(i)])) ... -3 => -3 -2 => -2 -1 => 1 0 => 0 1 => 1 2 => 2 3 => 3 22 => 22 -22 => -22 The repr of my lbits.LBits class doesn't have that problem, since the msb is always the lsb sign bit (except that I used '11b' for -1 for symmetry) BTW, what would you think of having signed binary literals in python, so you could write natively a = 010110b # not legal now b = 101010b # ditto like the strings my LBits constructor accepts >>> a = LBits('010110b') >>> a 010110b >>> b = LBits('101010b') >>> b 101010b >>> a+b 0b >>> a+b, a==-b (0b, True) >>> map(int, [a,b]) [22, -22] Sometimes it's nice to see bits, e.g., the bit isolation of your algo, shown step by step: >>> a 010110b >>> a &~(a-1) 010b >>> a ^= a &~(a-1) >>> a 010100b >>> a &~(a-1) 0100b >>> a ^= a &~(a-1) >>> a 010000b >>> a &~(a-1) 010000b >>> a ^= a &~(a-1) >>> a 0b Regards, Bengt Richter From bnsbp at texas.net Sat Dec 6 15:07:02 2003 From: bnsbp at texas.net (Barry Newberger) Date: Sat, 06 Dec 2003 14:07:02 -0600 Subject: Installing Python 232 onto CD-ROM Message-ID: Wanted to install Python 2.3.2 for Windows onto a CD-ROM. Problem, my high-speed connection is on PC with no CD burner. My solution: install onto USB removable cartridge, move the cartridge to my "other" computer and burn image of the cartridge onto the CD. Oh silly me. Installation onto the cartridge, and so far, so good. Install and runs hunky-dory from the removable. Burn onto the CD, and launch. Now fails with an "import site failed" error. After hitting the documentation, heck the sys.path list and no \lib\site-packages subdirectory. (Running from the removable, this subdirectory does appear. And the subdirectory is on both the CD-ROM and removable cartridge.) Add a .pth file with the subdirectory string. Still no good. Crying uncle at this point. TIA, Barry Newberger From skip at pobox.com Mon Dec 22 09:39:39 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Dec 2003 08:39:39 -0600 Subject: How do I test if an object is a sequence? In-Reply-To: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> References: <3fe6fbb1$0$69983$edfadb0f@dread12.news.tele.dk> Message-ID: <16359.555.38006.503958@montanaro.dyndns.org> Max> Then there is the approach of testing for a method that they all Max> share. The only one that springs to mind is the slice operation. Max> def is_sequence(object) Max> try: Max> test = object[0:0] Max> except: Max> return False Max> else: Max> return True Max> But it has the disadvantage that string also are sequences. But not Max> exactly the kind I am interrested in. Max> So it will need to be expanded to: Max> from types import StringTypes Max> def is_sequence(unknown): Max> if isinstance(unknown, StringTypes): Max> return False Max> try: Max> test = object[0:0] Max> return True Max> except: Max> return False Max> But that looks kind of ugly for a "simple" type check. Max> There must be a better way? Not really. You're better off testing for whatever operations you want to perform. You run the risk of overlapping with mapping objects, but that's life. Skip From razor-report at daimi.au.dk Mon Dec 8 15:53:54 2003 From: razor-report at daimi.au.dk (Rasmus) Date: Mon, 8 Dec 2003 21:53:54 +0100 Subject: Elementric(?) import problem? References: <3FD4C9A9.A8A03CBB@engcorp.com> Message-ID: Thanks. Hope this will teach me to read the whole manual before asking :-) R -- PS: Due to heavy(!) spam reception (1,000-26,000+/week), I use a fake sender address. Please answer in the newsgroup. And don't forget to hide your own address to avoid ending up in tons of spam. "Peter Hansen" wrote in message news:3FD4C9A9.A8A03CBB at engcorp.com... > Rasmus wrote: > > > > Still learning python, I have searched for guides, and found this one: > > http://www.cs.lth.se/Education/LU/kurser/dat108/PythonProgramming.pdf > > > > When trying some of the examples like > > >>> from Numeric import * > > You need to download the package, as it's not part of the standard > distribution: http://www.pfdubois.com/numpy/ > > See the last page of your PythonProgramming.pdf document for links > including the above... > > -Peter From francisgavila at yahoo.com Sat Dec 20 22:44:18 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 20 Dec 2003 22:44:18 -0500 Subject: Unicode from Web to MySQL References: <3FE47726.90504@rfa.org> <3FE4796D.1010609@rfa.org><16356.44377.466955.783810@montanaro.dyndns.org> Message-ID: Bill Eldridge wrote in message ... >Skip Montanaro wrote: >Encoding for example is a UTF-8 page Vietnamese, >try: > > http://www.rfa.org/service/index.html?service=vie >or > http://www.rfa.org/service/article.html?service=vie&encoding=9&id=123655 > >I've tried grabbing this, doing vietstring.decode(None,'strict') >gives an error (wants a string, not None), doing >unicode(data,'unicode','replace') fails, >unicode(data,'raw-unicode-escape','replace') somewhat works, >I can then try >unicode(data,'raw-unicode-escape','replace').encode('utf-8') >but I get a SQL error at that point. You still have not understood the crucial lession: Unicode is *not* *an* *encoding*. Not an encoding! Immediate logical ramification: UTF8 (or whatever other encoding you wish to name) IS NOT UNICODE! Let's look at each of your attempts and see why each makes no sense: >>> vietstring.decode(None, 'strict) How can a str be decoded from nothing? If it has no encoding, it's just raw bytes with no meaningful interpretation of those bytes. And now you want a unicode object to be magically produced? What you should say is, "Ok, I know that vietstring is utf8 encoded, so to decode it (to a unicode object), I guess I'll have to tell Python vietstring.decode('utf8'), meaning 'Decode vietstring from utf8.'" >>> viet = urllib.urlopen('http://www.rfa.org/service/index.html?service=vie') >>> vietstr = viet.read() >>> type(vietstr) # Raw bits; no intrinsic meaning >>> vietunicode = vietstr.decode('utf8') >>> type(vietunicode) # Raw intrinsic meaning; no bits. >>> unicode and str are diametrically opposed views of reality. Unicode is the rationalist--there's no reality outside of meaning (i.e., no bits). Str is the empiricist--there's only raw bits, and the only meaning is what you give them. >>> unicode(data, 'unicode', 'replace') You want a unicode object to be produced from data, which you declare as being in the 'unicode' encoding. But there's no such encoding! Unicode is *not* an encoding! Unicode is more abstract than bytes. Do not ever think of bytes and unicode in the same thought. >>> unicode(data, 'raw-unicode-escape', 'replace') This may seem to work, but really its exactly the same as ur''--its treating data as though it were a raw unicode literal: >>> s = '\\u1234' >>> len(s) 6 >>> us = unicode(s, 'raw-unicode-escape') >>> us u'\u1234' >>> len(us) 1 This is not what you want! So unicode(data,'raw-unicode-escape','replace').encode('utf-8') is the utf8-encoded str of what you didn't want in the first place! vietstring.decode('utf8') will give you what you want, namely, a unicode object. Before you feed the unicode object to SQL, encode it to utf8 (a str object). This part you seem to understand just fine, but you have some sort of mental block against recognizing that you need to decode the string you got from the web before you can get a unicode object! In this particular case, (where it's already utf8) you can put vietstring straight into the SQL database as you found it, without doing any conversion at all. But this is only because the raw bits are the same they would have been if you had decoded to pure unicode and then encoded to utf8. To make sure that all your problems are with Python unicode<->str conversion confusion, and NOT with SQL, try placing vietstring straight into SQL without touching it. -- Francis Avila From aahz at pythoncraft.com Wed Dec 10 11:56:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Dec 2003 11:56:48 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: In article , Jacek Generowicz wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> Generally speaking, map() won't be any faster than a for loop. > >This is at odds with my own experience (including a lot of timing runs >in the last two days), countless posts on this newsgroup over the >years, and, for exapmle, this article > > http://www.python.org/doc/essays/list2str.html All right, what I should have said is that map() isn't enough faster than a for loop in the cases where it is faster to make much difference, and there are definitely cases where it's slower than the equivalent for loop, and it's usually less readable than some other way of getting speed. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From allenabethea at aol.com Sun Dec 7 11:22:17 2003 From: allenabethea at aol.com (Allenabethea) Date: 07 Dec 2003 16:22:17 GMT Subject: Why Python won't work on .net Message-ID: <20031207112217.14343.00000306@mb-m14.aol.com> Jython is 100% java coded python. Python objects work with javacompilers and Virtual machines. I am a hobby programmer so the technical reasons are probably beyond me... Why is python incompatible with .net? Why can't python be coded in C#? I see the the MONO project on linux/unix is advancing. .Net seems to be a juggernaut especially if programmers will be able to use their favorite(most productive) language to program in. (every language but python) I am a new python tinkerer. I love the language. But what is its future but as a legacy tool? allen From http Fri Dec 5 16:30:15 2003 From: http (Paul Rubin) Date: 05 Dec 2003 13:30:15 -0800 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> <7xptf639rd.fsf@ruckus.brouhaha.com> <7xoeuq5sp2.fsf@ruckus.brouhaha.com> Message-ID: <7xbrqn7y1k.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > >I'm running tens of thousands of messages through it one after another. > >It could really be that many distinct addresses. > > Maybe. OTOH, my ISP (Panix) uses SA for several thousand customers, so > I'm sure they can't be taking 1.5 seconds per message. Either they're > running much heavier hardware than you (unlikely, IMO) or they've got > some config difference that makes it work. I wonder if it's possible to import the spam address blacklists (update the local copy a few times a day) instead of doing constant network hits on them. That would speed things up a lot. From ewoud.van.raamsdonk at altium.noo-schpam.nl Wed Dec 3 06:06:24 2003 From: ewoud.van.raamsdonk at altium.noo-schpam.nl (Ewoud) Date: Wed, 03 Dec 2003 12:06:24 +0100 Subject: Chameleon ++ In-Reply-To: References: Message-ID: <39db.3fcdc3ab.4166e@altium.nl> Samuel Sagan wrote: > Hi > I'm considering starting a new project at SourceForge, codenamed > 'Chameleon++'. > > The concept is to develop a set of C++ clases and functions that closely > mimmick the Python fundamentals: lists, tups, dictionnary, built-in > functions and, later, as many modules as possible. > > This would make it relatively easy to convert Python code into C++, using > mainly regular expressions and string replacement. > > In other words: compile Python apps via C++. > > Less important, but could come handy at times: the Chameleon++ subset of C++ > would make it very easy for people knowing Python to write in C++. > (Chameleon++ would not use pointers, etc -- only what we use in Python.) > > Among other things, Chameleon should also provide a pathway to .NET, since > C++ compiles to .NET. But the main goal remains to compile Python apps via > the C++ route. > > Before starting, any comments or directions you may have would be greatly > appreciated. > > Samuel Sagan > > > I think a major part of what makes python so useful are the modules that come with it. Without those it would still take a lot of effort to port any python app to c++. Do you have any ideas on how you will handle that? Regards, Ewoud From razor-report at daimi.au.dk Mon Dec 8 12:31:18 2003 From: razor-report at daimi.au.dk (Rasmus) Date: Mon, 8 Dec 2003 18:31:18 +0100 Subject: Elementric(?) import problem? Message-ID: Hi. Still learning python, I have searched for guides, and found this one: http://www.cs.lth.se/Education/LU/kurser/dat108/PythonProgramming.pdf When trying some of the examples like >>> from Numeric import * >>> a = array( (1,2,3) ) I get the error: >>> from Numeric import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named Numeric >>> I might have some setup problems? I'm running winXP, please advice me of either where to read, or what to do. Thanks in advance, Rasmus From dw-google.com at botanicus.net Wed Dec 24 12:38:03 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 24 Dec 2003 09:38:03 -0800 Subject: implementing mv References: Message-ID: <99dce321.0312240938.1ae0436b@posting.google.com> "Martin v. Loewis" wrote in message news:... > Hong Jiang wrote: > > > Is there an efficient way to implement the 'mv' command? I mean not by > > calling external commands. > > Try shutil.move. 'Sometimes' os.rename can do moves too, however for your purposes shutil.move sounds better suited. David. From newsgroups at jhrothjr.com Sat Dec 20 12:27:57 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 12:27:57 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: "David M. Wilson" wrote in message news:99dce321.0312200919.3dd4af66 at posting.google.com... > "John Roth" wrote... > > > What I'm missing, however, is any *thoughtful* > > discussion of the issues involved. Your [perjoritive > > adverb deleted] response makes it clear that you > > didn't think of the issues, you just reacted. > > The point he was making (in a rather convoluted way) is that optional > parens is against the Python philosophy. "Explicit rather than > implicit" being line 2. I would rather be forced to use empty parens > after a function call - it shows you/others exactly what you are > trying to do. > > On the other hand, I would detest Python if by simply referring to an > object with a __call__ method caused it to be executed. I'd say that's > closer to braindead. > > a = sys.exit > a > > Unless you design some silly rules to determine when empty parenthesis > should be allowed - did a get assigned the return value of sys.exit()? > (yes I know it doesn't have one), or did some silly unclear > (implicit) rules stop that from happening. Did sys.exit() run on the > second line? > > I think if you can't understand why this option isn't provided for > you, then you misunderstand some of the most fundamental Python > concepts. import this. I don't think I misunderstand it. As I've said several times in this thread, I am not seriously advocating it for a number of reasons. However, yours is not one of them. It's easy enough to distinguish between a function and some other kind of object that simply has a __call__ method. Functions provide the number of parameters they are expecting, other callables don't, so it would indeed be brain dead to expect an absent call parameter to call something other than a function. Also, to make it crystal clear, to call anything other than a function that is expecting no parameters. Please think before making a critique. John Roth > > > David. From newsgroups at jhrothjr.com Tue Dec 23 11:39:34 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Dec 2003 11:39:34 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Terry Reedy" wrote in message news:Vt2dnVX2JsOw83WiRVn-iQ at comcast.com... > John Roth" wrote in > message > > > Technically, since names are simply keys in > dictionaries, > > This is only true of attribute names, the third > use of 'name'. That's the sense I assumed Francis Avila was using the term in, and I didn't particularly care to be pedantic and discuss the different ways the word 'name' can be used, espeially since Lewis Carroll did such a fine job of it once. Of course, I could be wrong about which usage he intended. John Roth > Definition names start as code > token names and become values of a __name__ > attribute, not a key. Code token names otherwise > become whatever the interpreter does with them, > which might or might not be to make them a Python > dictionary key. > > Terry J. Reedy > > From gagenellina at softlab.com.ar Fri Dec 26 21:17:02 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2003 23:17:02 -0300 Subject: Identifying File type by reading files In-Reply-To: <93f5c5e9.0312261055.60a88bf@posting.google.com> Message-ID: <5.2.1.1.0.20031226225721.01e8dc70@192.168.0.115> At 26/12/2003 10:55, you wrote: >I have some functions that search for files that contain certian >strings and if the files found to have these string do not already >have a filename extension (such as '.doc' or '.xls') the function will >append that to the files and rename them. So, if a file named 'report' >was found to have the string 'Microsoft' and the string >'Word.Document.' (notice the '.' at the end of both words) and it does >not already have an extension, then a rename would take place that >would name the file 'report.doc' > >These functions work very well on most files (98% guessed correctly). >However, I would like the functions to be more precise (100%). So, >what should I look for in a file to determine whether or not it is a >MS Word file or an Excel file or a PDF file, etc., etc.? Below is a >list of some of the strings I use to ID files, but I can't help but >wonder that there must be a more precise way of doing this. I know of >the Unix 'file' command. It is not very useful for me as it doesn't >distinguish between MS Office documents... all .xls, .docs, .ppts are >MS documents to it. The various Office applications *used* to store data in OLE2 Compound Document format. If your program is running in Windows you could try IStorage & Co. to read and detect document types (more reliable than detecting strings and magic numbers). http://msdn.microsoft.com/library/default.asp?url=/library/en-us/stg/stg/istorage.asp The binary format is documented anywhere inside msdn, so you could use a magic-number approach too. But now I've been told (I dont use them) that Office 2003 (maybe Office 2000 too?) stores documents in XML format, and Word sometimes uses RTF too (even with .doc extension) so you should check that too. Gabriel Genellina Softlab SRL From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Tue Dec 30 06:34:24 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Tue, 30 Dec 2003 12:34:24 +0100 Subject: Programming language from python References: <3ff14d10$0$317$e4fe514c@news.xs4all.nl> Message-ID: >>> While Python approaches this almost, I believe the Sqiwrnsyivstblz++ toolkit, available on the third rock circling Betelgeuse, is highly superior at the moment. Hi ! But you don't know Var'Aq, the klingon Programmin Language" ??? See this links : http://www.geocities.com/connorbd/varaq http://web.tampabay.rr.com/ngabwi/varaq.htm http://www.trektoday.com/news/070800_05.shtml http://www.langmaker.com/db/mdl_varaq.htm http://en.wikipedia.org/wiki/Var%27aq @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From luigipaioro at libero.it Tue Dec 9 04:24:50 2003 From: luigipaioro at libero.it (Luigi) Date: 9 Dec 2003 01:24:50 -0800 Subject: Web authentication References: <9415febc.0312081244.2b03fa65@posting.google.com> Message-ID: I'm very very sorry!!!! My user name was wrong! Right now the second one works fine!!! Thank you very much!!! Luigi gregj at pobox.com (Greg Jorgensen) wrote in message news:<9415febc.0312081244.2b03fa65 at posting.google.com>... > luigipaioro at libero.it (Luigi) wrote in message news:... > > > These are my attempts: > > ... > > Both don't work! > > Where is my mistake?? > > Since you don't know what the problem is and you probably aren't > familiar with proxies and header sniffing, try fetching the page with > curl (http://curl.haxx.se/), which you will already have if you run > Linux. Once you have it working from the command line with curl you > can translate to Python. > > Turn on curl's verbose output: > > curl -v http://user:password at www.mysite.com/page.html > > Possible reasons for your problems: > > - username/password wrong > - url wrong > - server not using basic authentication > - server expecting specific referrer, IP address, user agent > - secure connection (HTTPS) required > > Some of these problems will be apparent from curl's output. Others > (like the referrer or user agent check) will not, but you can perhaps > deduce them from how the site works from a browser. > > > Greg Jorgensen > PDXperts LLC > Portland, Oregon USA From tim at worthy.demon.co.uk Tue Dec 30 04:46:26 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Tue, 30 Dec 2003 09:46:26 GMT Subject: Monitoring an MS Exchange mailbox References: Message-ID: <961ada684c.tim@worthy.demon.co.uk> In message Lindstrom Greg - glinds wrote: > I have written a script to monitor my MS Exchange mailbox for certain > messages and post information to an MS SQL Server Database. > Is there any way to either specify the profile or accept the default? I don't know about that but I do something similar using imaplib - it used to connect to a non-Exchange email server, I left it as it was when we switched to Exchange and it continued to work (obviously with IMAP enabled in Exchange). -- ___ |im ---- ARM Powered ---- From raims at dot.com Sat Dec 27 16:42:21 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 27 Dec 2003 22:42:21 +0100 Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> Message-ID: <87k74i545e.fsf@mobile.foo> MidasOneTwo at hotmail.nospam.com (Midas) writes: > Thanks for replying. It looks like you hardcoded the name ObjectB > within ClassA. I'd like to avoid all hardcoding of names. In other > words, I'd like ObjectA to be *told*, at run time, which object to call > and which method to call. Mmm what do you mean with "to be told, at run time, which object to call and which method to call" ? Something like: if var == "a": # create object a and call method x else: # create object c and call method y ? -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From mwh at python.net Tue Dec 16 05:50:07 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 16 Dec 2003 10:50:07 GMT Subject: Terminal "hang up" problem References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: JD writes: > What is the best way to debug a Python program if when i run it, it > totally hangs up the > terminal console. > > Control-c or control-d has NO effect, so it's hung up somewhere, but > we have no idea > where. > > We are using Python 2.3, on an openBSD box, running the python > script from the shell. "gdb -p"? Cheers, mwh -- Q: Isn't it okay to just read Slashdot for the links? A: No. Reading Slashdot for the links is like having "just one hit" off the crack pipe. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq From marks.pryorSHRUB at CHENEYverizon.net Sun Dec 7 15:48:37 2003 From: marks.pryorSHRUB at CHENEYverizon.net (Mark S Pryor) Date: Sun, 07 Dec 2003 20:48:37 GMT Subject: win32: tile desktop windows References: Message-ID: "Mark S Pryor" wrote in message news:UaMAb.2170$nz.1129 at nwrddc01.gnilink.net... > hello c.l.p., > I run my desktop at 2560 x 1024. When I get > involved manually resizing and moving windows about, > I keep thinking that I should be able to > automate this with a Python script. > > Anyone ever seen such a script? I'm looking to > write an API method, unless someone can steer me > some other way. > > = Enum all visible top level windows > = choose the largest even set (4,6,8) > = send WM_SIZE to all I see that ActivePython 2.2 supports win32gui.movewindow pycwnd.movewindow looks like a better way. > = tile each monitor (dual 17 in. LCD) vertically and/or > horizontally. > > tia, > msp > > From robin at jessikat.fsnet.co.uk Wed Dec 3 03:58:48 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 3 Dec 2003 08:58:48 +0000 Subject: Chameleon ++ References: Message-ID: In article , Samuel Sagan writes >Hi >I'm considering starting a new project at SourceForge, codenamed >'Chameleon++'. > >The concept is to develop a set of C++ clases and functions that closely >mimmick the Python fundamentals: lists, tups, dictionnary, built-in >functions and, later, as many modules as possible. > >This would make it relatively easy to convert Python code into C++, using >mainly regular expressions and string replacement. > >In other words: compile Python apps via C++. > >Less important, but could come handy at times: the Chameleon++ subset of C++ >would make it very easy for people knowing Python to write in C++. >(Chameleon++ would not use pointers, etc -- only what we use in Python.) > >Among other things, Chameleon should also provide a pathway to .NET, since >C++ compiles to .NET. But the main goal remains to compile Python apps via >the C++ route. > >Before starting, any comments or directions you may have would be greatly >appreciated. > >Samuel Sagan > > > Before reinventing the wheel, have you compared what you intend with what boost python already does? Or is the intention to emulate python in C++? There's also a python for net extension recently announced (I forget the name). In addition the pypy project intends to write python code translators and have it translate python to various backends. -- Robin Becker From rmunn at pobox.com Tue Dec 16 17:45:21 2003 From: rmunn at pobox.com (Robin Munn) Date: Tue, 16 Dec 2003 22:45:21 GMT Subject: I see advice on how to debug a python module that hangs up the process References: Message-ID: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> JD wrote: [snip problem with Python program that hangs] > How should I approach debugging this? Are there Python tools? Or should > I > use gdb? ktrace? systrace? I'm assuming I have to do this, as a bug > report > which reads "Python locks up" isn't too useful. The first step I'd suggest is to sprinkle print statements all around your code: print "About to call some_func()..." some_func() print "Returned from calling some_func()..." Then you can watch the console output (or redirect it to a file for later perusal) and see when the thing hangs. -- Robin Munn rmunn at pobox.com From bdesth.tagada at tsoin-tsoin.free.fr Wed Dec 17 18:30:01 2003 From: bdesth.tagada at tsoin-tsoin.free.fr (Bruno Desthuilliers) Date: Thu, 18 Dec 2003 00:30:01 +0100 Subject: Save the pythons. In-Reply-To: References: Message-ID: <3fe0e2af$0$24024$626a54ce@news.free.fr> f29 wrote: > I don't believe that noone has yet spotted that python is becoming > java. Each new version is fully equipped with more garbage than > before. Classes are great, but once there are 1000 of them, inheriting > from each other, I cannot avoid comparing this unpleasant situation to > java. > Python power is in it's syntax, not addons. Let's not copy perl's > experience and one java is already far too much for earth. > > f29 Too big. Won't work. From timothy.williams at nvl.army.mil Wed Dec 10 11:23:34 2003 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 10 Dec 2003 08:23:34 -0800 Subject: tkFileDialog.askopenfilenames not regonizing -multiple option References: Message-ID: Martin Franklin wrote in message news:... > On Fri, 2003-12-05 at 13:32, Tim Williams wrote: > > Hi. > > > > I'm using Python 2.3 and trying to use tkFileDialog to get a list of > > files. I get a message about the '-multiple' option is not a valid > > option in the call to Open. > > > > (snip) > > You will need to upgrade to tcl/tk 8.4 as the multiple option was not > added until then. > > Regards, > Martin. > > > > Thanks for any help. I installed Tcl/Tk 8.4.5 and now I'm having a problem installing Python 2.3.2: ######################################## ranlib libpython2.3.a c++ -pthread -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.3.a -lpthread -ldl -lutil -L/vps/pkg/Linux/lib -ltk8.4 -ltcl8.4 -lm libpython2.3.a(posixmodule.o): In function `posix_tmpnam': /vps/pkg/Linux/src/Python-2.3.2/Modules/posixmodule.c:5781: the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.3.a(posixmodule.o): In function `posix_tempnam': /vps/pkg/Linux/src/Python-2.3.2/Modules/posixmodule.c:5736: the use of `tempnam' is dangerous, better use `mkstemp' case $MAKEFLAGS in \ *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac ./python: error while loading shared libraries: libtk8.4.so: cannot open shared object file: No such file or directory make: *** [sharedmods] Error 127 ############################### I installed Tcl/Tk in a non-standard directory, since I don't have root, but I edited the Modules/Setup file to have # *** Always uncomment this (leave the leading underscore in!): _tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ # *** Uncomment and edit to reflect where your Tcl/Tk headers are: # -I/usr/local/include \ -I/vps/pkg/Linux/include \ # *** Uncomment and edit to reflect your Tcl/Tk versions: # -ltk8.2 -ltcl8.2 \ -ltk8.4 -ltcl8.4 \ gumbo:/vps/pkg/Linux/src/Python-2.3.2> ls -l --color=none /vps/pkg/Linux/lib/libt*8.4* -r-xr-xr-x 1 williams c4i 753972 Dec 10 08:22 /vps/pkg/Linux/lib/libtcl8.4.so* -rw-r--r-- 1 williams c4i 1696 Dec 10 08:22 /vps/pkg/Linux/lib/libtclstub8.4.a -r-xr-xr-x 1 williams c4i 870936 Dec 10 08:31 /vps/pkg/Linux/lib/libtk8.4.so* -rw-r--r-- 1 williams c4i 3094 Dec 10 08:31 /vps/pkg/Linux/lib/libtkstub8.4.a I can install python 2.3 (w/o changing Setup) w/o problems. From python-url at phaseit.net Fri Dec 26 09:51:32 2003 From: python-url at phaseit.net (Emile van Sebille) Date: Fri, 26 Dec 2003 14:51:32 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 26) Message-ID: QOTW (advanced interfaces track): "I'm firmly in favour of any language that can DWIMNWIS." -- Tim Delaney QOTW (MS roadkill track): "Underestimate MS at your own risk. It is one thing to not like MS, and possibly a reasonable position to take. However, underestimating them is for fools." -- Mark Hammond, on Microsoft's commitment to .net. Anthony Baxter releases Python 2.3.3 final. http://groups.google.com/groups?selm=mailman.381.1071951151.9307.python-list at python.org Guido van Rossum confirms the ownership transfer of python.org to the PSF. http://groups.google.com/groups?selm=mailman.1071930722.27948.clpa-moderators at python.org Richard Jones announces SC-Track Roundup 0.6.4, an issue tracking system. http://groups.google.com/groups?selm=mailman.1071631682.2786.clpa-moderators at python.org Paulo Pinto is looking for the pythonic way of doing tcl's uplevel. http://groups.google.com/groups?threadm=brmpt2$7nn$1 at sunnews.cern.ch Padraig investigates the interaction of object scope and reachability through exceptions. http://groups.google.com/groups?threadm=0%mEb.1392$HR.4074 at news.indigo.ie Jason Tesser has an objection to dynamic typing raised at work when he suggests python as an appropriate language for a new project. http://groups.google.com/groups?threadm=mailman.355.1071850867.9307.python-list at python.org Anthony Tuininga announces three cross platform python based Oracle modules: ...cx_Oracle 4.0, a DBAPI 2.0 Python extension module for Oracle... http://groups.google.com/groups?selm=mailman.1071684783.10357.clpa-moderators at python.org ...cx_OracleTools 7.2, to handle Oracle database development tasks... http://groups.google.com/groups?selm=mailman.1071856207.1807.clpa-moderators at python.org ... and cx_OracleDBATools 2.0, that addresses Oracle DBA tasks. http://groups.google.com/groups?selm=mailman.1071856203.1804.clpa-moderators at python.org A comment by Guido in PEP 279 causes Logan concerns about using filter and map. http://groups.google.com/groups?threadm=pan.2003.12.17.18.35.25.713854 at phreaker.nospam Marc gets help hiding the console window when using py2exe. http://groups.google.com/groups?threadm=4378fa6f.0312182234.42c4fe73 at posting.google.com Glen Wheeler looks into ways of reducing memory footprint when dealing with millions of small integers, but finds it may be the pointers eating his memory. http://groups.google.com/groups?threadm=s7i4uvchbhm26mhhshh13lchj0a6uuddd6 at 4ax.com John wants advice on debugging a python process that's hanging. http://groups.google.com/groups?threadm=mailman.223.1071608597.9307.python-list at python.org Brandon J. Van Every asks if anyone's kicking the tires of python for .net, which leads to a comment on Microsoft as technology leader. http://groups.google.com/groups?threadm=brnuts$591mp$1 at ID-207230.news.uni-berlin.de Matthew Sims gets lessons on using python lists and how they differ from perl's. http://groups.google.com/groups?threadm=1e963607.0312151408.583221e6 at posting.google.com Edward K. Ream announces the release of Leo 4.1 rc3, an outlining editor for programmers. It is written in 100% pure Python. http://groups.google.com/groups?selm=vu682r680amh8d at corp.supernews.com Kamus of Kadizhar gets help with the logging module and then on googling, prompting Skip to start a tips page. http://groups.google.com/groups?threadm=brs5rc$dslu$1 at news3.infoave.net http://www.python.org/cgi-bin/moinmoin/GoogleTips John Hunter releases matplotlib-0.40, a pure python cross platform 2D plotting library with a matlab syntax. http://groups.google.com/groups?selm=mailman.157.1071504049.9307.python-list at python.org Gustavo Campanelli gets a quick response from Andrew Clover when he asks about a problem with Gif transparency and Pil. http://groups.google.com/groups?threadm=brlfna$ir8$1 at taurus.webcorp.pl Davide Carboni forwards Michele Marchesi's request to take part in an online survey on agile practices adoption in software industry. http://groups.google.com/groups?threadm=brseqq$tng$7 at pietro.crs4.it Paul McGuire announces parsing 1.0.0, a Python class library for defining and executing text parsers. http://groups.google.com/groups?selm=q0zDb.222088$do1.192962 at twister.austin.rr.com Steve Holden announces that submissions for PyCon DC 2004 are now being considered. http://groups.google.com/groups?selm=mailman.161.1071510872.9307.python-list at python.org Paul Miller discovers a PyThreadState_Swap difference in 2.3.2 and needs help identifying the source of the problem. http://groups.google.com/groups?threadm=knbstvgsn3o3qmmtu975g8eb94rhpmae2o at 4ax.com Irmen de Jong announces the availability of Snakelets 1.9, a Python threaded web application server. http://groups.google.com/groups?selm=3fde25a4$0$209$e4fe514c at news.xs4all.nl Gilles Lenfant is looking for ways to do spell checking from Python. http://groups.google.com/groups?threadm=brl2vb$1dj$1 at biggoron.nerim.net Gustavo Campanelli solicits suggestions for a standalone client database for Python. http://groups.google.com/groups?threadm=brps08$fe9$1 at taurus.webcorp.pl Steve wants help automating remote access through ssh using python. http://groups.google.com/groups?threadm=3fe0dfd7$1 at clarion.carno.net.au Arcady Genkin releases a Samba password hashes generator. http://groups.google.com/groups?selm=mailman.1071510842.14628.clpa-moderators at python.org Jason R. Mastaler announces the release of TMDA 1.0 final, a python based anti-spam system. http://groups.google.com/groups?selm=mailman.1072147564.23791.clpa-moderators at python.org Patrick Useldinger announces bkmChk, a stand-alone Python program which checks URLs to detect dead links. http://groups.google.com/groups?selm=mailman.1071856205.1805.clpa-moderators at python.org ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jdhunter at ace.bsd.uchicago.edu Fri Dec 12 11:46:58 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 12 Dec 2003 10:46:58 -0600 Subject: do this with list comp? Message-ID: I want to replace all empty fields in a CSV line with 'NULL'. Here is a brute force way def fixline(line): ret = [] for s in line.split(','): if not len(s): ret.append('NULL') else: ret.append(s) return ret line = 'John,Bill,,,Fred' print fixline(line) # ['John', 'Bill', 'NULL', 'NULL', 'Fred'] I am wondering if there is a way to do it with list comprehensions. I know how I would do it with a ternary operator..... John Hunter From noemail at noemail4u.com Tue Dec 9 12:41:03 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Tue, 09 Dec 2003 17:41:03 GMT Subject: online examination system References: <425cc8d1.0312090932.697fd6c6@posting.google.com> Message-ID: <412aa581e375edd3be954b4d3a293ef1@news.teranews.com> On 9 Dec 2003 09:32:22 -0800, mir4uu at yahoo.com (mir nazim) wrote: >hi there, >One of my client needs a computer based examination system. It should >have following capabilities. > >1. It should support Multiple choice questions. >2. It should be adaptive, that is, difficulty should vary with each >question. > kind of those used in MCSD/MCSE/SCJP etc examinations. >3. should be web based. >4. MySQL support. (better be Database independent) >5. OS independent. > >Now please let me know if there is one available for ZOPE platform. >blesses-n-luck Does it need to be free also? --dang From usenet_spam at janc.invalid Sat Dec 13 01:14:07 2003 From: usenet_spam at janc.invalid (JanC) Date: Sat, 13 Dec 2003 06:14:07 GMT Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: "Edward K. Ream" schreef: > The (admittedly very cool) wxPython demo regularly > segfaults on Windows. Sheesh. Were you using the Unicode build on Win95/98/ME? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bignose-hates-spam at and-benfinney-does-too.id.au Mon Dec 1 22:03:15 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 2 Dec 2003 13:53:15 +1050 Subject: language learning vs. process References: Message-ID: On Mon, 1 Dec 2003 21:09:31 -0500, Ryan Walker wrote: > I'm finding that there is very little (that I can find) about how to > do basic logistical things related to using python and implementing > programs. For example: how to run a program. That's pretty basic, > but I don't see anything in the tutorials about it. That's probably because it's very dependent on the OS and environment you're using; running programs, forming commands, customising an environment are better documented in the docs for the OS. Putting that kind of stuff in detail into Python's docs (or a PYthon-specific tutorial) would be a waste of space: you'd be uninterested in all the information that was for environments other than your own. -- \ "It is seldom that liberty of any kind is lost all at once." | `\ -- David Hume | _o__) | Ben Finney From adsl5lcq at tpg.com.au Thu Dec 18 22:55:04 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Fri, 19 Dec 2003 14:55:04 +1100 Subject: How to use a 5 or 6 bit integer in Python? References: Message-ID: On 19 Dec 2003 13:59:44 +1050, Ben Finney wrote: >On Fri, 19 Dec 2003 11:42:49 +1100, Glen Wheeler wrote: >> My program uses many millions of integers, and Python is allocating >> way too much memory for these. > >How have you measured this? As pointed out by others, Python doesn't >have duplicate occurrences of identical integers; it refers to the same >object multiple times. > >Given this, I'm curious how you've measured the memory usage caused by >your program using millions of integers, and why you think reducing the >size of those integers will help significantly. I realise now that I was wrong in assuming this. However, Python does use more memory than it needs to to store the data I'm manipulating. This is probably caused by their container types, dictionaries and tuples, however. Reducing the amount of memory allocated by any method is my goal right now, along with increasing the speed at which my program runs. I'm using one dictionary to store all of the data, with tuples of ints as keys and a tuple as the data associated with each key. The data tuples contain a few ints and two more dictionaries. Can you think of a way to reduce the memory used here? Thanks, Glen From tzot at sil-tec.gr Tue Dec 23 03:14:55 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 23 Dec 2003 10:14:55 +0200 Subject: Default arguments, object sharing, name lookup and others References: Message-ID: <59ufuvs0beg9qukh1udt361po93cjshlnr@4ax.com> On Mon, 22 Dec 2003 17:20:09 +0100, rumours say that Maciej Sobczak might have written: >Hi, > >Playing around with the Python Tutorial I found the following definition: [snip of confusion about names and binding] This might help: http://groups.google.com/groups?selm=7u1ghvc2pppu75ceesas51ghjp9a2aib45%404ax.com Then again, it might not :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From gagenellina at softlab.com.ar Mon Dec 29 17:44:59 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Mon, 29 Dec 2003 19:44:59 -0300 Subject: NEWBIE: What's the instance name? In-Reply-To: References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <5.2.1.1.0.20031229193958.01fa0410@192.168.0.115> At 29/12/2003 11:03, you wrote: >Some of the classes have a common (or near common) display routine, >others are totally different. If I use lx.display(), the display code >has to be contained as a method in each class. I chose, for ease of >maintenance, to make a display module with all the display routines >gathered together in one spot. . In the event a future programmer >decided to make a change to the display routine for a given class, or >needed to add a class/display, I feel there's less chance of his/her >messing up the UPCA-like classes. I guess I'm a believer in >classes/methods doing a limited number of things, and doing them well. >Is that a C hang-over? You could define anyway a display() method in each class, and delegate the implementation to another module: class UPCE(UPCA): def display(self): othermodule.display_nice_upce_instances_as_I_know_how_to_do_that(self) class UPCF(UPCA): def display(self): othermodule.call_another_display_function(self) Gabriel Genellina Softlab SRL From matt at pollenation.net Tue Dec 30 15:42:10 2003 From: matt at pollenation.net (Matt Goodall) Date: Tue, 30 Dec 2003 20:42:10 +0000 Subject: function-arguments by reference In-Reply-To: <1072809902.14197@news.liwest.at> References: <1072788957.24786@news.liwest.at> <79v2vv0ijgdvqu354uh4mh21v4b3liurj0@4ax.com> <1072798233.200308@news.liwest.at> <1072809902.14197@news.liwest.at> Message-ID: <3FF1E322.5060208@pollenation.net> EsC wrote: >hy JCM! > >damned - you are right! >i didn't know the way Python is handling arguments >up to now! It's a little bit different to other languages >i know - and somtimes even a little bit easier. > >i made some (useless) performance-tests to proof your exclamations ... >if somebody is interested: i enclosed the code and results ... > >- String 1 & String2: only read-access within the called function >the runtime is almost identical; therefore the text of the string can't >be copied > > I don't think your test code proves that the string is not copied, only that passing a reference to a string takes approximately the same amount of time as passing a reference to a list and accessing the 1st item. A better "proof" that the string is not copied is: >>> s1 = 'this is a string' >>> def f(s2): ... print s1 is s2 ... >>> f(s1) True >>> The "True" result indicates that both s1 and s2 are bound to the same string object. >- String 3: the argument string is modified but NOT passed back to >the caller; >- String 4: the argument string is passed "by reference" within a >list object and modified. > >i think this informations are very interesting >thanks! > >greetings >iolo > > >------------ CODE ------------- >import sys >from string import * >from time import * > >def ls(str): > return len(str) > >def ll(str): > return len(str[0]) > >def as(str): > str += "x" > return len( str ) > >def al(str): > str[0] += "x" > return len( str[0] ) > >loop = 2000 >strlen = 30000 >strl = [] >strl.append("") >strs = "" > >for a in range(strlen): > strs += 'x' > strl[0] += 'y' > >print "Loop: ", loop >print "Stringlength: " , strlen > >print >print 'String 1' >l = 0 >start = time() >for x in range(loop): > l += ls(strs) >end = time() >print "duration in seconds: ", end - start >print "result: ", l >if strlen == l / loop: > print 'OK' >else: > print 'ERROR' > >print >print 'String 2' >l = 0 >start = time() >for x in range(loop): > l += ll(strl) >end = time() >print "duration in seconds: ", end - start >print "result: ", l >if strlen == l / loop: > print 'OK' >else: > print 'ERROR' > >print >print 'String 3' >l = 0 >start = time() >for x in range(loop): > l += as(strs) >end = time() >print "duration in seconds: ", end - start >print "result: ", l >if l == loop * strlen + loop: > print 'OK' >else: > print 'ERROR' > >print >print 'String 4' >l = 0 >start = time() >for x in range(loop): > l += al(strl) >end = time() >print "duration in seconds: ", end - start >print "result: ", l >if l == (loop / 2 ) * ((strlen + 1) + (strlen + loop)): > print 'OK' >else: > print 'ERROR' > >---------------- RESULT ---------------- >Loop: 50000 >Stringlength: 200000 > >String 1 >duration in seconds: 0.0620000362396 >result: 10000000000 >OK > >String 2 >duration in seconds: 0.0779999494553 >result: 10000000000 >OK > >String 3 >duration in seconds: 3.2349998951 >result: 10000050000 >OK > >String 4 >duration in seconds: 5.93700003624 >result: 11250025000 >OK >-------------------------------------------------- > >"JCM" schrieb im Newsbeitrag >news:bss7u2$18e$1 at fred.mathworks.com... > > >>EsC wrote: >> >> >>>hy! >>> >>> >>>thanks for your explanations! >>> >>> >>>i want to avoid performance-problems by repeated (very often) >>>function-calls with very long strings. >>>in some languages (C, PHP, Powerbuilder, ...) i have the opportunity, >>>to pass "by value" or "by reference/pointer)". >>> >>> >>The text of the string is not copied; a reference to the string/object >>is passed into the function. You can modify objects passed into >>functions (but only if they're mutable--strings and integers are >>examples of immutable objects), but you cannot rebind the variable >>holding the value in the caller's scope. >> >>There have been some discussions in this newsgroup about whether >>Python is call-by-value or not. I'm not sure if I want to recommend >>looking for them; there was no good consensus about the terminology. >> >> > > > > -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net From lists at webcrunchers.com Tue Dec 16 23:10:08 2003 From: lists at webcrunchers.com (JD) Date: Tue, 16 Dec 2003 20:10:08 -0800 Subject: I see advice on how to debug a python module that hangs up the process In-Reply-To: <-pmdncxNCLOeIkKiRVn-iw@comcast.com> References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> <-pmdncxNCLOeIkKiRVn-iw@comcast.com> Message-ID: On Dec 16, 2003, at 6:27 PM, Jeff Schwab wrote: > Bengt Richter wrote: >> On Tue, 16 Dec 2003 20:51:31 -0500, Jeff Schwab >> wrote: >> >>> Bengt Richter wrote: >> No I didn't. Please trim more carefully. >>>>> Then, we have to do a "kill -9" the process. >>> >>> Did you try it without -9? yes - it wouldn't kill. Only the -9 option would kill it. Like I posted earlier, After identifying the function that hangs up (my putting "print" statements before and after), we also put a print statement at the beginning of the function that hangs up, but it never gets called. So the process of calling the errant function is enough to send it to never-never land. How does one debug these kinds of problems? John From na Sun Dec 28 22:44:12 2003 From: na (Pythonious) Date: Sun, 28 Dec 2003 19:44:12 -0800 Subject: PHP and Python Message-ID: Hi I was interested in implementing a PHP web page that collected information from a guestbook in a database I don't have Python Support through my web host so I am using PHP Anyway thats besides the point I was looking through an older book called learning python. That had a Tkinter application that collected information from a python web script the application could edit the information and delete records. I want to do this using Tkinter but what I want to do is be able to use some sort of network protocal to remotely log in to my database I guess you could call it SSH or telnet to be able to edit the records in my database from my computer. But through a Graphical environment without having to execute mysql commands. My questions are could one of you fine Pythonians point me in the direction of what I would need to learn in order to be able to do this and reference materials Thank You Andrew From http Mon Dec 8 16:31:03 2003 From: http (Paul Rubin) Date: 08 Dec 2003 13:31:03 -0800 Subject: from spam import eggs, spam at runtime, how? References: <7xhe0bf5id.fsf@ruckus.brouhaha.com> Message-ID: <7xoeuj5754.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > >Another way: > > > > exec 'import spam' > > That's precisely what we were trying to avoid. I missed that part. The alternatives don't really seem better though. From chrisks at udel.edu Sat Dec 20 08:03:08 2003 From: chrisks at udel.edu (Chris S) Date: Sat, 20 Dec 2003 08:03:08 -0500 Subject: py2exe application crash References: <36fe33a9.0312200234.45e8a976@posting.google.com> Message-ID: Is this one of those telepathy experiments? Chris S. "Max DRUDI" wrote in message news:36fe33a9.0312200234.45e8a976 at posting.google.com... > I have build a simple exe using py2exe. > > I use it on 5 pc ( 1 Win2000 + 4 Win98). > Why this exe go in crash immediately on 3 pc's (all Win98) ? > > ...at the moment the only Win98 where exe don't crash is pc where i > develop the application...an the application must only view a > window... From vincent.rioux at no-log.org Mon Dec 8 09:01:45 2003 From: vincent.rioux at no-log.org (Vincent Rioux) Date: Mon, 08 Dec 2003 15:01:45 +0100 Subject: Tkinter question: drag and drop In-Reply-To: References: Message-ID: <6.0.1.1.2.20031208145708.01ba9350@pop.no-log.org> Hi, I know how to use dnd between two Tkinter windows but do not know if it is possible to receive a dnd call when dragging a file/folder icon from a window manager (e.g. winxp explorer, nautilus...) to a Tk window? /vr From lvraab at earthlink.net Mon Dec 1 17:11:35 2003 From: lvraab at earthlink.net (Lucas Raab) Date: Mon, 01 Dec 2003 22:11:35 GMT Subject: Scientific Python Message-ID: Is there a version of SciPy or Scientific (correct me if they're the same) available for Python 2.3.2?? If there's not could somebody point me in the right direction on getting an equivalent?? Thanks From fnord at u.washington.edu Wed Dec 10 00:57:35 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 9 Dec 2003 21:57:35 -0800 Subject: from spam import eggs, spam at runtime, how? References: Message-ID: You might also have a look at the imp module. (http://www.python.org/doc/current/lib/module-imp.html). It may be overkill for what you're trying to do, but I've found it to be quite useful for dynamic module manipulation. -ljp Rene Pijlman wrote in message news:... > How do I do: > > from spam import eggs > > ... when 'spam' is only known at runtime? From jjl at pobox.com Sat Dec 27 07:40:46 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Dec 2003 12:40:46 +0000 Subject: Project dream References: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> Message-ID: <87smj6mo1d.fsf@pobox.com> Paul Rubin writes: > hwlgw at hotmail.com (Will Stuyvesant) writes: > > What would your favorite be? > > A CVS-like system for email. You'd receive all your messages on a > server somewhere. You'd then be able to connect your laptop to the > internet, download ("check out") your mail, and read and reply to it > offline (not necessarily all of it). When you dial up again, the > replies get sent out and stored ("checked in") on the server, the > messages that you read get marked as read, the ones you didn't read > don't get marked, etc. The CVS-like aspect is that you can do the > same thing from your office computer, your friend's computer, etc., so > you have the same messages checked out on multiple clients at the same > time. The server automatically merges the "change sets" when you > check any in. Finally, the server shouldn't need any special protocol > to check messages in or out. It should be able to create a single > tarball or zipfile that you download, and accept a single tarball or > zipfile when you upload As Michael says, you're pretty much describing disconnected IMAP. I'm pretty sure it's supposed to handle multiple concurrent connections to one account & mailbox well, but it doesn't have CVS-like merge facilities -- I don't think I'd really want that, anyway. In reality, though, disconnected operation seems to be poorly implemented. At least, in Mulberry 2.x (or was in 3.x beta?), which is supposed to be an exemplary IMAP client implementation, it didn't really work for me (and Mulberry seems over-stuffed with features). Maybe it does with the current 3.x releases, it's been over a year since I tried it. Also, KDE's MUA (KMail?) is just getting support for disconnected IMAP now, but I'm sure it'll be a while before it actually works. Also, I've found it to be a pain to get MUAs working with IMAP servers (mostly using pine, which again is supposed to be a good IMAP implementation) -- I guess this is because the protocol has too many knobs and dials for its own good. fastmail.fm has mostly been very good (but one one-day outage during the recent power failures in US, and another one before that -- I think they've probably learned from that, though), very clueful and extremely good value for money (one-off 15 USD payment when I joined, with quite enough bandwith and storage for someone who has been subscribed to ten or so mailing lists in the past, and gets a lot of spam, and I think that price is still current). If anybody knows of a free disconnected IMAP client that works (especially in Python :-), please let me know! John From dman at dman13.dyndns.org Fri Dec 19 13:33:13 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Fri, 19 Dec 2003 18:33:13 GMT Subject: tuning memory and time usage (was: Re: How to use a 5 or 6 bit integer in Python?) References: Message-ID: Glen : On Fri, 19 Dec 2003 14:30:23 +1100, Glen Wheeler wrote: > I've read up on Numarray and the array module in the docs, but > didn't see how I could adapt my current program to use these modules > because of how my data is currently organised. You may need to reorganize the data in order to save space! > I have one constantly changing dict with many millions of keys > (tuples of ints) which in turn associates itself with a tuple of ints > and two more dicts. If you state the actual task and computation you are performing then people can suggest alternate data structures and algorithms. Simply describing your current data structure leaves people shooting in the dark trying to suggest alternate ways of storing the data. Usually time and space (memory) are mutually exclusive tradeoffs -- less computation requires more storage, less storage requires more computation. However, there are cases where poor choice in data structure and/or algorithm can allow a restructuring to improve both speed and memory use. In order to construct and evaluate data structure and algorithm suitability a a concrete understanding of what task needs to be performed by the program and what sort of data will be handled is essential. Presently you, Glen, are the only one with this knowledge of the task and problem space. Share that knowledge with the group and the group will then be capable of better assisting you. -D -- A mouse is a device used to point at the xterm you want to type in. --Kim Alm, a.s.r www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From gagenellina at softlab.com.ar Wed Dec 24 14:40:10 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2003 16:40:10 -0300 Subject: ungetch in Python In-Reply-To: Message-ID: <5.2.1.1.0.20031224163325.01f88060@192.168.0.115> At 24/12/2003 11:41, you wrote: >I'm writing a small parser for a minilanguage in Python, >and I was wondering --- is there any equiv. of C's ungetch >or Scheme's peek-char in python? That is, is there a way to No, and neither a getc(), but you can make them easily (provided you just ungetc *one* char at a time) (Untested): class file_with_ungetc(file): ungetbuffer = None def ungetc(self, c): self.ungetbuffer = c def getc(self): if self.ungetbuffer is not None: c=self.ungetbuffer self.ungetbuffer = None return c else: return self.read(1) Gabriel Genellina Softlab SRL From M.Waack at gmx.de Mon Dec 29 11:38:25 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Mon, 29 Dec 2003 17:38:25 +0100 Subject: Results from os.system() different from execution at prompt References: Message-ID: <1t16c1-b37.ln1@valpo.de> Enno Middelberg wrote: > So, the Python-executed mpeg_encode reports fewer input files. Any > clues why this could happen? Is there a limit on the command length > or so? Why do you think the reason for this behaviour could be truncated command line? You just call 'mpeg_encode mpeg.par', this line shouldn't be too long neither for python nor for the shell. Mathias From rjain at nyct.net Sat Dec 20 16:16:23 2003 From: rjain at nyct.net (Rahul Jain) Date: Sat, 20 Dec 2003 16:16:23 -0500 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: <8765gbqjfc.fsf@nyct.net> Gunnar Hjalmarsson writes: > Paul McGuire wrote: >> I hope someone who knows the answer can respond, hopefully in more >> civil language. > > I'm sure that quite a few people know the answer, but most of them > have probably killfiled or decided to ignore him. > > I hope that nobody provides an answer. And it's crossposted to numerous groups that have nothing to do with perl. -- Rahul Jain rjain at nyct.net Professional Software Developer, Amateur Quantum Mechanicist From dadaista at __no_spam_please_.crs4.it Thu Dec 18 10:11:32 2003 From: dadaista at __no_spam_please_.crs4.it (Davide Carboni) Date: Thu, 18 Dec 2003 16:11:32 +0100 Subject: [Fwd: Online survey on agile practices adoption in software industry] Message-ID: -------- Original Message -------- Subject: Online survey on agile practices adoption in software industry Date: Thu, 18 Dec 2003 16:01:00 +0100 From: Davide Carboni To: undisclosed-recipients: ; Newsgroups: it.comp.java,comp.lang.java.programmer Apologies for multiple copies. _______________________________________ Hi all, AgileGroup of University of Cagliari, Sardinia, Italy, is running a survey on the adoption and use of methodologies and processes in the IT industry, with particular regard to agile practices. The survey should not take more than 10 minutes to complete. It is strictly confidential. The survey is available at: http://maps.diee.unica.it The results of the survey will be published on the same web page. If you know one or more colleague wishing to contribute her/his opinion to our study, please invite them to: http://maps.diee.unica.it Also, please fell free to forward this invitation to other professional lists and online forums. Thanks in advance for your cooperation!! Michele Marchesi DIEE - University of Cagliari Italy -- ________________________________________________________ /\ \ \_| Prof. Michele Marchesi | | DIEE - Univ. Cagliari - p.zza D'Armi - 09123 CA | |Tel:+39 070 6755757/+39 010 3532783 Fax:+39 070 6755782| | Cell.: 320 4372981 - Casa/Home: =39 010 566354 | | e-mail: michele at diee.unica.it | | XP2003 site: http://www.xp2003.org | | ____________________________________________________|__ \_/______________________________________________________/ From aleax at aleax.it Sat Dec 27 18:00:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Dec 2003 23:00:49 GMT Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: Bjorn Pettersen wrote: ... >> Here's my candidate for "most frequent scenario where copies are needed": >> >> for item in somelist: >> if froobable(item): >> somelist.append(frooble(item)) >> elif uncadable(item): >> somelist.remove(item) >> >> i.e.: you want to modify the very list you're looping on. This is one >> of Python's few but important "traps and pitfalls". > > That is an interesting version in that it iterates while either (1) > appending or (2) removing. I.e. froobable(frooble(item)) must always be > false to prevent infinite recursion. It doesn't have to _always_ be false -- some frooble(item)'s might be froobable, as long as each such chain always ends in a non-froobable. > I don't think I've seen one of these > and it made me curious, do you have a concrete example? Roughly, yes, though not quite as direct and obvious as this one. E.g.: for listener_method in this_object.registered_listeners: listener_method(this_object, change_hint) where some of the registered listener methods were trying to deregister themselves and/or register some other listener(s). This hidden case of "mutating the list being iterated on" was a rather serious bug, but it only led to infinite recursion (and hence to discovery) when a subtle combination of circumstances led to addition of unlimited number of new listeners. In a simpler variation, twisted's woven component had a list of _weak_ references to listeners giving potential for similar misbehavior (now fixed by the usual, simple approach of looping over a copy of the list). Sometimes I wonder if it might not be worth giving such "fragile" iterables as lists and dicts the ability to emit warnings when mutated, while they have iterators outstanding, in the ways that are likely to misbehave (adding or removing items to a list, or keys to a dict -- some container mutations, namely change of what value corresponds to a fixed key in a dict, are obviously benign in this sense). > My first instinct would be a "functional" approach, creating a new correct > list and abandoning the old incorrect version: > > # O(n) > tmp = [] > for item in somelist: > if shouldModify(item): > tmp.append(mutate(item)) > elif shouldRemove(item): > pass > else: > tmp.append(item) > somelist = tmp Sure, this is often a feasible approach (assuming mutate(item) returns the value one wants in lieu of item, of course). It's often particularly attractive to express it as a list comprehension: def possibly_mutated(item): if shouldModify(item): mutate(item) # no assumption it returns the value return item somelist[:] = [ possibly_mutated(item) for item in somelist if not shouldRemove(item) ] (I'm changing somelist in-place, rather than just rebinding the name, but of course depending on one's needs name rebinding can sometimes work just as well). > # O(n**2) > i = 0 > while i < len(somelist): > if shouldModify(item): this would raise a NameError about item, so I don't think this is the solution you wanted to post -- perhaps missing an item = somelist[i] ? > somelist[i] = mutate(item) > i += 1 > elif shouldRemove(item): > del somelist[i] > else: > i += 1 Yeah, the (possibly repeated) 'del' in the middle of the list has bad performance (even worse, of course, is the somelist.remove I had in the original example). Might as well keep two indices (and enumerate lets you update manually just one of them...): itarget = 0 for isrc, item in enumerate(somelist): if shouldModify(item): somelist[itarget] = mutate(item) itarget += 1 elif shouldRemove(item): pass else: somelist[itarget] = item itarget += 1 del somelist[itarget:] possibly more elegantly expressed, if the tests can be applied in different order without affecting their outcome, as: itarget = 0 for isrc, item in enumerate(somelist): if shouldRemove(item): continue if shouldModify(item): item = mutate(item) # or just mutate(item) ... somelist[itarget] = item itarget += 1 del somelist[itarget:] > I thought I found a solution using enumerate, but it was a mirage ;-) So Maybe one of the above ones...? They're both O(N), btw. > Returning to the example in the beginning, the functional version would be > > tmp = []; tail = [] > for item in somelist: > if froobable(item): > tail.append(frooble(item)) > elif uncadable(item): > pass > else: > tmp.append(item) > somelist = tmp + tail > > provided froobable(frooble(item)) is always false. If that is not the You also need to assume uncadable(frooble(item)) is also always false, otherwise the original version would remove the frooble(item) (after first adding it) and this one wouldn't. > case, it would make a functional solution messier. (but I think that would Not all that much, I think -- you just need to recurse on tail (the end case for the recursion is when tail is empty), i.e. something like: def froobanduncad(somelist): tmp = []; tail = [] for item in somelist: if froobable(item): tail.append(frooble(item)) elif uncadable(item): pass else: tmp.append(item) if tail: froobanduncad(tail) somelist[:] = tmp + tail of course, you DO need to change-in-place (or return the result) -- just rebinding the argument name would be little use;-). > be a rather perverse problem space ;-) As long as the recursion eventually terminates, not particularly, IMHO. > The case I've seen come up repeatedly is a little simple, only involving > deletions of the list: > > x = range(30) > for i in x: > if 5 <= i <= 10: # try to remove 5,6,7,8,9,10 > x.remove(i) You're luckier than I am, I think -- in the buggy cases I see, there is often some 'else:' branch to the if guarding the removal, as well as some extra action around the removal itself -- and it's not necessarily the case that the loop can be split into a list comprehension first (to weed out the items that need to be removed) and a loop later (for the actions on surviving items) because the order in which things are performed can be significant (sometimes it's quite a bother to check whether it is, or isn't, significant...). You can handle it with appending nonremoved items to an empty list (unless order of execution including possible __del__ special methods bites you...) -- but simply looping on a copy is the simplest, least-invasive modification you can perform on the subtly buggy code to make it non-buggy. > the above removes 6,8,10 instead. The solution doesn't require a copy to > iterate over though, a list comprehension will do (as will calling filter > if you want to go against the times):: > > x = [n for n in x if not 5 <= n <= 10] If removal is ALL you need, yes -- and in this case a LC or the like is also far more efficient (the .remove method is a dog...;-). > # I realize there are quite a number of Python programmers that aren't > # CS majors. Big-O notation [ O(n) and O(n**2) above ] is simply a I'm not a CS major, for example, but that doesn't imply I'm not pretty good at O()-notation anyway...;-). (Some of us engineers aren't all that bad, you know...). > # I'll make another absolute statement and say that so few > # people will work with lists big enough to ever care that it's > # irrellevant largely :-) It doesn't take much for O(N*N) to bite, in cases, such as this one, where the multiplicative constants aren't all that different from the O(N) possibilities. I.e., lists of a few hundreds items are very common in many programs. Removing half the items from a list with .remove takes about 670 usec [[on my machine, according to timeit.py]], while a LC takes 115 usec, for a list of length 200; when the list's length is 400, the time is 220 for the LC, 2100 for the .remove's. These levels of performance hits can often be quite relevant, IMHO. Alex From hwlgw at hotmail.com Wed Dec 24 06:01:22 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 24 Dec 2003 03:01:22 -0800 Subject: creating EPS with Python References: Message-ID: > [John Hunter] > PyX is a very nice python postscript generator > > http://pyx.sourceforge.net/ > Their webpage has nice examples, and it looks promising, so I downloaded it, but: python.exe setup.py install d:\python23\lib\distutils\dist.py:227: UserWarning: Unknown distribution option: 'platform' warnings.warn(msg) running install running build running build_py running build_ext error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. Bah! Maybe there is something in the .py files I can use. From raims at dot.com Thu Dec 18 03:34:33 2003 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 18 Dec 2003 09:34:33 +0100 Subject: Using python with SSH? References: <3fe0dfd7$1@clarion.carno.net.au> <8765gf82kk.fsf@mobile.foo> Message-ID: <873cbile1y.fsf@mobile.foo> Jp Calderone writes: > It does not. ssh won't accept a password from standard input, it requires > it to be entered into the terminal. Ah ok, i thought it did. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From charles at steinkuehler.net Thu Dec 18 10:52:36 2003 From: charles at steinkuehler.net (Charles Steinkuehler) Date: Thu, 18 Dec 2003 09:52:36 -0600 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: <7xhdzycfgf.fsf@ruckus.brouhaha.com> References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> <3FE1C42D.6050505@steinkuehler.net> <7xhdzycfgf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Charles Steinkuehler writes: >> Which is why I think that a small Forth kernel talking directly to the >> linux kernel is the best solution. > > Forth is such a contorted language though, it's best to avoid it > unless you're desperate. Forth as a language is not at all contorted. Programming in Forth is essentially creating a custom language to solve the problem at hand, so Forth is simply reflecting the structure (or lack thereof) of the mind of the programmer solving the problem. Forth code can be as elegent or as twisted as you desire to make it. In this regard, Forth is far more unrestricted than even C, allowing just about any form of nonsensical code. While I generally like highly structured languages with strong typechecking and other features to keep the programmer out of trouble (ada, pascal, etc), the small size and potent abilities of Forth make it highly suitable for specific problem domains, especially if there are any resource constraints to deal with. -- Charles Steinkuehler charles at steinkuehler.net From exarkun at intarweb.us Thu Dec 18 20:04:39 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 18 Dec 2003 20:04:39 -0500 Subject: Beginner question - How to effectively pass a large list In-Reply-To: <38ec68a6.0312181529.729b654@posting.google.com> References: <3fde309f$0$19285$626a54ce@news.free.fr> <38ec68a6.0312181529.729b654@posting.google.com> Message-ID: <20031219010439.GB10543@intarweb.us> On Thu, Dec 18, 2003 at 03:29:55PM -0800, Asun Friere wrote: > "J.R." wrote in message news:... > > > > 1. There is no value passed to the default argument > > The name "d" is bound to the first element of the f.func_defaults. Since the > > function "f" is an > > object, which will be kept alive as long as there is name (current is "f") > > refered to it, the > > list in the func_defaults shall be accumulated by each invoking. > > > > ... > > > > > I think we could eliminate such accumulation effect by changing the function > > as follow: > > >>> def f(d=[]): > > d = d+[0] > > print d > > > > And the reason this eliminates the accumulation is that the assignment > ('d = d + [0]') rebinds the name 'd' to the new list object ([] + > [0]), ie. it no longer points to the first value in f.func_defaults. > > What surprised me was that the facially equivalent: > >>> def f (d=[]) : > ... d += [0] > ... print d > did not do so. Apparently '+=' in regards to lists acts like > list.apppend, rather than as the assignment operator it looks like. list.extend, to be more precise, or list.__iadd__ to be completely precise :) The maybe-mutate-maybe-rebind semantics of += lead me to avoid its use in most circumstances. Jp > -- > http://mail.python.org/mailman/listinfo/python-list > From gashton at cmedltd.com Tue Dec 16 03:52:05 2003 From: gashton at cmedltd.com (Graham Ashton) Date: Tue, 16 Dec 2003 08:52:05 +0000 Subject: Package organization References: <73b00f0c.0311181638.49a5997d@posting.google.com> <73b00f0c.0311191423.3c946fdc@posting.google.com> Message-ID: On Wed, 19 Nov 2003 14:23:33 -0800, Robert Ferrell wrote: > Graham Ashton wrote in message news:... >> Also, because you're importing something from inside a module using the >> "from" style imports you're risking running into circular reference >> problems. In my experience from imports are best avoided, unless you're >> importing a module from a package. > > I don't understand this comment. How does "from" style importing > increase the risk of circular imports? Imagine you've got two modules, spam and eggs. When you import a module it's top level statements get evaluated. Imagine that spam imports something from eggs. The interpreter (whilst importing spam) pauses to import eggs. What if eggs tries to import something from spam? You might think, ah, that's a circular import. But it isn't necessarily. You see, when it starts importing spam the interpreter stores an empty module object in sys.modules and fills in the details once it's finished importing spam. Consequently when it's trying to import spam again from inside eggs it finds a module reference in sys.modules for spam and can carry on happily. Things only break on you if eggs is trying to refer to something inside spam that the original import of spam hasn't filled in yet. I'll try and give you an example. Here's the spam module: import eggs def count_spam(): return 1 And the eggs module: from spam import count_spam def count_eggs_and_spam(): return count_spam() + 1 If your main script then tries to import spam it'll blow up: % python Python 2.3.2 (#1, Dec 8 2003, 10:49:17) [GCC 3.3.2 20031022 (Gentoo Linux 3.3.2-r3, propolice)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import spam Traceback (most recent call last): File "", line 1, in ? File "spam.py", line 1, in ? import eggs File "eggs.py", line 1, in ? from spam import count_spam ImportError: cannot import name count_spam It's because the spam module in sys.modules hasn't been filled in yet, as the interpreter put off importing the contents of spam until the "import eggs" statement returned. Replace the from import with a normal import and the problem goes away. Here's a replacement eggs module: % cat eggs.py import spam def count_eggs_and_spam(): return spam.count_spam() + 1 It's no longer an issue as the spam.count_spam() function doesn't get evaluated until the count_eggs_and_spam() function is called, which is long after both the modules have been fully imported. Stay away from from, it's dangerous. And in my opinion you get less clear code. Incidentally, I learnt the nitty gritty of this from Martelli's Python in a Nutshell. Recommended. -- Graham From rbsharp at gmx.de Tue Dec 16 03:19:18 2003 From: rbsharp at gmx.de (Richard Sharp) Date: 16 Dec 2003 08:19:18 GMT Subject: SWIG problems - "ImportError: dynamic module does not define......." References: <6e4c7e29.0312152000.229a9d3a@posting.google.com> Message-ID: Hello, I am not at my home office at the moment but you will probably find the following link helpful: http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&oe=utf- 8&threadm=mailman.999029862.20314.python- list%40python.org&rnum=7&prev=/groups%3Fhl%3Dde%26ie%3DUTF-8%26oe%3Dutf- 8%26q%3Dpython%2Bdistutils%2Bexport%26sa%3DN%26tab%3Dwg The content is: Section 5.2 of the Extending and Embedding the Python Interpreter says: "The problem is that some entry points are defined by the Python runtime solely for extension modules to use. If the embedding application does not use any of these entry points, some linkers will not include those entries in the symbol table of the finished executable. Some additional options are needed to inform the linker not to remove these symbols. Determining the right options to use for any given platform can be quite difficult, but fortunately the Python configuration already has those values. To retrieve them from an installed Python interpreter, start an interactive interpreter and have a short session like this: >>> import distutils.sysconfig >>> distutils.sysconfig.get_config_var('LINKFORSHARED') '-Xlinker -export-dynamic' The contents of the string presented will be the options that should be used. If the string is empty, there's no need to add any additional options. The LINKFORSHARED definition corresponds to the variable of the same name in Python's top-level Makefile." The '-Xlinker' tells gcc to pass '-export-dynamic' to ld. gcc itself seems to ignore it otherwise. Richard Sharp c.hodapp at softhome.net (Chris Hodapp) wrote in <6e4c7e29.0312152000.229a9d3a at posting.google.com>: >I have seen messages posted about this before, and there is a clear >reference to it in the manual, but I have been unable to find a >solution. > >I'm on Slackware 9.1, kernel 2.6.0-test11, using Python 2.3.1 and >GCC 3.2.3 (both installed by default with Slackware) and SWIG 1.3.19, >compiled from source code. >I messed around a little on my own and couldn't get things to work >right, >so I copied the examples from the book, nearly verbatim but with some >minor changes to fit my configuration. > >I copied the example code exactly into example.i and example.c, and >did >the following commands: >swig -python example.i >gcc -c example.c example_wrap.c -I/usr/include/python2.3 >ld -shared example.o example_wrap.o -o _example.so >... and several other times in the last command I tried some other >things like examplemodule.so and example.so. All of these worked >without >error, so I tried it from within Python, and got the usual error about >"ImportError: dynamic module does not define init function" when I >tried >'import example'. It made no difference if I added the path with all >the >files to sys.path; the same error occurred. > >I tried this several times over, and I could never get it to work >right. The last helpful suggestion I saw on here was that I did not >make the init function public by putting >/EXPORT:init on the linker line, but that doesn't seem to be >what GNU ld understands > >Any suggestions? > >Thanks, >-Chris > From metinkaya44 at yahoo.com Sat Dec 27 23:21:41 2003 From: metinkaya44 at yahoo.com (Metin Kaya) Date: 27 Dec 2003 20:21:41 -0800 Subject: solar water heater Message-ID: <424b8cf2.0312272021.272bcd1@posting.google.com> www.kuzeysan.com From max at cNvOiSsiPoAnMtech.com Tue Dec 2 09:38:48 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Tue, 02 Dec 2003 14:38:48 GMT Subject: Can Python be run off of a CD-ROM? In-Reply-To: References: Message-ID: how about using mxCGIPython (a single-file python binary)? BJ MacNevin wrote: > Hi all, > > I teach middle school and am currently trying to bring some computer science > to the students. Our district has a wonderfully linked network throughout > all our schools... done via MS Windows Network. In order to protect the > network, our district's IT department does not want things installed on the > system (or at least makes it VERY difficult to get it done). SO, I am using > MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it > off of them. > > BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I > can do the same thing... or something similar? Is there a way to install > Python on a CD-ROM, too, if we don't need it to be accessed from a command > prompt? > > Thanks, > BJ MacNevin > From __peter__ at web.de Thu Dec 11 09:56:14 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Dec 2003 15:56:14 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Jacek Generowicz wrote: > One key feature of this is that I can use it to replace any[*] > function with a functionally equivalent but faster one, without having > to change any of the call sites of the original. Understood, but not until this post. Strictly speaking, all optimizations that fulfill the above criterium should be built into the compiler, while memoizing will not for its memory tradeoffs and dependancy of the input data. > IIUC, Aahz suggested to replace the proxy function with a > dictionary. This sounds reasonable, as, after all, the proxy maps its > arguments to its return values, while a dictionary maps keys to > values. The whole point of this is that function call overhead is > large compared to dictionary lookup, which is (almost) all that the > proxy does. However, it's the "almost" that creates the problem. If > I'm prepared to mess around with the calls to the original functions > and replace them with your suggestion, then, of course the problem is > solved ... however, I _really_ do not want to replace the calls to the > original ... See below for my ideas towards a generalized memoizing framework. I've adressed the problem by writing a map() variant that knows about result caches (essentially Aahz' innerloop() I see). You could use it to shade the builtin. > def foo(some_type): > ... > return something > > > foo = memoize(foo) > > data = [int, float, my_class, his_class, str, other_class] * 10**6 > > map(foo, data) [+] Do you discard the result for real? > [+] Can you see why I don't want to mess with the call site ? No. Now to my code. The idea is to make memoized functions available to different modules from a central registry, and to expose the cached results for hand-optimized hotspots. Otherwise it was all mentioned in this thread, if not the original post. import __builtin__ class RegistryItem: """ provide the necessary infrastructure to transparently speed up one function """ def __init__(self, func, argc): cache = self.cache = {} def memoized(*args): try: return cache[args] except KeyError: result = cache[args] = func(*args) return result assert argc > 0 if argc == 1: def callseq(seq): print seq[:3] result = [] append = result.append for arg in seq: try: append(cache[arg]) except KeyError: value = cache[arg] = func(arg) append(value) return result else: def callseq(*seqs): result = [] append = result.append if len(seqs) == 1: # multiple args as one tuple in the sequence for args in seqs[0]: try: append(cache[args]) except KeyError: value = cache[args] = func(*args) append(value) else: # multiple args in multiple sequences # XXX special case (too lazy for now) return map(memoized, *seqs) return result self.wrapped = memoized self.callseq = callseq self.original = func class Registry: """ Registry for function variants using a result cache fast = register(slow, ) """ def __init__(self): self.data = {} def __call__(self, func, argc): assert argc > 0 try: return self.data[func] except KeyError: ri = RegistryItem(func, argc) self.data[func] = ri self.data[ri.wrapped] = ri return ri.wrapped def __getitem__(self, func): return self.data[func] def getmap(self): """ provide a cache-enhanced version of map """ data = self.data def memomap(func, *seqs): try: callseq = data[func].callseq except KeyError: return __builtin__.map(func, *seqs) return callseq(*seqs) return memomap registry = register = Registry() # for improved clarity of this example I've have omitted # rebinding the original names and instead used fastXXX import memoize, time def slow(arg): print "no cache or cache miss with %r" % arg time.sleep(0.1) return "<%s>" % arg sample = range(10) * 100 # preparation code fast = memoize.register(slow, True) # typically used like so: # slow = memoize.register(slow) fastmap = memoize.registry.getmap() # could also be used like so: # map = memoize.registry[slow].getmap() # some tests assert fast is memoize.registry[fast].wrapped assert fast is memoize.registry[slow].wrapped assert slow is memoize.registry[slow].original # stray function call print slow(10) # stray function call using cache print fast(20) #built-in loop support fastmap(slow, sample) fastmap(fast, sample) # hand-crafted code using the cache cache = memoize.registry[slow].cache for arg in sample: cache[arg] Feel free to play with the above. Be warned that there will be bugs. However, before working on the code I will have to profile to make at least sure it does not slow down things... maybe this weekend. Peter From martin at v.loewis.de Wed Dec 24 04:19:48 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 24 Dec 2003 10:19:48 +0100 Subject: implementing mv In-Reply-To: References: Message-ID: Hong Jiang wrote: > Is there an efficient way to implement the 'mv' command? I mean not by > calling external commands. Try shutil.move. Regards, Martin From http Wed Dec 3 01:19:37 2003 From: http (Paul Rubin) Date: 02 Dec 2003 22:19:37 -0800 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> <7xptf639rd.fsf@ruckus.brouhaha.com> Message-ID: <7xoeuq5sp2.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > spamd is supposed to cache the network checks; perhaps it's not properly > configured. I'm running tens of thousands of messages through it one after another. It could really be that many distinct addresses. From nospam at nowhere.com Tue Dec 9 19:28:58 2003 From: nospam at nowhere.com (Courageous) Date: Wed, 10 Dec 2003 00:28:58 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> <80804$3fd60ee5$436596f5$26728@msgid.meganewsservers.com> Message-ID: >> It's not. The .net virtual machine is Turing Complete. > >The subject here is imprecise. The issue is that .net performs very poorly with >dynamic languages. Yes, I agree. While it would be *possible* to implement most anything on .net, any language that isn't a close friend, thematically, to C#, really isn't at home there. The underlying framework is really a virtual machine designed to implement C#'s features. Moreover, and more to the point, any other programming language which does not use these primitives as intended (e.g., uses dynamic composition to achieve inheritance instead of the framework's primary primitives to achieve same) will be a second bastard child in the environment, with glaring warts that will be obvious the moment interoperation is attempted. Since the *main appeal* of .net is language interop, ... Well, perhaps that answers the OP's question. C// From jacek.generowicz at cern.ch Wed Dec 10 11:26:49 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 17:26:49 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > Generally speaking, map() won't be any faster than a for loop. This is at odds with my own experience (including a lot of timing runs in the last two days), countless posts on this newsgroup over the years, and, for exapmle, this article http://www.python.org/doc/essays/list2str.html by Guido, in which he concludes that "An implied loop in map() is faster than an explicit for loop" From wtrenker at hotmail.com Sun Dec 21 10:58:59 2003 From: wtrenker at hotmail.com (William Trenker) Date: Sun, 21 Dec 2003 15:58:59 +0000 Subject: memory overhead using from-import? In-Reply-To: References: <20031221102848.4f901801.wtrenker@shaw.ca> Message-ID: <20031221155859.22b6f141.wtrenker@hotmail.com> Bengt Richter wrote: > (which might be returned to python free pools rather than the system) Ah. So using the "ps" command (on Linux) to inspect the process's virtual memory size may not show me if memory for dereferenced objects is being freed for re-use within python's execution environment? I snooped around on google, and read the profiler docs to try and find a python tool for measuring memory usage. I haven't found anything, yet. (Of course, the profiler focuses on execution times.) Is there an api for inspecting python memory usage? For example, is there a way to determine the memory freed by deleting an imported module, even if the freed memory is internal to python and can't be "seen" as a change to the total process memory allocated by the operating system? Thanks, Bill From eddie at holyrood.ed.ac.uk Wed Dec 3 10:40:26 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 3 Dec 2003 15:40:26 +0000 (UTC) Subject: Can Python be run off of a CD-ROM? References: <7Zlzb.290907$ao4.1008621@attbi_s51> Message-ID: "BJ MacNevin" writes: >Cool idea, Arthur! >I tried to download KNOPPIX last night, and to no avial. The knoppix servers >are currently restricted from allowing downloadings. DOH! I tried to find an >available mirror someplace, but had no luck. If you are interested in going this route (and you ought to be) it might be worth checking out Morphix (http://morphix.sourceforge.net/) which allows you to create your own Knoppix distributions. Basically adding your own requirements to the base distribution (or removing things you don't want your students to have). Eddie From jeder at earthlink.net Sat Dec 6 13:19:59 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Sat, 06 Dec 2003 18:19:59 GMT Subject: Moving around in a string References: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> <5PSdndqm1duFeEyiRVn-sw@sysmatrix.net> Message-ID: On Sat, 06 Dec 2003 08:18:00 -0600, Mark Engle wrote: > Peter Otten wrote: > >> Mark Engle wrote: >> > http://www.python.org/doc/current/lib/module-string.html >> > >> >> One caveat (only for the string module), quoting from the above >> document, but easily overlooked: >> >> "Many of the functions provided by this module are also defined as >> methods of string and Unicode objects; see ``String Methods'' >> (section 2.2.6) for more information on those." >> >> So whenever you're tempted to write string.somefunc(s, moreargs), >> rather use s.somefunc(moreargs). >> >> Peter > > Thank you. Time to do some more reading. > > Mark Heya Mark, Thanks for the split function. It did the trick of splitting up the words to the appropriate white space. words_within = sentence.split() When printed, it lists all the words separated by white space. I'll be back after some more research however ;) ~Ryan From fumanchu at amor.org Sun Dec 7 00:14:27 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 6 Dec 2003 21:14:27 -0800 Subject: list.sorted() Message-ID: > >reverse is not true: you can't call normal instance methods from the > >class--you get a TypeError by not passing an instance for > "self" to bind > to. > > Yes you can: explicitly pass an instance as first arg for > 'self' to bind to > ;-) > (or did I misunderstand your claim?) Understood. The claim was more about the automagic passing of "self" (vs "cls" in classmethod). FuManChu From alejandro at cableonda.net Tue Dec 30 00:52:07 2003 From: alejandro at cableonda.net (Alejandro Lombardo) Date: Tue, 30 Dec 2003 00:52:07 -0500 Subject: Programming language from python Message-ID: <000001c3ce99$0efa7900$0300a8c0@Alex> Dear sirs: I need to create a programming language. Can this be done with the latest version of python? Is python the best computer programming language development tool in the entire universe? If it isn?t could you please tell me the name of the best computer programming language development tool in the entire universe? So that I can download it from the Internet for free? I would apreciate it if you could answer these questions as soon as posible. Sincerely, Prophet -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeder at earthlink.net Sat Dec 6 03:41:24 2003 From: jeder at earthlink.net (Ryan Spencer) Date: Sat, 06 Dec 2003 08:41:24 GMT Subject: Moving around in a string Message-ID: Hello All, Once again I'm back a with a question, ha ha. Well, I've gotten to an exercises where it wants me to write a translation program that takes input from the user and translates it into either pig Latin or something called "ubby dubby". It describes the basic rules and all, and I somewhat understand in my mind on how to go about doing it, but... It requires me to, for the pig Latin part, remove the first letter and move it to the end of a string (and then add ay to the end.) How should I go about "moving" to the end of the string? Just for clarification I want to do something like... Please enter a word: Orange rangeOay (taking the O and bringing it to end and then adding 'ay' to the end) Thanks as always, ~Ryan From jepler at unpythonic.net Tue Dec 30 11:38:55 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Dec 2003 10:38:55 -0600 Subject: Is Python Mac Centric??? In-Reply-To: References: Message-ID: <20031230163855.GN6171@unpythonic.net> Apple decided they wanted to include Python in 10.3, and the Python community was thrilled. There are also a couple of people who are working very hard on Mac-specific modules for Python. I don't know why they're included in the core while pythonwin is not--is it just historical coincidence? A license difficulty? Change in attitudes? However, I don't view the pythonwin download as a big hassle. Python could probably be included in the next version of Windows if Bill Gates decided he wanted to. But I don't think he's called Guido up yet. Jeff From mwh at python.net Tue Dec 2 13:13:21 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Dec 2003 18:13:21 GMT Subject: Fast attribute/list item extraction References: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > Excuses, rationalizations. I don't wan't to incite a contest, but > IMO "key=" is misleading ;-) Well, I don't, and I seem to be winning at the moment :-) Cheers, mwh -- I believe C++ instills fear in programmers, fear that the interaction of some details causes unpredictable results. -- Erik Naggum, comp.lang.lisp From sebastien.giraud at eds.com Wed Dec 17 08:41:35 2003 From: sebastien.giraud at eds.com (Giraud, Sebastien) Date: Wed, 17 Dec 2003 13:41:35 -0000 Subject: Threads for a newbe Message-ID: First thx for Your answer :) So here are my two codes : The first which doesn't work - And the second which works (at last :) ) I cant say why the first one doesn't work... In fact you'll see that it's my first time in Python AND in object programming as well... There are lot's of error (like using variable instead of using parameters) but I'll rewrite the source when I'll have understood thread's, socket and object better... Maybe should I have started with an easier project... ;) Exceptions, protocol and high lvl user function are still missing. But i just try to make a socket-server works at first. If you have any advise or idea I'll be glad to read it :) -----Message d'origine----- De : python-list-bounces+sebastien.giraud=eds.com at python.org [mailto:python-list-bounces+sebastien.giraud=eds.com at python.org] De la part de Diez B. Roggisch Envoy? : mercredi 17 d?cembre 2003 13:33 ? : python-list at python.org Objet : Re: Threads for a newbe Hi, > i can... I'm a python newbe and have the following problem : I try to > create 2 threads in a server program and they seems to block each other. > I use something like this : > start thread waiting for connexion with : server.threadserver = > threading.Thread(target = self.__startserver) then do while 1 : > socket, host = accept(...) > then start a new thread for each new connexion after accept using > client.threadclient = threading.Thread(target = self.__receive) > and while 1 : > client.receive() > And here the first thread seems not to work anymore :( . I didn't join > threads. Maybe a lock() problem but i don't now how to use the lock() > function in Python... Maybe if someone had a multithread server sample > source I could understand what is the issue... I recently did implement a socket-server using threads. So if you give me more actual code, I might be able to help you. However, I stepped away from that approach and went for twisted - a really excellent networing framework, which eliminated the need for different threads. You should really look into that, as just having different threads sitting on blocking io-descriptors is abusing them (while I have to admit - its tempting...) Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: Server0.0.1.py Type: application/octet-stream Size: 3098 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Server0.0.2.py Type: application/octet-stream Size: 3003 bytes Desc: not available URL: From __peter__ at web.de Tue Dec 30 16:35:39 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Dec 2003 22:35:39 +0100 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > I have this dict that maps a name to a sequence of other names. > I want to have it reversed, i.e., map the other names each to > the key they belong to (yes, the other names are unique and > they only occur once). Like this: [...] > What I'm doing is using a nested loop: > > dict2={} > for (key,value) in dict1.items(): > for name in value: > dict2[name] = key > > which is simple enough, but I'm hearing this little voice in > the back of my head saying "there's a simpler solution". > Is there? What is it? ;-) Here's what I've come up with: import itertools original = {"key1": ("value1", "value2"), "key2": ("value3",)} def forInv(original): result = {} for (key, values) in original.iteritems(): for val in values: result[val] = key return result def updateInv(original): result = {} for (key, values) in original.iteritems(): result.update(dict.fromkeys(values, key)) return result def iterInv(original): result = {} for (key, values) in original.iteritems(): result.update(dict(itertools.izip(values, itertools.repeat(key)))) return result def iterInv2(original): return dict(itertools.chain(*[itertools.izip(values, itertools.repeat(key)) for key, values in original.iteritems()])) def compInv(original): return dict([(val, key) for (key, values) in original.iteritems() for val in values]) wanted = { "value1": "key1", "value2": "key1", "value3": "key2" } for inv in globals().values(): if callable(inv): print inv.__name__, if inv(original) == wanted: print "OK" else: print "FAILED" Conclusion: my favourite toys, itertools and list comprehensions, lead to clumsier code - well, me at least. So I would recommend that you don't listen to that voice. Peter From llothar at web.de Thu Dec 25 18:51:02 2003 From: llothar at web.de (Lothar Scholz) Date: 25 Dec 2003 15:51:02 -0800 Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: <6ee58e07.0312251551.13175989@posting.google.com> "python newbie" wrote in message news:<%thGb.1817$vz5.1144 at newssvr27.news.prodigy.com>... > I need the ability to debug, so I think I'm learning toward buying Komodo, > however this would only be for straight Python. When I start building a > wxPython interface to my current program, will this work? > > Does anyone currently develop in wxPython and if so, are you using a > dependable tool for debugging in this? Test all the mentioned IDE's if they work with WxPython. Not everyone is doing this. And it should work with threads. So Wing-IDE is not the best choise. From claird at lairds.com Wed Dec 10 14:39:32 2003 From: claird at lairds.com (Cameron Laird) Date: Wed, 10 Dec 2003 19:39:32 -0000 Subject: Python & Expect References: <3FD7263E.110F9CC4@engcorp.com> Message-ID: In article , Jeff Wagner wrote: >On Wed, 10 Dec 2003 08:57:18 -0500, Peter Hansen wrotf: > >>Jeff Wagner wrote: >>> >>> Is there an Expect-like module for Python that is cross platform and, >for the most part, does what >>> Expect does? A number of years ago, I wrote some Tcl scripts using >Expect for automation. I am >>> trying to convince my good friend who I worked with at the time to >try Python. He said, "what about >>> Expect?" >>> >>> I have heard of a Pexpect but was told that it didn't run on win32 >and he needs win32 and Linux >>> support both. . . . >>Pexpect does not currently work on the standard Windows Python(see the >pty requirement); >>however, it seems to work fine using Cygwin. ... . . . >Ok, I did look at it and mentioned in my post that Pexpect doesn't run >on win32. The question was, >is there a Expect-like module that does run on win32. I couldn't find one. > >Jeff Yes and no. I could write a book on that one question--in fact, I've given serious thought to the possibility. The basic answer is, no, but there are at least a half-dozen qualifications to that. The answer to, "What about Expect?" is this: it's a wonderful application, with all sorts of virtues--but it is NOT effec- tively available for Windows. So, in deciding between Python and Tcl, if the requirement is for a current Expect-like thing, Tcl has no particular advantage over Python, 'cause they both depend, at least for now, on POSIXy ptys. I think Expect and Tcl quite valuable; I use 'em all the time. HOWEVER, along with understanding the lack of portability of the pty abstraction to Windows, the second crucial fact you deserve to know is that Expect is far less necessary for most people than it used to be, or than they persist in thinking it is now. You can automate telnet, FTP, SMTP, and much else, without recourse to Expect. As is so often the case, the best advice I know is to take a little time and think over your true requirements again. -- Cameron Laird Business: http://www.Phaseit.net From edreamleo at charter.net Thu Dec 11 13:47:55 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 11 Dec 2003 12:47:55 -0600 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: > > My experience is that Tkinter is the "least bad" and more flexible. > > wxPython (of course) inherits all the _many_ bugs in wxWindows. > > It's not clear that wxWindows really actually works. > > Isn't that last sentence a bit overly FUD-ish? Umm. Maybe you are right. My main point, and I think it is important, is that wxWindows seems significantly flakier than Tk. Much more than Tk, the wxWindows experience is "design once, debug everywhere". Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bjorn.pettersen at comcast.net Fri Dec 26 05:28:42 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Fri, 26 Dec 2003 04:28:42 -0600 Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: Arthur wrote in news:27umuvkmnbnk6qsdgbh7em35ekga1od1jv at 4ax.com: > On Thu, 25 Dec 2003 05:17:47 -0600, Bjorn Pettersen > wrote: > > >> There is a module called copy that let you get the semantics that >> you're looking for. I've never used it in my 6+ years of Python >> programming, since it normally indicates the presence of flawed logic >> . > > Why would you mention this in the context here? Because it's true more times than not. People who believe they need a copy, usually comes from C++ where they've written copy constructors (ctors) as a matter of course to have their classes work with the std lib. > I remain confused by this oft repeated mantra regrading the use of > copy. Are you saying that the need to copy a list indicates flawed > logic, or that doing it otherwise than by list[:] is flawed? Creating an exact copy by any means normally indicates to me that something is more complex than it needs to be. In object oriented terms, the concept of a copy doesn't really make sense. It's easier to see on a more concrete object, e.g. let me create an object representing my best friend: kira = Dog(breed='Akita', age=4, color='tri-colored') what would a copy.copy(kira) be? Where would I use the copy without being able to use the original object? The reason copy ctors are so frequent in C++ is simply because the language does not have garbage collection. There just isn't a convenient way of creating an object which outlives function scope yet doesn't leak memory. There are of course times where a copy is needed (e.g. multi-version scenarios) but most programmers don't bump into these very frequently... -- bjorn From usenet at soraia.com Mon Dec 8 15:26:57 2003 From: usenet at soraia.com (Joe Francia) Date: Mon, 08 Dec 2003 20:26:57 GMT Subject: Explorer Shell extensions are here! In-Reply-To: <8a27e309.0312081137.18c2810b@posting.google.com> References: <8a27e309.0312081137.18c2810b@posting.google.com> Message-ID: R.Marquez wrote: > I just happened to bump into this today when I went to the Win32 > Python Extensions page. I think the M.H. and his team are a bit too > modest. > > Quote: > "win32com.shell grows many more interfaces, allowing Python to operate > as a nearly complete shell extension, and to interact with the shell > interfaces. See the win32comext\shell\demos\server directory for > examples." > > This is something I had been waiting for a while, and even submited a > "feature request" about it. So, since I hadn't heard any thing about > it, I figure there may be a few more like me that would enjoy knowing > about this. I _do_ enjoy knowing about this ;>) Thanks for the tip. > (Now, if I could only figure out how to make a context menu that would > show up for any file of folder... ;) In the demo "context_menu.py", replace the register and unregister bits with the code below. Run context_menu.py with either the --register or --unregister switch, as appropiate. def DllRegisterServer(): import _winreg folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Folder\\shellex") folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers") folder_subkey2 = _winreg.CreateKey(folder_subkey, "PythonSample") _winreg.SetValueEx(folder_subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) file_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "*\\shellex") file_subkey = _winreg.CreateKey(file_key, "ContextMenuHandlers") file_subkey2 = _winreg.CreateKey(file_subkey, "PythonSample") _winreg.SetValueEx(file_subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_) print ShellExtension._reg_desc_, "registration complete." def DllUnregisterServer(): import _winreg try: folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "Folder\\shellex\\ContextMenuHandlers\\PythonSample") file_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT, "*\\shellex\\ContextMenuHandlers\\PythonSample") except WindowsError, details: import errno if details.errno != errno.ENOENT: raise print ShellExtension._reg_desc_, "unregistration complete." Peace, Joe From FBatista at uniFON.com.ar Mon Dec 29 12:10:31 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 29 Dec 2003 14:10:31 -0300 Subject: prePEP "Decimal data type" v0.2 Message-ID: Here is the second version of the prePEP for the Decimal data type. Sorry for the delay, but I restructured it to new (thanks list), and changing to a new house and deploying GSM in Argentina are not very time-freeing tasks, :p Anyway, I'll appreciate any suggestion. Thank you! . Facundo ------------------------------------------------------------ PEP: 9999 Title: Decimal data type Version: $Revision: 0.2 $ Last-Modified: $Date: 2003/12/29 13:35:00 $ Author: Facundo Batista Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 17-Oct-2003 Python-Version: 2.3.4 Abstract ======== The idea is to have a Decimal data type, for every use where decimals are needed but binary floating point is too inexact. The Decimal data type will support the Python standard functions and operations, and must comply the decimal arithmetic ANSI standard X3.274-1996. Decimal will be floating point (as opposite of fixed point) and will have bounded precision (the precision is the upper limit on the quantity of significant digits in a result). This work is based on code and test functions written by Eric Price, Aahz and Tim Peters. Actually I'll work on the Decimal.py code in the sandbox (at python/nondist/sandbox/decimal in SourceForge). Lot of the explanations of this PEP are taken from the Cowlishaw's work and comp.lang.python. Motivation ========== Here I'll expose the reasons of why I think a Decimal data type is needed and why others numeric data types are not enough. I wanted a Money data type, and after proposing a prePEP in comp.lang.python, the comunity agreed to have a numeric data type with the needed arithmetic behaviour, and then build Money over it: all the considerations about quantity of digits after the decimal point, rounding, etc., will be handled through Money. It is not the purpose of this PEP to have a data type that can be used as Money without further effort. One of the biggest advantages of implementing a standard is that someone already thought all the creepy cases for you. And to a standard GvR redirected me: the Decimal specification is the Mike Cowlishaw's work at http://www2.hursley.ibm.com/decimal/. This document defines a general purpose decimal arithmetic. A correct implementation of this specification will conform to the decimal arithmetic defined in ANSI/IEEE standard 854-1987, 5 except for some minor restrictions, and will also provide unrounded decimal arithmetic and integer arithmetic as proper subsets. The problem with binary float ----------------------------- In decimal math, there are many numbers that can't be represented with a fixed number of decimal digits, e.g. 1/3 = 0.3333333333....... In base 2 (the way that standard floating point is calculated), 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. 0.2 equals 2/10 equals 1/5, resulting in the binary fractional number 0.001100110011001... As you can see, the problem is that some decimal numbers can't be represented exactly in binary, resulting in small roundoff errors. So we need a decimal data type that represents exactly decimal numbers. Instead of a binary data type, we need a decimal one. Why floating point? ------------------- So we go to decimal, but why *floating point*? Floating point numbers use a fixed quantity of digits (precision) to represent a number, working with an exponent when the number gets too big or too small. For example, with a precision of 5:: 1234 ==> 1234e0 12345 ==> 12345e0 123456 ==> 12345e1 In opposite of this, we have the example of a ``long`` number, which precision is infinite, meaning that you can have the number as big as you want, and you'll never lose anything. So, why can't we have an infinite precision decimal? It's no so easy, because of the not exact divisions. Ej: 1/3 = 0.3333333333333... ad infinitum. In this case you should store a infinite amount of 3s, which takes too much memory, ;). John Roth proposed to eliminate the division operator and force the user to use an explicit method, just to avoid this kind of trouble. This generated adverse reactions in comp.lang.python, as everybody wants to have the ``"/"`` support in a numeric data type. With this exposed maybe you're thinking "Hey! Can we just store the 1 and the 3 as numerator and denominator?", which take us to the next point. Why not rationale ----------------- Rationale numbers are stored using two integers numbers, the numerator and the denominator. This implies that the arithmetic operations can't be executed directly (e.g. to add two rationale numbers you first need to calculate the common denominator). Quoting Alex Martelli: "The performance implications of the fact that summing two rationals (which take O(M) and O(N) space respectively) gives a rational which takes O(M+N) memory space is just too troublesome. There are excellent Rational implementations in both pure Python and as extensions (e.g., gmpy), but they'll always be a "niche market" IMHO. Probably worth PEPping, not worth doing without Decimal -- which is the right way to represent sums of money, a truly major use case in the real world." Anyway, if you're interested in this data type, you maybe will want to take a look at PEP 239: Adding a Rational Type to Python. So, what we got? ---------------- The result is a Decimal data type, with bounded precision and floating point. Will it be useful? I won't say it better than Alex Martelli: "Python (out of the box) doesn't let you have binary floating point numbers *with whatever precision you specify*: you're limited to what your hardware supplies. Decimal, be it used as a fixed or floating point number, should suffer from no such limitation: whatever bounded precision you may specify on number creation (your memory permitting) should work just as well. Most of the expense of programming simplicity can be hidden from application programs and placed in a suitable decimal arithmetic type. As per http://www2.hursley.ibm.com/decimal/ , *a single data type can be used for integer, fixed-point, and floating-point decimal arithmetic* -- and for money arithmetic which doesn't drive the application programmer crazy." There're several uses for such a data type. As I said before, I will use it as base for Money. In this case the bounded precision is not an issue; quoting Tim Peters: "A precision of 20 would be way more than enough to account for total world economic output, down to the penny, since the beginning of time." General Decimal Arithmetic Specification ======================================== Here I'll include information and descriptions that are part of the specification (the structure of the number, the context, etc.). All the requeriments included in this section are not for discussion, as they are in the standard, and the PEP is for just implementing the standard. Anyway, if you think that something here should change, just propose it (maybe I misplaced the item), but you've been warned, ;) This is a very trimmed version of the original document: for a more specific verba, check it at http://www2.hursley.ibm.com/decimal/. The Arithmetic Model -------------------- The specification is based on a model of decimal arithmetic which is a formalization of the decimal system of numeration (Algorism) as further defined and constrained by the relevant standards (IEEE 854, ANSI X3-274, and the proposed revision of IEEE 754). There are three components to the model: - Numbers: which represent the values that can be manipulated by, or be the results of, the core operations defined in the specification. - Operations: the core operations (such as addition, multiplication, etc.) which can be carried out on numbers. - Context: which represents the user-selectable parameters and rules that govern the results of arithmetic operations (for example, the precision to be used). Numbers ------- Numbers may be finite numbers (numbers whose value can be represented exactly) or they may be special values (infinities and other values which are not finite numbers). Finite numbers are defined by three integer parameters: - Sign: a value which must be either 0 or 1, where 1 indicates that the number is negative or is the negative zero and 0 indicates that the number is zero or positive. - Coefficient: an integer which is zero or positive. - Exponent: a signed integer which indicates the power of ten by which the coefficient is multiplied. The numerical value of a finite number is given by:: (-1)**sign * coefficient * 10**exponent Numbers must also be able to represent one of three named special values: - Infinity: a value representing a number whose magnitude is infinitely large. - Quiet NaN: a value representing undefined results (*Not a Number*) which does not cause an Invalid operation condition. - Signaling NaN: a value representing undefined results (*Not a Number*) which will cause an Invalid operation condition if used in any operation defined in the specification. All special values may have a sign, as for finite numbers. The sign of an infinity is significant and the sign of a NaN has no meaning. Context ------- The context represents the user-selectable parameters and rules which govern the results of arithmetic operations (for example, the precision to be used). The context gets that name because surrounds the Decimal numbers. It's up to the implementation to work with one or several contexts, but definitely the idea is not to get a context per Decimal number. These definitions doesn't affect the internal storage of the Decimal numbers, just the way that the arithmetic operations are performed. The context is defined by the following parameters: - Precision: An integer which must be greater than 0. This sets the maximum number of significant digits that can result from an arithmetic operation. - Rounding: A named value which indicates the algorithm to be used when rounding is necessary. Rounding is applied when a result coefficient has more significant digits than the value of precision; in this case the result coefficient is shortened to precision digits and may then be incremented by one (which may require a further shortening), depending on the rounding algorithm selected and the remaining digits of the original coefficient. The exponent is adjusted to compensate for any shortening. - Flags and trap-enablers: The exceptional conditions are grouped into signals, which can be controlled individually. The context contains a flag and a trap-enabler (both are either 0 or 1) for each signal. For each of the signals, the corresponding flag is set to 1 when the signal occurs. It is only reset to 0 by explicit user action. For each of the signals, the corresponding trap-enabler indicates which action is to be taken when the signal occurs. If 0, a defined result is supplied, and execution continues. If 1, the execution of the operation is ended or paused and control passes to a "trap handler", which will have access to the defined result. The signals are: clamped, division-by-zero, inexact, invalid-operation, overflow, rounded, subnormal and underflow. Default Contexts ---------------- The specification defines two default contexts, which define suitable settings for basic arithmetic and for the extended arithmetic defined by IEEE 854. It is recommended that the default contexts be easily selectable by the user. In the basic default context, the parameters are set as follows: - flags: all set to 0 - trap-enablers: inexact, rounded, and subnormal are set to 0; all others are set to 1 - precision: is set to 9 - rounding: is set to round-half-up In the extended default context, the parameters are set as follows: - flags: all set to 0 - trap-enablers: all set to 0 - precision: is set to the designated single precision - rounding: is set to round-half-even Exceptional Conditions ---------------------- This section lists, in the abstract, the exceptional conditions that may arise during the operations defined in the specification. For each condition, the corresponding signal in the context is given, along with the defined result: - Clamped: This occurs and signals ``clamped`` if the exponent of a result has been altered in order to fit the constraints of a specific concrete representation. - Conversion syntax: This occurs and signals ``invalid-operation`` if an string is being converted to a number and it does not conform to the numeric string syntax. The result is [0,qNaN]. - Division by zero: This occurs and signals ``division-by-zero`` if division of a non-zero finite number by zero was attempted. The result of the operation is [sign,inf], where sign is the *exclusive or* of the signs of the operands for divide. - Division impossible: This occurs and signals ``invalid-operation`` if the integer result of a divide-integer or remainder operation had too many digits. The result is [0,qNaN]. - Division undefined: This occurs and signals ``invalid-operation`` if division by zero was attempted, and the dividend is also zero. The result is [0,qNaN]. - Inexact: This occurs and signals ``inexact`` whenever the result of an operation is not exact (that is, it needed to be rounded and any discarded digits were non-zero), or if an overflow or underflow condition occurs. The result in all cases is unchanged. - Insufficient storage: For many implementations, storage is needed for calculations and intermediate results, and on occasion an arithmetic operation may fail due to lack of storage. The result is [0,qNaN]. - Invalid context: This occurs and signals ``invalid-operation`` if an invalid context was detected during an operation. The result is [0,qNaN]. - Invalid operation: This occurs and signals ``invalid-operation`` in a variety of cases (an operand to an operation is a signaling NaN, an attempt is made to add [0,inf] to [1,inf] or to multiply 0 by [0,inf] or [1,inf], etc.). The result of the operation after any of the invalid operations is [0,qNaN] except when the cause is a signaling NaN, in which case the result is [s,qNaN] or [s,qNaN,d] where the sign and diagnostic are copied from the signaling NaN. - Overflow: This occurs and signals ``overflow`` if the adjusted exponent of a result, after rounding, would be greater than the largest value that can be handled. The result depends on the rounding mode: largest finite number, [0,inf] or [1,inf]). In all cases, Inexact and Rounded will also be raised. - Rounded: This occurs and signals ``rounded`` whenever the result of an operation is rounded (that is, some zero or non-zero digits were discarded from the coefficient), or if an overflow or underflow condition occurs. The result in all cases is unchanged. - Subnormal: This occurs and signals ``subnormal`` whenever the result of a conversion or operation is subnormal (that is, its adjusted exponent is less than the smallest value that can be handled, before any rounding). The result in all cases is unchanged. - Underflow: This occurs and signals ``underflow`` if a result is both inexact and sub-normal. Different kinds Of Rounding --------------------------- ``round-down``: The discarded digits are ignored; the result is unchanged (round toward 0, truncate):: 1.123 --> 1.12 1.128 --> 1.12 1.125 --> 1.12 1.135 --> 1.13 ``round-half-up``: If the discarded digits represent greater than or equal to half (0.5) then the result should be incremented by 1; otherwise the discarded digits are ignored:: 1.123 --> 1.12 1.128 --> 1.13 1.125 --> 1.13 1.135 --> 1.14 ``round-half-even``: If the discarded digits represent greater than half (0.5) then the result coefficient is incremented by 1; if they represent less than half, then the result is not adjusted; otherwise the result is unaltered if its rightmost digit is even, or incremented by 1 if its rightmost digit is odd (to make an even digit):: 1.123 --> 1.12 1.128 --> 1.13 1.125 --> 1.12 1.135 --> 1.14 ``round-ceiling``: If all of the discarded digits are zero or if the sign is negative the result is unchanged; otherwise, the result is incremented by 1:: 1.123 --> 1.13 1.128 --> 1.13 -1.123 --> -1.12 -1.128 --> -1.12 ``round-floor``: If all of the discarded digits are zero or if the sign is positive the result is unchanged; otherwise, the absolute value of the result is incremented by 1:: 1.123 --> 1.12 1.128 --> 1.12 -1.123 --> -1.13 -1.128 --> -1.13 ``round-half-down``: If the discarded digits represent greater than half (0.5) then the result is incremented by 1; otherwise the discarded digits are ignored:: 1.123 --> 1.12 1.128 --> 1.13 1.125 --> 1.12 1.135 --> 1.13 ``round-up``: If all of the discarded digits are zero the result is unchanged, otherwise the result is incremented by 1 (round away from 0):: 1.123 --> 1.13 1.128 --> 1.13 1.125 --> 1.13 1.135 --> 1.14 Rationale ========= I must separate the requeriments in two sections. The first is to comply with the ANSI standard. All the needings for this are specified in the Mike Cowlishaw's work. He also provided a **comprehensive** suite of test cases. The second section of requeriments (standard Python functions support, usability, etc) is detailed from here, where I'll include all the decisions made and why, and all the subjects still being discussed. Explicit construction --------------------- The explicit construction does not get affected by the context (there is no rounding, no limits by the precision, etc.), because the context affects just operations' results. **From int or long**: There's no loss and no need to specify any other information:: Decimal(35) Decimal(-124) **From string**: Strings with floats in normal and engineering notation will be supported. In this transformation there is no loss of information, as the string is directly converted to Decimal (there is not an intermediate conversion through float):: Decimal("-12") Decimal("23.2e-7") **From float**: The initial discussion on this item was what should happen when passing floating point to the constructor: 1. ``Decimal(1.1) == Decimal('1.1')`` 2. ``Decimal(1.1) == Decimal('110000000000000008881784197001252...e-51')`` 3. an exception is raised Several peopel allegued that (1) is the better option here, because it's what you expect when writing ``Decimal(1.1)``. And quoting John Roth, it's easy to implement: "It's not at all difficult to find where the actual number ends and where the fuzz begins. You can do it visually, and the algorithms to do it are quite well known". But If I *really* want my number to be ``Decimal('110000000000000008881784197001252...e-51')``, why can not write ``Decimal(1.1)``? Why should I expect Decimal to be "rounding" it? Remember that ``1.1`` *is* binary floating point, so I can predict the result. It's not intuitive to a begginer, but that's the way it is. Anyway, Paul Moore shown that (1) can't be, because:: (1) says D(1.1) == D('1.1') but 1.1 == 1.1000000000000001 so D(1.1) == D(1.1000000000000001) together: D(1.1000000000000001) == D('1.1') which is wrong, because if I write ``Decimal('1.1')`` it is exact, not ``D(1.1000000000000001)``. He also proposed to have an explicit conversion to float. bokr says you need to put the precision in the constructor and mwilson has the idea to:: d = Decimal (1.1, 1) # take float value to 1 decimal place d = Decimal (1.1) # gets `places` from pre-set context But Alex Martelli says that "Constructing with some specified precision would be fine. Thus, I think *construction from float with some default precision* runs a substantial risk of tricking naive users." So, I think that the best solution is to have a parameter that says in which position after the decimal point you apply a round-half-up rounding. If you do not specify this parameter, you get an exact conversion. In this way:: Decimal(1.1, 2) == Decimal('1.1') Decimal(1.1, 16) == Decimal('1.1000000000000001') Decimal(1.1) == Decimal('110000000000000008881784197001252...e-51') **From tuples**: Aahz suggested to construc from tuples: it's easier to implement ``eval()``'s round trip and "someone who has numeric values representing a Decimal does not need to convert them to a string." The structure will be a tuple of three elements: sign, number and exponent. The sign is 1 or 0, the number is a tuple of decimal digits and the exponent is a signed int or long:: Decimal((1, (3, 2, 2, 5), -2)) # for -32.25 **From Decimal**: No mistery here, just a copy. **Syntax to all the cases**:: Decimal(value, [decimal_digits]) where ``value`` can be any of the data types just mentioned and ``decimal_digits`` is allowed only when value is float. Implicit construction --------------------- As the implicit construction is the consequence of an operation, it will be affected by the context as is detailed in each point. John Roth suggested that "The other type should be handled in the same way the decimal() constructor would handle it". But Alex Martelli thinks that "this total breach with Python tradition would be a terrible mistake. 23+"43" is NOT handled in the same way as 23+int("45"), and a VERY good thing that is too. It's a completely different thing for a user to EXPLICITLY indicate they want construction (conversion) and to just happen to sum two objects one of which by mistake could be a string." So, here I define the behaviour again for each data type. **From int or long**: Aahz suggested the need of an explicit conversion from int, but also thinks it's ok if the precision in the current Context is not exceeded; in that case you raise ValueError. Votes in comp.lang.python agreed with this. **From string**: Everybody agrees to raise an exception here. **From float**: Aahz is strongly opposed to interact with float: "The problem is that Decimal is capable of greater precision, accuracy, and range than float", suggesting an explicit conversion. But in Python it's ok to do ``35 + 1.1``, so why can't I do ``Decimal(35) + 1.1``? We agree that when a naive user writes ``1.1`` doesn't know that he's being inexact, but that happens in the both examples I just mentioned. So, what should we do? I propose to allow the interaction with float, making an exact conversion and raising ValueError if exceeds the precision in the current context (this is maybe too tricky, because for example with a precision of 9, ``Decimal(35) + 1.2`` is ok but ``Decimal(35) + 1.1`` raises an error). **From Decimal**: There isn't any issue here. Use of Context -------------- In the last prePEP I said that "The Context must be omnipresent, meaning that changes to it affects all the current and future Decimal instances". I was wrong. In response, John Roth said that "The context should be selectable for the particular usage. That is, it should be possible to have several different contexts in play at one time in an application." In comp.lang.python, Aahz explained that the idea is to have a "context per thread". So, all the instances of a thread belongs to a context, and you can change a context in thread A (and the behaviour of the instances of that thread) without changing nothing in thread B. Also, and again correcting me, he said that the "Context applies only to operations, not to Decimal instances; changing the Context does not affect existing instances if there are no operations on them". Arguing about special cases when there's need to perform operations with other rules that those of the current context, Tim Peters said that the context will have the operations as methods. This way, the user "can create whatever private context object(s) it needs, and spell arithmetic as explicit method calls on its private context object(s), so that the default thread context object is neither consulted nor modified". Python Usability ---------------- - Decimal should support the basic aritmetic (``+, -, *, /, //, **, %, divmod``) and comparison (``==, !=, <, >, <=, >=, cmp``) operators in the following cases (check `Implicit Construction`_ to see what types could OtherType be, and what happens in each case): - Decimal op Decimal - Decimal op otherType - otherType op Decimal - Decimal op= Decimal - Decimal op= otherType - Decimal should support unary operators (``-, +, abs``). - Decimal should support the built-in methods: - min, max - float, int, long - str, repr - hash - copy, deepcopy - bool (0 is false, otherwise true) - Calling repr() should do round trip, meaning that:: m = Decimal(...) m == eval(repr(m)) - Decimal should be immutable. Reference Implementation ======================== To be included later: - code - test code - documentation Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsbenson at bensonsystems.com Tue Dec 2 18:58:42 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 2 Dec 2003 15:58:42 -0800 Subject: Tkinter question: how to the red "Tk" window title bar icon? Message-ID: <00bb01c3b930$36e26000$8f0a500a@jsbwxp3> Hi, I'm using Tkinter and would like to know how to replace the red "Tk" logo in the left corner of the title bar of the root window with some other icon. Another question for curiosity's sake: I've often seen Tkinter referred to as the "standard" Python GUI. I assume that this is because it may be the oldest and perhaps the most cross-platform. Is that all that can be said for it? I've already heard about the Tkinter interpretive overhead, but given the amazing increase in CPU speeds recently, I wave my paw and just say "Bah!" (something I learned from Dogbert). Any other comments? Thanks in advance for any aid and comfort. From peter at engcorp.com Fri Dec 12 09:47:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Dec 2003 09:47:05 -0500 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> Message-ID: <3FD9D4E9.FE199F61@engcorp.com> "John J. Lee" wrote: > > If you want to stay sane, use this: > > http://wwwsearch.sourceforge.net/ClientCookie > > just say: > > ClientCookie.urlopen(req) > > and forget about cookies. As the author, John might seem biased, but I'll weigh in with my own praise for the product. His comment "if you want to stay sane" is really on-the-mark here... Cookies _are_ insane, but ClientCookie at least provides them a nice padded room in which to reside... Thanks, John! :-) -Peter From aahz at pythoncraft.com Fri Dec 5 22:04:33 2003 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2003 22:04:33 -0500 Subject: Adding method to object References: Message-ID: In article , Thomas Guettler wrote: > >How can I add a method to an object. >This code does not work: > >class Foo: > def __init__(self): > self.counter=0 > >f=Foo() > >def incr(self): > self.counter+=1 > >f.incr=incr >f.incr() Try ``Foo.incr=incr`` -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From tjreedy at udel.edu Wed Dec 10 09:41:52 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2003 09:41:52 -0500 Subject: how do i get a "wide build" precompiled python w support unicodehigher than 'ffff' References: Message-ID: "Posadas, Dennis" wrote in message news:mailman.16.1071039432.9307.python-list at python.org... >I don't want to have to compile python, > but I need one ready to support unicode that includes CJK. I cannot do this, but following info might get you better info or offers: What system? What usage? Research? Commerce? Are you willing to pay? TJR From donn at drizzle.com Thu Dec 25 00:20:55 2003 From: donn at drizzle.com (Donn Cave) Date: Thu, 25 Dec 2003 05:20:55 -0000 Subject: file opening and closing References: Message-ID: <1072329653.682617@yasure> Quoth anton muhin : | hokieghal99 wrote: |> jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF') |> |> Should this file be closed after reading? If so, how would one close it? |> What's the downside to not closing it? | | It would, then the file object gets destroyed (it method __del__ is | called). However, as Python uses garbage collection, it can happen much | later after you leave the function. | | There is mostly no downsides except for the cases when you try to read | this file---it might not be flashed. (Flushed, that is, and of course that wouldn't be a problem here since the file is only to be read.) Note that the exact behavior here depends on the implementation: Java Python may as you say defer the close indefinitely, but C Python will execute it immediately on function return, because its garbage collection is based on reference count. The above usage is fine in C Python. In Java Python, it's probably OK but potential problems would include file descriptor resource starvation if opening many files this way, and low disk space if reading large files this way and then deleting them, because the open file descriptor will preserve the actual file even though its directory entry is gone. Donn Cave, donn at drizzle.com From jjl at pobox.com Mon Dec 1 12:14:53 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Dec 2003 17:14:53 +0000 Subject: comparing nan "number" References: Message-ID: <87vfp01muq.fsf@pobox.com> Bo?tjan Jerko writes: > I need to know if the result of math formula is nan (Not a number). > How can I do that? I suppose: NAN = any_calculation_that_returns_nan() if some_other_calculation() is NAN: ... John From fredrik at pythonware.com Sun Dec 14 05:31:48 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Dec 2003 11:31:48 +0100 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: Message-ID: "google12" wrote: > May anyone help me? > > I need a lib which support .jpeg file with RGBA mode. PIL seems to support > RGB and CMYK mode only... last time I checked, JPEG didn't support RGBA. From bjorn.pettersen at comcast.net Sat Dec 27 13:04:52 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Sat, 27 Dec 2003 12:04:52 -0600 Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: Alex Martelli wrote in news:QuWGb.9617$_P.378641 @news4.tin.it: > Bjorn Pettersen wrote: > ... >> There are of course times where a copy is needed (e.g. multi-version >> scenarios) but most programmers don't bump into these very frequently... > > Here's my candidate for "most frequent scenario where copies are needed": > > for item in somelist: > if froobable(item): > somelist.append(frooble(item)) > elif uncadable(item): > somelist.remove(item) > > i.e.: you want to modify the very list you're looping on. This is one > of Python's few but important "traps and pitfalls". That is an interesting version in that it iterates while either (1) appending or (2) removing. I.e. froobable(frooble(item)) must always be false to prevent infinite recursion. I don't think I've seen one of these and it made me curious, do you have a concrete example? The more frequently encountered algorithm is one the iterates while either (1) mutating or (2) removing items [and a gazzilion variations you can find in any Scheme/ML/Lisp/etc. introduction (current pet-peeve: aren't there interesting things you could do in an introduction to those languages?)]. First the version using a copy, pretty straight forward, but only able to deal with lists of mutable objects (see last solution below): # O(n**2) for item in somelist[:]: # or copy.copy(somelist) or list(somelist) if shouldModify(item): mutate(item) # assuming item is mutable in the Python sense elif shouldRemove(item): somelist.remove(item) else: pass My first instinct would be a "functional" approach, creating a new correct list and abandoning the old incorrect version: # O(n) tmp = [] for item in somelist: if shouldModify(item): tmp.append(mutate(item)) elif shouldRemove(item): pass else: tmp.append(item) somelist = tmp ; it doesn't look quite so forced in [pseudo-]lisp [I didn't ; count the parens or actually run it -- I'm sure there are ; enough lispers here to correct it ]. (defun frooble (lst) (cond ((shouldModify (car lst)) (cons (mutate (car lst)) (frooble (cdr lst))) ((shouldRemove (car lst)) (frooble (cdr lst))) (t (cons (car lst) (frooble (cdr lst)))))) if I was programming in C++ or especially C, a pure imperative approach would probably bubble to the top (assuming the list could have variable size without leaking memory). The fact that I wrote a bug in this code originally, without noticing, would (at least for me) be filed in the "don't destroy what you're iterating over" category. Alternatively, it would indicate that you are using the wrong datastructure, i.e. an array, instead of some sort of linked list. # O(n**2) i = 0 while i < len(somelist): if shouldModify(item): somelist[i] = mutate(item) i += 1 elif shouldRemove(item): del somelist[i] else: i += 1 I thought I found a solution using enumerate, but it was a mirage ;-) So far the functional solution still seems like a winner, it's both faster (yeah, I know, see below), and easy to verify for correctness visually (in fact, it's set up for an inductive proof, if that exites anyone ;-) Returning to the example in the beginning, the functional version would be tmp = []; tail = [] for item in somelist: if froobable(item): tail.append(frooble(item)) elif uncadable(item): pass else: tmp.append(item) somelist = tmp + tail provided froobable(frooble(item)) is always false. If that is not the case, it would make a functional solution messier. (but I think that would be a rather perverse problem space ;-) The case I've seen come up repeatedly is a little simple, only involving deletions of the list: x = range(30) for i in x: if 5 <= i <= 10: # try to remove 5,6,7,8,9,10 x.remove(i) the above removes 6,8,10 instead. The solution doesn't require a copy to iterate over though, a list comprehension will do (as will calling filter if you want to go against the times):: x = [n for n in x if not 5 <= n <= 10] -- bjorn (*) # I realize there are quite a number of Python programmers that aren't # CS majors. Big-O notation [ O(n) and O(n**2) above ] is simply a # measure of how bad the worst case scenario of a function would be # (most frequently) measured in operations, and for the cases above # I'll make another absolute statement and say that so few # people will work with lists big enough to ever care that it's # irrellevant largely :-) The quatratic complexity comes from deleting an item in the middle of the list, since this causes all items above the empty spot to be shifted down. Shifting all elements down is O(n), and you could end up doing it for every element, O(n) work for each of the O(n) elements gives O(n** 2) From aaron at reportlab.com Wed Dec 10 14:26:11 2003 From: aaron at reportlab.com (Aaron Watters) Date: 10 Dec 2003 11:26:11 -0800 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: <9a6d7d9d.0312101126.6b526167@posting.google.com> Istvan Albert wrote in message news:... > Aaron Watters wrote: > > General Technical Notes: > > The xsdb package is implemented in Python, and the server mode requires > > stackless python. > > Why? > IMHO this sort of limitations severely reduce any > project's potential. > Istvan. Because it's the Right Way (tm) to do it :). First let me emphasize that only the server layer uses stackless at present. I'm using stackless because (aside from the fact that it was simplest way implement the functionality) database concurrency control requires the following: If a young transaction tries to read something written by an old transaction which has not yet committed it must wait until the old transaction decides to commit or abort. In order to allow transactions to wait the options are: 1) Use an event loop and write the application "inside out", much like a fortran 4 program attempting to emulate recursion. 2) Use operating system threads (which have very high overhead and sometimes don't really work the same across different platforms...) 3) Use stackless. 4) punt: automatically abort any transaction which needs to wait. As a first approach I went for (3) because it was easy. I don't plan to do (1) because I treasure my sanity. I intend to implement both (2) and (4) as server options before I call xsdb a "beta", but I want to also keep the stackless version alive. I'm still wishing that real stackless functionality will make it into standard Python, but I also don't really understand the deep implications. -- Aaron Watters === I don't know if you've been loving somebody I only know it isn't mine. -- Elvis Costello "Alison" From timh at zute.net Mon Dec 8 10:30:11 2003 From: timh at zute.net (Tim Hoffman) Date: Mon, 08 Dec 2003 23:30:11 +0800 Subject: ANN: pythonfs - create linux filesystems in python In-Reply-To: References: Message-ID: <3fd49841@news.highway1.com.au> You could access ZODB as a filesystem ;-) Rene Pijlman wrote: > David McNab: > >>a framework which allows mountable linux filesystems to be >>implemented in pure python. > > > Serious question: why? > From wtrenker at shaw.ca Sun Dec 21 09:24:07 2003 From: wtrenker at shaw.ca (William Trenker) Date: Sun, 21 Dec 2003 14:24:07 +0000 Subject: How do I really delete an imported module? Message-ID: <20031221142407.3044616b.wtrenker@shaw.ca> I've been googling around trying to figure out how to delete an imported module and free up the memory it was using. One point of confusion, for me, is that if I "del" a module the virtual memory used by the process doesn't decrease. Using Python 2.3.2 on Linux, here is a simple test program that prints out the virtual memory size and the relative contents of the sys.modules dict at various points: import sys,os,pprint,sets def vmem(text): print '%s: VmSize=%skB'%(text,os.popen('ps h o vsize %s'%os.getpid()).read().strip()) def mods(): pprint.pprint(sets.Set(sys.modules.keys()) - baseModules) baseModules = sets.Set(sys.modules.keys()) vmem('begin') import re vmem('after import re') mods() del re vmem('after del re') mods() Here is the output: begin: VmSize=3348kB after import re: VmSize=3408kB Set(['strop', 'sre', '_sre', 'sre_constants', 're', 'sre_compile', 'sre_parse', 'string']) after del re: VmSize=3408kB Set(['strop', 'sre', '_sre', 'sre_constants', 're', 'sre_compile', 'sre_parse', 'string']) The sys.modules items related to the "re" library module are still showing up after "del re". And the virtual memory for the process has not been reduced. What is the pythonic way to completely delete a module and get it's memory garbage collected? Thanks, Bill From exarkun at intarweb.us Mon Dec 22 09:29:16 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 22 Dec 2003 09:29:16 -0500 Subject: Thread and tkMessageBox (Synchonimous) In-Reply-To: <104c369a.0312220334.7ee4583f@posting.google.com> References: <104c369a.0312220334.7ee4583f@posting.google.com> Message-ID: <20031222142916.GB21664@intarweb.us> On Mon, Dec 22, 2003 at 03:34:10AM -0800, Askari wrote: > I think that my problem is in the syncho between main thread and my > thread created with (with thread.start_new_thread(...) ). But, I don't > understand the method for syncho with a thread... > > I want pop a message to user with > tkMessageBox.showinfo("Title","Message") but when this command is in > my thread, it's don't work (and my main thread give no reponse > (crash)). > > How I can pop a message (or question) with a thread? > All Tkinter calls must be made in the main thread. Perhaps you can solve this problem by making the showinfo call in the main thread and running your own code in another thread, or perhaps you can solve it by displaying GUI widgets using non-blocking APIs, thus obviating the need for threads at all. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From hans at zephyrfalcon.org Sat Dec 20 10:58:24 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 20 Dec 2003 10:58:24 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: Ville Vainio wrote: > Most importantly, why would anyone even care? Ability to optionally > invoke a "call" operation on an object implicitly seems utterly > worthless to me. It has the feel of perl philosophy (regexps in > language syntaxm anyone? ), and it's not the only instance in Ruby. I > don't really like the Perl philosophy (like most of the people who > "get" Python), and I don't really believe a language whose designers > appreciate the perlisms poses a serious threat to Python. Not even if > they got some things right. Hmm, I looked at Ruby a few months ago, and while it has more similarities to Python than differences, its design philosophies are indeed very different. As such, it seems less "clean" to me than Python (but anyone's MMV, of course). In some places it seems too "pure", in other places it adds a lot of extra syntax for special cases. It's just different from Python, but I expect that many people don't care much about that. The rise of Ruby may not be a good thing for Python, but I think that in the long run, it's good for scripting/dynamic languages as a whole. Python gets another competitor, which wouldn't be possible if dynamic (agile?) languages were not a viable choice. Enough people are interested in dynamic languages that there's room for another one. So, in a way, it's a sign that people who use one of these languages (be it Python, Perl, Ruby) are on the right track. As for switching... I like Ruby's code blocks (although not necessarily the way they are used), and maybe a few other small things, but I haven't seen anything that would make me seriously consider switching. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From klapotec at chello.at Fri Dec 12 13:52:54 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 12 Dec 2003 18:52:54 GMT Subject: java.awt.Robot equivalent? References: <4qw66tu0.fsf@python.net> Message-ID: <093ktvs2nv2lnf5o4q9arj5t2ghnof481e@4ax.com> On Fri, 12 Dec 2003 14:36:55 +0100, Thomas Heller wrote: >"Fredrik Lundh" writes: > >> Christopher Koppler wrote: >> >>> Is this capability available in any of the GUI toolkits (searching >>> Tkinter docs brought up nothing)? Is there a C library that I could >>> wrap? Or maybe I just need to use the Windows extensions. But if so, >>> how - I don't have the slightest idea how that would work. >>> >>> Anyone have any pointers? >> >> win32api's PostMessage might be useful. random google link: >> >> http://mail.python.org/pipermail/python-win32/2002-December/000635.html > >Other random resources: > >Simon Brunning has written a 3-part details blog entry on >'automating the win32 gui'. > >And there's a library named 'autoit' which can be driven by com. > Thank you very many, Fredrik, Thomas! Autoit does exactly what I need (click on a specific coordinate in a canvas-like window), and finally a reason to learn to use ctypes, too... -- Christopher From tzot at sil-tec.gr Mon Dec 8 21:45:39 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 09 Dec 2003 04:45:39 +0200 Subject: [OT] Hilarious output from whois Message-ID: (European readers mainly) whois is a very useful tool for desperate postmasters fighting spam at the originating ip level... and just a few moments ago I ran a whois query against the radb whois server for a wannabe spammer coming from 202.156.211.73 . I found a detail in the whois output hilarious --reminded me of Lucky Luke comix by Goscinny and Morris. See if you can spot the connection to the comix (hint at the end :) [whois.radb.net] route: 202.156.208.0/20 descr: StarHub Cable Vision Ltd 2D Ayer Rajah Crescent AOS Building Singapore 139938 Tel: +65-65862903 origin: AS10091 remarks: For any abuse matter, pls report to abuse at starhub.com notify: bienoc at starhub.com notify: serene at starhub.com mnt-by: MAINT-AS10091 changed: serene at starhub.com 20030120 source: RADB route: 202.156.0.0/16 descr: StarHUB internet Tempolaly registry admin-c: Yukimasa Ito tech-c: Takanori Mizuguchi origin: AS4657 notify: ops at ntt.net mnt-by: MAINT-AS7515 changed: yasuta at ntt.net 20020816 source: ARCSTAR route: 202.156.192.0/19 descr: Global Hostnet (additions) origin: AS13589 mnt-by: MAINT-AS13589 changed: bsg at panamsat.com 20011026 source: EPOCH Hint: what exactly is the role of StarHUB internet? :) I bet that this is on purpose, and that is why I send it to the group... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From theller at python.net Fri Dec 12 13:14:50 2003 From: theller at python.net (Thomas Heller) Date: Fri, 12 Dec 2003 19:14:50 +0100 Subject: win32 socket, "Operation not supported" References: Message-ID: <7k116gyt.fsf@python.net> David Konerding writes: > Hello, > > I have written an app which opens a TCP connection to a server and > uses a protocol to communicate with it. Specifically, I've written a > python IMD client for the molecular dynamics application 'NAMD' (do > searches for IMD and NAMD if you want to learn more). > > The protocol is very simple: both ends of the TCP connection can send > messages to the other side at any time; when data is available on a > read socket, a full packet (with known size) is read in a blocking > fashion from the socket. > > This is used, on the client side, to make requests of the molecular > dynamics engine (such as "speed up", or "slow down", or "quit"). The > server side periodically sends updates on the state of the molecular > dynamics engine (current step, atomic coords, etc). > > This all works fine on linux: I can connect, and send and receive > messages as necessary. > > However, on Windows, I can connect and complete the initial handshake, > and receive periodic updates, but when I try to send a message to the > server, socket.send gets an "Operation not supported". > > From my reading of the win32 docs, the socket send call returns this > in a couple of situations: when a two-way socket had one half shut > down and the send would have used the shut down direction, or when an > out of band message was sent on a socket type which does not support > it (such as UDP). > > Neither of these situations are true. When I re-code the app in C, > the problem doesn't occur. Anybody got some suggestions? (PS: the > socket I/O is set to blocking, and the Nagle algorithm is disabled). I have no idea, and if it works in C it should also work in Python ;-). OTOH, the approach you take sounds a little strange - if you communicate with fixed size packets wouldn't UDP datagrams fit better? This would IIUC also remove the requirement to disable the nagle algo. Thomas From t_therkelsen at hotmail.com Sun Dec 14 13:06:45 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 14 Dec 2003 18:06:45 GMT Subject: urllib2 http authorization question References: Message-ID: In article , Matthew Wilson wrote: [snip] >>>> lookup.mr814('username', 'password') > Traceback (most recent call last): > File "", line 1, in ? > File "lookup.py", line 13, in mr814 > for line in urllib2.urlopen(req): > File "/usr/lib/python2.3/urllib2.py", line 136, in urlopen > return _opener.open(url, data) > File "/usr/lib/python2.3/urllib2.py", line 333, in open > '_open', req) > File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain > result = func(*args) > File "/usr/lib/python2.3/urllib2.py", line 849, in http_open > return self.do_open(httplib.HTTP, req) > File "/usr/lib/python2.3/urllib2.py", line 843, in do_open > return self.parent.error('http', req, fp, code, msg, hdrs) > File "/usr/lib/python2.3/urllib2.py", line 359, in error > return self._call_chain(*args) > File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain > result = func(*args) > File "/usr/lib/python2.3/urllib2.py", line 419, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > urllib2.HTTPError: HTTP Error 401: Unauthorized >>>> lookup.mr814('admin', '54wins') > '66.72.200.255' To me, but maybe this is a copy-n-paste error, it looks like you aren't calling lookup.mr814() with exactly the same args: >>> lookup.mr814('username', 'password') versus >>> lookup.mr814('admin', '54wins') ? > > This is baffling me. Does the webserver ignore the AUTHORIZATION header > on the first request? Should I do something like this: > >>>> try: > ... lookup.mr814('admin', '54wins') > ... except urllib2.HTTPError: #I only want to catch 401 here, but how? > ... print "I got back the 401 error. Trying again..." > ... lookup.mr814('admin', '54wins') > ... except: > ... print "something else went wrong." > > If that is recommended, how do I distinguish between 401 errors, vs > other errors? I don't know if it's recommended, but take a look at the source for the urllib2.HTTPError class, at the definition of __str__ (which is used by the traceback system): def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) In other words, the actual HTTP error code is in self.code... you could check for that something like this: try: lookup.mr814('admin', '54wins') except urllib2.HTTPError, err: if err.code != 401: raise > > Thanks for the help. I hope the above helps, /Troels Therkelsen From money at mario-kaess.de Wed Dec 3 05:46:30 2003 From: money at mario-kaess.de (Mario Kaess) Date: Wed, 3 Dec 2003 11:46:30 +0100 Subject: *** MAKE MONEY ONLINE TODAY - IT'S REALLY EASY !!!! *** Message-ID: *** MAKE MONEY ONLINE TODAY - IT'S REALLY EASY !!!! *** HTTP://MONEY.MARIO-KAESS.DE *** MAKE MONEY ONLINE TODAY - IT'S REALLY EASY !!!! *** From torsten.rueger at hiit.fi Thu Dec 18 03:24:30 2003 From: torsten.rueger at hiit.fi (Torsten Rueger) Date: Thu, 18 Dec 2003 10:24:30 +0200 Subject: udp broadcast example, please In-Reply-To: <20031217152749.GA4432@intarweb.us> Message-ID: <99C41BAC-3133-11D8-BB2B-000A959C1BB0@hiit.fi> On Wednesday, Dec 17, 2003, at 17:27 Europe/Helsinki, Jp Calderone wrote: > > No threads, but maybe it's good enough anyway: Thanks for trying to help. But really this is very incomplete, missing all read or write calls to the socket. And I've tried, with just that SO_BROADCAST option I do not receive the stuff I send, and in fact with just that option, I can't even send. But thanks for the pointer to twisted. Torsten > import sys > from socket import SOL_SOCKET, SO_BROADCAST > > from twisted.internet import reactor > from twisted.internet import protocol > from twisted.internet import task > from twisted.python import log > > log.startLogging(sys.stdout) > > port = 7154 > > class BroadcastingDatagramProtocol(protocol.DatagramProtocol): > > port = port > > def startProtocol(self): > self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, > True) > self.call = task.LoopingCall(self.tick) > self.dcall = self.call.start(1.0) > > def stopProtocol(self): > self.call.stop() > > def tick(self): > self.transport.write(self.getPacket(), ("", > self.port)) > > def getPacket(self): > return "Some bytes for you" > > def datagramReceived(self, data, addr): > print "Received", repr(data) > > reactor.listenUDP(port, BroadcastingDatagramProtocol()) > reactor.run() > > Jp > > -- > http://mail.python.org/mailman/listinfo/python-list From not at all.com Sat Dec 27 14:21:38 2003 From: not at all.com (G.I.L) Date: Sat, 27 Dec 2003 21:21:38 +0200 Subject: ProtoCiv: porting Freeciv to Python References: <3fec66f1$0$967$a1866201@newsreader.visi.com> Message-ID: <3feddb73$1@news.012.net.il> Nathan Mates wrote: > In article , > Brandon J. Van Every wrote: >> But this discussion would only (properly) be about the >> appropriateness of various languages for prototyping Game Designs. >> I say Python is appropriate, and C isn't. > > Prototyping != implementing. Well, duh! g From pascal.parent at free.fr Wed Dec 3 10:06:10 2003 From: pascal.parent at free.fr (Pascal) Date: 3 Dec 2003 07:06:10 -0800 Subject: Extract double in binary file References: Message-ID: Thanks a lot! From ben at adversary.org Sat Dec 20 16:58:04 2003 From: ben at adversary.org (Ben McGinnes) Date: Sun, 21 Dec 2003 08:58:04 +1100 Subject: semi-OT: DNS issues for python.org (re-send) In-Reply-To: <16355.44904.529915.592465@montanaro.dyndns.org>; from skip@pobox.com on Fri, Dec 19, 2003 at 08:09:44PM -0600 References: <16355.44904.529915.592465@montanaro.dyndns.org> Message-ID: <20031221085804.T749@devious.adversary.org> Skip Montanaro(skip at pobox.com)@Fri, Dec 19, 2003 at 08:09:44PM -0600: > > The python.org domain is in transition between CNRI and the PSF. I > imagine things will settle down in the next day or so. Ah, thanks for the explanation. I half-suspected a re-delegation, but it was difficult to tell without being able to resolve the web site to check any announcements about that. As it happened I was out for a few hours after posting the first time and it appeared to be resolved by the early evening here (+1100 GMT/UTC). So just in time for the latest release too. Regards, Ben -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 181 bytes Desc: not available URL: From fw58959 at hotmail.com Thu Dec 4 01:12:00 2003 From: fw58959 at hotmail.com (CK) Date: 3 Dec 2003 22:12:00 -0800 Subject: thread vs threading -- Unexpected Results Message-ID: I am a "newbie" to python and today I had the need to write a program which generated a lot of tcp connections to a range of addresses (10.34.32.0/22) in order to troubleshoot a problem with a switch. I also wanted to get familiar with threads under python and so I thought I could do both at the same time. I wrote two programs - one using thread and one using threading but the results between the two were unexpected and quite different. I was hoping that someone could shed some light on why there is such a difference. Program A - thread example #!/usr/local/bin/python import socket import time import thread def tcp_connect(dst_ip,dst_port): print "%s Connecting to %s on port %d" % (time.asctime(),dst_ip,dst_port) s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((dst_ip,dst_port)) except: pass s.close() print "%s Disconnecting from %s on port %d" % (time.asctime(),dst_ip,dst_port) for x in range(0,2): for octet3 in range(32,36): for octet4 in range(0,256): ip_addr = "10.34."+str(octet3)+"."+str(octet4) thread.start_new_thread(tcp_connect,(ip_addr,135)) produces the following output pus-bin[49]% ./tcp_connector.py Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.0 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.5 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.10 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.15 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.20 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.25 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.24 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.23 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.22 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.21 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.19 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.18 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.17 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.16 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.14 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.13 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.12 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.11 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.9 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.8 on port 135 Wed Dec 3 21:36:01 2003 Connecting to 10.34.32.7 on port 135 ...etc... At most I see only 2 Disconnecting prints. I would have expected to see Disconnect prints intermingled in the output. In fact I don't see any Disconnecting prints (other than the two). Why is this? And now for something completely different....:-) Program B - threading example #!/usr/local/bin/python import socket import time import threading class connector(threading.Thread): def __init__(self,dst_ip,dst_port): self.dst_ip = dst_ip self.dst_port = dst_port threading.Thread.__init__(self) def run(self): print "%s Connecting to %s on port %d" % (time.asctime(),self.dst_ip,self.dst_port) self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: self.s.connect((dst_ip,dst_port)) except: pass self.s.close() print "%s Disconnecting from %s on port %d" % (time.asctime(),self.dst_ip,self.dst_port) threadlist = [] for x in range(0,4): for octet3 in range(32,36): for octet4 in range(0,256): ip_addr = "10.34."+str(octet3)+"."+str(octet4) thread = connector(ip_addr,135) thread.start() threadlist.append(thread) for thread in threadlist: thread.join() print "Main thread exitting" which produces the following output... Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.0 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.0 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.1 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.1 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.2 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.2 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.3 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.3 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.4 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.4 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.5 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.5 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.6 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.6 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.7 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.7 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.8 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.8 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.9 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.9 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.10 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.10 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.11 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.11 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.12 on port 135 Wed Dec 3 21:56:42 2003 Disconnecting from 10.34.32.12 on port 135 Wed Dec 3 21:56:42 2003 Connecting to 10.34.32.13 on port 135 .... etc ... Now in the threading example I have Connect / Disconnect pairs for the whole cycle. I would have expected multiple Connects here and there and multiple Disconnects appearing here and there but it looks like at most only two threads are ever active (main + one). Why don't I see multiple Connects / Disconnects?? Thanks. ./CK From yan at NsOeSiPnAeMr.com Wed Dec 31 10:55:12 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Wed, 31 Dec 2003 10:55:12 -0500 Subject: dropping priveledges Message-ID: Any way to get a python script to run with a specified user priveledges? I have a script that has to run as a specific user. Thanks, -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From yan at NsOeSiPnAeMr.com Sat Dec 6 06:53:41 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 06 Dec 2003 06:53:41 -0500 Subject: newbie list question Message-ID: I have two lists, fav and oldfav. Each has the same number of elements. Each is a list of lists: fav: [['dcp_0229.jpg', 'dcp_0230.jpg', 'dcp_0231.jpg', 'dcp_0235.jpg', 'dcp_0237.jpg', 'dcp_0238.jpg', 'dcp_0240.jpg', 'dcp_0243.jpg'], ['dcp_0244.jpg', 'dcp_0252.jpg', 'dcp_0257.jpg', 'dcp_0275.jpg', 'dcp_0276.jpg', 'dcp_0280.jpg', 'dcp_0283.jpg', 'dcp_0284.jpg'], ['dcp_0287.jpg', 'dcp_0293.jpg', 'dcp_0294.jpg', 'dcp_0303.jpg', 'dcp_0308.jpg', 'dcp_0314.jpg', 'dcp_0319.jpg', 'dcp_0331.jpg'], ['dcp_0336.jpg', 'dcp_0346.jpg', 'dcp_0347.jpg', 'dcp_0349.jpg', 'dcp_0350.jpg', 'dcp_0353.jpg', 'dcp_0355.jpg', 'dcp_0360.jpg']] oldfav: [['dcp_0278.jpg', 'dcp_0348.jpg', 'dcp_0349.jpg', 'dcp_0275.jpg', 'dcp_0347.jpg', 'dcp_0318.jpg', 'dcp_0280.jpg', 'dcp_0315.jpg', 'dcp_0240.jpg'], [], [], []] I want to remove those elements that are in the sub-lists of fav that also appear in the corresponding sub-list of oldfav: for the 1st sub-list of fav difffav[0:1] = Set(fav[0:1]) - Set(oldfav[0:1]) for the 2nd sub-list of fav difffav[1:2] = Set(fav[1:2]) - Set(oldfav[1:2]) and so on. The number of sub-lists in fav and oldfav may change, but they will always be the same. I can hack this up using C-style indexes, but I have to imagine there is some neat python way that eliminates indexes altogether. -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From http Sat Dec 27 21:11:31 2003 From: http (Paul Rubin) Date: 27 Dec 2003 18:11:31 -0800 Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: <7xbrpt6698.fsf@ruckus.brouhaha.com> Andrew MacIntyre writes: > > list(x) is my favourite way to make a shallow copy of list x, but x[:] > > and copy.copy(x) are essentially equivalent. > > Behaviourally yes, performance wise no. Eh? Last time I looked at the copy module, x[:] is exactly what it did. From hokiegal99 at hotmail.com Tue Dec 16 22:12:34 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 16 Dec 2003 19:12:34 -0800 Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: <93f5c5e9.0312161912.3f5c5bc4@posting.google.com> William Park wrote in message news:... > Heike C. Zimmerer wrote: > > William Park writes: > > > > > hokiegal99 wrote: > > >> import os, string > > >> setpath = raw_input("Enter the path: ") #This can be hard coded. > > >> for root, dirs, files in os.walk(setpath, topdown=False): > > >> for fname in files: > > >> s = string.find(fname, '.mp3') > > >> if s >=1: > > >> fpath = os.path.join(root,fname) > > >> os.remove(fpath) > > >> print "Removed", fpath, "\n" > > > > > > FYI, in shell, you would go > > > find . -type f -name '*.mp3' | xargs rm > > > > Which will fail if the file name contains any spaces or other special > > characters (not too unusual for .mp3 - Files). > > In which case, you look up 'man find xargs' and edit the command to > find ... -print0 | xargs -0 ... What would you man on a Windows box??? Not everyone has a unix shell, and not everyone wants/needs one. None of our users use Linux/Unix. They all use Windows XP or Mac OS X. So, you shouldn't assume that I'm running Linux or some other type of Unix. I do as an admin/developer, but that's not the point. The above python script will run on Windows, Linux, OS X, etc. and it makes for much easier reading. This is a python forum. So, you're off-topic. From jjl at pobox.com Wed Dec 3 13:14:48 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Dec 2003 18:14:48 +0000 Subject: SGMLParser eats ä etc References: <87he0mn0c7.fsf@pobox.com> <19cbe1rfd2rx$.dlg@amez.homeip.net> Message-ID: <87u14hlqef.fsf@pobox.com> ddubin writes: > Anders Eriksson writes: [...] > disappears. The question is what replacement text has been put in its > place, and why can't you see it? He can't see it because it's not there. From sgmllib.py: # To be overridden -- handlers for unknown objects def unknown_starttag(self, tag, attrs): pass def unknown_endtag(self, tag): pass def unknown_charref(self, ref): pass def unknown_entityref(self, ref): pass John From theller at python.net Thu Dec 11 03:34:57 2003 From: theller at python.net (Thomas Heller) Date: Thu, 11 Dec 2003 09:34:57 +0100 Subject: [Windows] Installation/Upgrade question References: <3fNBb.1864$Zq2.1463894@news2.news.adelphia.net> Message-ID: Robert writes: > When Python comes out with a bug fix version (2.3.2->2.3.3 being the > next) can the setup just run and overwrite the previous installation > or is an uninstall/reinstall what needs to happen? It is recommended to uninstall the previous (minor) version first, at least that's the only way that is tested. You don't need to remove/reinstall any extensions you have. Thomas From jzgoda at gazeta.usun.pl Fri Dec 19 15:31:49 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Dec 2003 20:31:49 +0000 (UTC) Subject: Spell checking and Python References: Message-ID: William Trenker pisze: > Might want to apply the following patch to __init__.py so that the > dictionary files are located relative to the installation directory. > When I first tried running myspell-python (Linux Python 2.3.2) I got a > traceback -- the dictionary path was wrong compared with where > setup.py actually installed the dictionaries. > > After the fix, myspell-python worked very well. The list of suggested > spellings for a given word is quite good. Of course, all pathes, fixes and suggestions are welcome. I hope that this piece of code finally find it's safe harbor at Savannah or SF. I think that other people also find it worth using. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From birdiepageANTI at SPAMciudad.FILTERcom.ar Fri Dec 5 17:00:41 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Fri, 05 Dec 2003 19:00:41 -0300 Subject: Newbie question: Any way to improve this code? Message-ID: I'm begining to work in a program that cicles through a list of phrases (basically, a changing signature file). I started yesterday, and I only have abput 8 full hours of real Python experience. So far I produced a code that succesfully reads an process the file, separating the phrases. Is there any way to optimize this code, so that I don't have to use the if for the first list member? Now for the data. The file is firmas.txt, it contains the following three example phrases Frase 1 Frase 2 Frase 3 Note that this phrases are separated by newline characters. Upon reading the full file (it won't be long) I get this: 'Frase 1\nFrase 2\nFrase 3\n' so, as you can see, the newlines are there. My code is this (I know I should close the file, but so far the runtime is so small it doesn't really matter, that'll change) import string f = open("firmas.txt",'r') # open the file texto = f.read () n = range (len (texto)) frases = [0] frase ="" cant = 0 for a in n: if texto [a] != "\n": frase = frase + (texto [a]) else: if cant == 0: frases [0] = frase else: frases.append (1) frases [cant] = frase cant +=1 frase = "" Well, that's it, thanks. Gustavo Campanelli From no at spam.invalid Fri Dec 26 18:39:13 2003 From: no at spam.invalid (Russell E. Owen) Date: Fri, 26 Dec 2003 15:39:13 -0800 Subject: Tkinter: is event_generate safe from background thread? Message-ID: In general, I thought one should not mess with Tkinter from a background thread. But Eric Brunel recently posted a clever suggestion that one could communicate from a background thread to the main thread using event_generate to create custom events. Very neat: it's direct and it saves polling. He said it works for him on Linux, Windows and Solaris. I'd love to use it in my code, but am wondering if it's truly safe, e.g. safe by design and likely to remain so? Also, are there any other things one can safely do with Tkinter from background threads (such as set variables)? -- Russell From peter at engcorp.com Sat Dec 6 19:57:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Dec 2003 19:57:22 -0500 Subject: Fuzzy Logic References: <3FD26452.90906@di.uoa.gr> Message-ID: <3FD27AF2.9709740C@engcorp.com> Christos KK Loverdos wrote: > > Hi all! > > Is there any fuzzy logic package? Google is your friend: http://www.google.com/search?q=python+%22fuzzy+logic%22 From thomas at esands.com Wed Dec 10 17:30:57 2003 From: thomas at esands.com (Thomas Schulz) Date: Wed, 10 Dec 2003 22:30:57 +0000 Subject: check disc space Message-ID: Any ideas how to check for free disc space from Python. Platform independent? Thanks for any suggestion. Thomas From fumanchu at amor.org Thu Dec 11 13:15:50 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 11 Dec 2003 10:15:50 -0800 Subject: Prototype-based programming Message-ID: Now if we can just develop OO-optimized hardware: http://z.iwethey.org/forums/render/content/show?contentid=120862 Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: Hung Jung Lu [mailto:hungjunglu at yahoo.com] > Sent: Thursday, December 11, 2003 10:11 AM > To: python-list at python.org > Subject: Re: Prototype-based programming > > > Bruno Desthuilliers wrote in > message news:<3fd7bf36$0$28702$626a54ce at news.free.fr>... > > > > You may want to have a look at Io > > http://www.iolanguage.com/ > > > > Thanks. That was a good dose of adrenaline shot. :) > > It's amazing to see how people are converging. It's also refreshing to > see some brains out there. I am over 1 year late in knowing about the > existence of Io (it came out last year) and over 2 years late in > hitting upon some concepts. But that's all right. Better catch up late > than never. :) > > When I saw that Io was prototype-based, I told myself: "OK, smart". > When I saw statements were message-based, I told myself: "OK, more > than smart". When I saw that it was designed with full awareness of > Python and Ruby, I told myself: "OK, very smart". When I saw that it > has codeblocks ("block" in Io syntax) and weaklinks, I told myself: > "OK, really smart". When I saw that it can print the source code of a > block, I told myself: "OK, extremely smart". :) > > Of course, all the fundamentals have been out there before. But it is > refreshing to see people heading in the right direction. > > regards, > > Hung Jung > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Mon Dec 15 09:43:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Dec 2003 09:43:02 -0500 Subject: gzip module - help! References: <3fdc2a06.0@news1.mweb.co.za> <3fdc2cd3.0@news1.mweb.co.za> Message-ID: <3FDDC876.193D2284@engcorp.com> bmgz wrote: > > Sorry, I forgot to mention that i am trying to create an archive. As I understand it, gzip is about compressing, while tar and zip are about archives. You can't use gzip to make an archive, you can only use it to compress or decompress... archives, or other files. -Peter From nospam at nospam.net Sat Dec 27 13:21:24 2003 From: nospam at nospam.net (Karol Zadora) Date: Sat, 27 Dec 2003 10:21:24 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> <7xr7yvjle5.fsf@ruckus.brouhaha.com> <21bb8d55.0312240144.4eb9caab@posting.google.com> <7xk74mik64.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xk74mik64.fsf at ruckus.brouhaha.com... > andreif at mail.dntis.ro (Stormbringer) writes: > > Sounds like a poorly designed system the one you messed with. > > The system I messed with wasn't designed for high volumes of updates. > > > Even if it was limited i/o traffic I am not sure how to do profiling > > to find out if this is the case (although I do have doubts about this) > > - any suggesions how ? > > A crude but maybe useful thing you can do is just observe the CPU load > while the program is running. If the CPU load is low but you hear the > disk banging around, you're i/o bound. As for profiling, there's a > Python profiler documented in the Python library manual, that's the > first thing to try. > > There's a good article series on full text indexing at tbray.com which > might interest you, by the way. It was linked from Slashdot a couple > days ago. On Windows, to determine if you are I/O bound, you might try to watch these two counters: - Physical Disk: Avg. Disk Queue Length (should be not more than three times the number of physical disks (spindles) used by your program) - Physical Disk: Avg. Disk sec/Transfer (should be less than 15-18 ms) HTH, Karol From reply.in.the.newsgroup at my.address.is.invalid Sat Dec 13 03:23:51 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 13 Dec 2003 09:23:51 +0100 Subject: ANN: lunatic-python 0.1 References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> Message-ID: <5iiltv4pf107ubuck3kqk6ob2d1jj3kvn4@4ax.com> Paul Rubin: >Gustavo Niemeyer: >> Lunatic Python is a two-way bridge between Python and Lua > >But you left out the most important question: WHY? And: What is Lua? What is it good for? "Lua, the extensible, embedded language ... for extending and customizing applications ... - Clear and simple syntax (since it is not the main language for most of its users). - Small size and small implementation (so the cost of adding it to the host will not be too high). - Good data-description facilities (to make it useful as a configuration language). - Adequate extensibility (to allow its use in high abstraction levels--for interfacing with users in diverse domains)." http://www.lua.org/ddj.html -- Ren? Pijlman From try_vanevery_at_mycompanyname at yahoo.com Fri Dec 19 08:05:25 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 19 Dec 2003 05:05:25 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> <23891c90.0312180345.6cdda060@posting.google.com> Message-ID: "Paul Boddie" wrote in message news:23891c90.0312180345.6cdda060 at posting.google.com... > > Not at all. My point was that .NET apparently got cooked up when Sun > rained on Microsoft's J++ parade. A lot of old timers made comparable > remarks when Java emerged back in the mid-nineties because the > portable virtual machine thing has a long history and has produced a > lot of compelling competitors to Java, although the Java security > model does seem like a differentiator to me. Ok, to understand history (lest we be doomed to repeat it) why did Java succeed as an industry dominant language where others failed? Was it simple things like level of support? Incidentally, I just did a whirlwind tour of all the various languages recognizably available on Usenet: Haskell, OCaml, Mercury, Bigloo, Erlang, Common Lisp, Eiffel, quite a few really. Although I'm satisfied with Python from a high level applications glueing standpoint, I'm not satisfied from a low-level performance language interop standpoint. So I wanted to see if there was something that was both high level and generated much faster code for 2D image processing type problems. What I decided was, Python has too much community, library, and industry support behind it, and a lot of these other languages carry major design risks, i.e. going from imperative to functional programming. So as of today, Python is winning in practice despite whatever might be better in theory. See any parallels with Java or C# history debates? > > I'd say the latter, since otherwise, it would be Java and we'd all be > > doing our language interop in Java. > > Well, I get a fair amount of mileage out of Jython, Apache Axis (SOAP) > and so on, but I guess that this isn't your point. It could be for your problem domain, but it isn't for mine. > and I can imagine that the Mono > people have pushed it even further to leverage various components > implemented in C/C++. > > Perhaps we will be doing all our development in .NET-related > technologies in five years time. I just hope that if this is the case, > Microsoft don't do a SCO and hit everyone up with $799 "licence" > demands. I would hope that there's a replacement strategy for the interop concept. Aren't the FSF guys doing something like that? -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From newsgroups at jhrothjr.com Sat Dec 20 06:39:22 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 06:39:22 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Steve Lamb" wrote in message news:slrnbu7m1s.u03.grey at dmiyu.org... > On 2003-12-20, John Roth wrote: > > I'm not sure what your point is. > > If you had run it you would have understood it. You didn't run it, did > you? > > > Your example isn't going to produce the expected result if you say: > > > print thisis.amethod > > > instead of > > > print thisis.amethod() > > Well, you kind of got it. Here's the run: > > Python 2.3+ (#2, Aug 10 2003, 11:33:47) > [GCC 3.3.1 (Debian)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> class ThisIs: > ... avariable = 'a' > ... def amethod(self): > ... return 'b' > ... > >>> thisis = ThisIs() > >>> print thisis.avariable > a > >>> print thisis.amethod() > b > >>> import this > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! > >>> print "Read line 2." > Read line 2. > > Line 2: "Explicit is better than implicit." > > thisis.amethod() is an explicit call to a method. If you flubbed it and > overwrote your namespace later on then you would get unexpected results at > runtime. If you remove the () it becomes an implicit call depending on the > object that is a reference to. Hmmm, I guess I could have also finished with > this line as well, "Read line 12." IE, "In the face of ambiguity, refuse the > temptation to guess." > > def foo: > return 'a' > > bar = foo > > Is it a or is it the function object? Rats, now we have to make a special > case when point to a function as opposed to any other object. D'oh, now we > need to read line 8, "Special cases aren't special enough to break the rules." > Ok, so we shouldn't make a special case here. That also applies to where? > > How often to we make calls to functions/methods without parameters > compared to how often we do? ;) > > Man, I never knew that little tidbit was so fun and self referencing. > Thanks Tim Peters! :) > > -- > Steve C. Lamb | I'm your priest, I'm your shrink, I'm your > PGP Key: 8B6E99C5 | main connection to the switchboard of souls. > -------------------------------+------------------------------------------ --- From ajw140NO at SPAM.york.ac.uk Wed Dec 17 18:10:55 2003 From: ajw140NO at SPAM.york.ac.uk (Andrew Wilkinson) Date: Wed, 17 Dec 2003 23:10:55 +0000 Subject: nb_multiply and different types Message-ID: Hi, I'm trying to wrap a Vector and Matrix class I have written in C into Python types. Everything is working nicely, except for the Matrix multiply by Vector function. I have defined an nb_multiple callback, and it works fine for Matrix * Matrix - but it's not even getting called for Matrix * Vector - Python is deciding for me that its of the wrong type, and raising a type error. How do I persuade it that I know what I'm doing? I have seen about about coercing, but I'm not sure if that'll do what I want - if someone could give me an example that'd be muchly appreciated. Thanks in advance, Andrew Wilkinson -- I like nonsense, it wakes up the brain cells. From oren-py-l at hishome.net Sat Dec 20 08:21:27 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 20 Dec 2003 08:21:27 -0500 Subject: How to use a 5 or 6 bit integer in Python? In-Reply-To: <4h95uvg1jpbt1psdon9m4ov7tbc79d586g@4ax.com> References: <4h95uvg1jpbt1psdon9m4ov7tbc79d586g@4ax.com> Message-ID: <20031220132127.GC99675@hishome.net> On Fri, Dec 19, 2003 at 06:26:22PM +1100, Glen Wheeler wrote: .... > tuple of integers as it's data type. All integers are from 0-63. > For the second dict: Trivially small, with a maximum of 32 > elements, starts at 0 and an average of around 7. Keys are kept as > integers from 0-63 and data ranges from -1-30, i It's your lucky day... All your integers are from -1 to 63 which fits nicely in Python's range of "privileged" integers from -1 to 100. These are handled much faster by using a static table of integer objects without the overhead of allocation and deallocatiom. Oren From giles_brown at hotmail.com Mon Dec 1 03:44:09 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 1 Dec 2003 00:44:09 -0800 Subject: medusa as win32 service References: Message-ID: <57de9986.0312010044.49f6430c@posting.google.com> Robin Becker wrote in message news:... > I wonder if this is the right way to write a medusa(asyncore) server > with the win32all framework. Other example services seem to create an > event to pass the stop signal from SvcStop into a separate termination > method, but I'm unsure how that would mix with the polling loop. > > This simple framework seems to start and stop OK, but I wonder if I'm > missing some obvious race or something. I think the cleanest design for this is to use the medusa.threading.select_trigger function to send an asyncore.ExitNow exception into the main select loop. The only problem with this is that the current medusa.threading.select_trigger (in the sourceforge medusa version) catches (and does not re-raise) this exception. I've modified our code so that it does not catch it and this seems to work very well (we have a web server using medusa that runs as a service). Regards, Giles Brown From matt at satbp.com Sat Dec 6 15:46:48 2003 From: matt at satbp.com (Matthew A. Berglund) Date: Sat, 06 Dec 2003 20:46:48 GMT Subject: Binary number manipulation References: <350rsvkbsht8rgs1fsjjc7vkktf87sahi7@4ax.com> <9hkzb.52005$Vu5.3422581@twister.southeast.rr.com> Message-ID: <20031206154820.0c56455e.matt@satbp.com> Thanks everybody. I settled on the ((high << 8) | low) As this fits my need for the moment. I will look at struct when I have some more time. Thanks, Matt From nospam at nowhere.hu Mon Dec 15 18:54:05 2003 From: nospam at nowhere.hu (Miklós) Date: Tue, 16 Dec 2003 00:54:05 +0100 Subject: Leo 4.1 rc1 released References: Message-ID: Thanks, Edward for this really great piece of software! A while back I managed to clean up (a bit at least) such a mess with Leo I hadn't imagined I could ever... Now my nagging: While the edit pane is fine I do want my favourite Vim... Is this possible somehow? I mean to embed Vim in the window.. Best and many thanks, Mikl?s Edward K. Ream wrote in message news:vtrrmpfit4q8b at corp.supernews.com... > Leo 4.1 release candidate 1 is now available at: > http://sourceforge.net/projects/leo/ > > The highlights of this release: From bokr at oz.net Tue Dec 16 01:21:54 2003 From: bokr at oz.net (Bengt Richter) Date: 16 Dec 2003 06:21:54 GMT Subject: Terminal "hang up" problem References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: On Mon, 15 Dec 2003 16:07:31 -0800, JD wrote: >What is the best way to debug a Python program if when i run it, it >totally hangs up the >terminal console. > >Control-c or control-d has NO effect, so it's hung up somewhere, but >we have no idea >where. > >We are using Python 2.3, on an openBSD box, running the python script >from the shell. > >Is it possible to somehow find out what is making it hang up? > have you tried gdb python and then run with your_python_prog.py as the arg? If gdb will catch a ctl-c then you might be able to use bt to get a backtrace? (I don't really know much about gdb, but someone here has probably done this and can tell you the right way to do it ;-) Of course, there's the lions-in-africa thing of putting print statements to narrow down successively the area where it could be hanging ;-) Regards, Bengt Richter From __peter__ at web.de Fri Dec 5 22:11:46 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Dec 2003 04:11:46 +0100 Subject: Newbie question: Any way to improve this code? References: Message-ID: Duncan Smith wrote: > try: > f = open("firmas.txt",'r') > texto = f.read() > frases = texto.split('\n')[:-1] > finally: > f.close() Running this with a nonexistent firmas.txt gives you: ...> python frases.py Traceback (most recent call last): File "frases.py", line 6, in ? f.close() NameError: name 'f' is not defined Although it looks less symmetrical, the f = open() should be placed *before* the try block. When you enter the try block, you are already sure that the file was opened, and only then it makes sense to ensure that the file will be closed even if some of the following operations fail. frases = ... does not need access to the file and thus belongs *after* the finally block - but that is less crucial. Another (minor) issue: I'm never confident that a plain text file ends with a newline character, so in my opinion you risk losing la ?ltima frase. Peter From max at alcyone.com Wed Dec 3 23:41:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 03 Dec 2003 20:41:16 -0800 Subject: String length ... len(str) References: <8adtsvoen2vb4akhk3nsib151kfjel9mja@4ax.com> Message-ID: <3FCEBAEC.995B77EE@alcyone.com> Jeff Wagner wrote: > Thanks for the info, it clears up a lot of confusion for me. > > I was under the impression that: > str1 = "here" + "we" + "are" was the same as > str2 = "here" , "we" , "are" ... > > the only difference being that the str2 was separated by a space. But > str1 is a string, str2 is a > tuple. Right. What probably confused you is that print acts like this: >>> print "one", "two", "three" one two three But this is only because print is a statement, and uses this as a special form. > Cool ... who ever came up with the word tuple? That's a weird name. It's derived from mathematics. A pair of items is a double, three items is a triple, four is a quadruple, and n is an n-tuple. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Can I be your friend / 'Till the end -- India Arie From reply.in.the.newsgroup at my.address.is.invalid Sat Dec 20 05:28:17 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 20 Dec 2003 11:28:17 +0100 Subject: string parsing screwing up on large files? References: <75765317.0312191855.6ce6f4d2@posting.google.com> Message-ID: Daniel Kramer: >Any suggestions where I might look? In the source code, probably. I've looked long and hard at your posting, but I didn't find any bug there. -- Ren? Pijlman From jacek.generowicz at cern.ch Thu Dec 11 08:03:36 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Dec 2003 14:03:36 +0100 Subject: About the use of **args References: Message-ID: Zunbeltz Izaola writes: [snip] > 3) If when setting some attribute there is necesary to have side > effects, it can be achive defining __setattr__ and doing the right > thing depend on the attribute. (It is possible to raise an > exception when the attribute is not in a list/dictionary of usable > attributes, to prevent typos and such kind of errors) > > 4) __getattr__ can be defined to deal with undefined attributes. For > example it can handle in different way the attributes in a list of > permited attributes (see point 3) > > 5) attributes that are computed in the fly, can be get like normal > attributes using "property" (property is new in 2.3 or 2.2?) [snip] > Are those ideas correct? Pretty much. Properties are available in 2.2. They only work on new style classes. Just about anything that can be done with properties can be done with __setattr__ &co, but I think that properties are generally preferred, if available. From robin at jessikat.fsnet.co.uk Mon Dec 1 05:37:12 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 1 Dec 2003 10:37:12 +0000 Subject: win32net.NetUserChange vs XP Message-ID: I'm trying to centralize changing the administrator password on our mini office net and the following works OK for all of the win2k clients. win32net.NetUserChangePassword(comp, 'Administrator', current, next) however, it fails with access denied for the XP machines and I'm not clever enough to work out why. I do notice that XP seems to have a different system drive (Windows instead of Winnt) and that I am unable to work out how to share that directory. -- Robin Becker From martin at v.loewis.de Sun Dec 7 15:39:03 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Dec 2003 21:39:03 +0100 Subject: diferences between 22 and python 23 In-Reply-To: References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: Bengt Richter wrote: > This sounds very similar to what I have been trying to say. I would really suggest that you implement your ideas. You *will* find that they are unimplementable. After adjusting the ideas to constraints of reality, you *will* find that you break backwards compatibility. After fixing the backwards compatibility problems, you *will* find that your implementation has very bad performance characteristics, compared to the existing string types. Unfortunately, it is very difficult to nail down the problems you will encounter, as you refuse to provide a complete specification of the interface and implementation that you propose. Originally, I thought you are proposing modifications to , but now it appears that you are proposing a new data type, which has large similarities with . If so, I fail to understand why you don't want to use the existing Unicode type. Notice that /F has something completely different in mind: He is still talking about the Python Unicode type, and just suggesting that a different internal representation should be used. Speculating about the motivation, I would think he has efficiency in the face of round-trip conversions in mind, but not a change in visible behaviour. Regards, Martin From rainerd at eldwood.com Sat Dec 20 13:49:06 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 20 Dec 2003 18:49:06 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Carl Banks wrote: > You ideas about what a function's purpose is are just not relevant to > whether the time of evaluation is consistent. I'm not talking about whether or not time of evaluation is consistent - clearly either way is consistent so long as it is consistently used. I'm saying that getting a fresh copy of default args is useless and dangerous because it only helps with functions which shouldn't be written in the first place. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From anton at vredegoor.doge.nl Thu Dec 11 17:51:40 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 11 Dec 2003 23:51:40 +0100 Subject: optimization pointers? References: Message-ID: <3fd8f5c4$0$121$3a628fcd@reader1.nntp.hccnet.nl> "r.e.s." wrote: >Would anyone care to offer pointers on how the following code >might be optimized? Or alternatives? ... > >--- >def lz(string): > """ Return the Lempel-Ziv complexity (LZ78) of string. """ > > vocabulary = [] > word = '' > for char in string: > word += char > if word not in vocabulary: > vocabulary.append(word) > word = '' > return len(vocabulary) >--- > >On my 2 GHz system running PythonWin, the above code averages >about 1.3 hrs to process a 1 MB string. I'd hoped to compute >LZ78 for multi-GB files, but it seems infeasible. (?) On a 300 mhz celeron the script below takes about ten or twenty seconds, the original lz is commented out as it never seems to finish for longer strings. Anton p.s. the file I used is here: http://sailor.gutenberg.org/etext97/1donq10.zip import sets def lz(string): """ Return the Lempel-Ziv complexity (LZ78) of string. """ vocabulary = [] word = '' for char in string: word += char if word not in vocabulary: vocabulary.append(word) word = '' return len(vocabulary) def lzx(string): """ Return the Lempel-Ziv complexity (LZ78) of string. """ vocabulary = sets.Set() word = '' for char in string: word += char if word not in vocabulary: vocabulary.add(word) word = '' return len(vocabulary) def test(): fn = '1donq10.txt' s = file(fn,'rb').read(1000000) print lzx(s) #print lz(s) if __name__=='__main__': test() From no at spam.invalid Fri Dec 26 18:25:40 2003 From: no at spam.invalid (Russell E. Owen) Date: Fri, 26 Dec 2003 15:25:40 -0800 Subject: Python on Max osx and tkinter References: Message-ID: In article , Ralf Wieseler wrote: >Hello! I'm quite new to Python. > >I wrote some little scripts using the "import from tkinter" Statemant >that work well on Windows and Linux. but if i try to execute them in my >Powerbook with Mac OSX 10.2.8 i get only Errors. I imorted the TKinter >Module with the Package Manager of MacPython 2.3 but it doesn't work. >My Macphython has no idea of TKinter. >Whats wrong? What I did that worked on Jaguar: - Installed MacPython 2.3 for Jaguar using the binary installer from: - Installed Tcl/Tk 8.4.4 using the binary installer from - Used Package Manager (in /Applications/MacPython) to install _tkinter (and also readlines and some other useful stuff) At that point you ought to be able to open a NEW terminal window (tcsh caches some info, so an existing window will probably NOT work) and type "pythonw" (not "python", that would result in a GUI you cannot bring to the front) and you're in business: import Tkinter root = Tkinter.Tk() should bring up a window. (By the way "import from tkinter" will not work. The T in Tkinter is capitalized, and I don't think "import from " is valid python. If that does not work for you, can you be more specific about how it fails? -- Russell P.S. for Panther, you can use the same technique, but make sure you install MacPython 2.3 for Panther instead of for Jaguar, or you'll end up with a mess. Panther already includes a usable MacPython (and two copies do not coexist well), so the MacPython installer only adds some extra components. From roy at panix.com Fri Dec 5 13:11:18 2003 From: roy at panix.com (Roy Smith) Date: Fri, 05 Dec 2003 13:11:18 -0500 Subject: Lists and Tuples References: Message-ID: In article , Skip Montanaro wrote: > (Probably more response than you wanted. I kind of got carried away...) > > >> I've spent most of the day playing around with lists and tuples to > >> get a really good grasp on what you can do with them. I am still left > >> with a question and that is, when should you choose a list or a > >> tuple? > > Generally, choose between tuples and lists based upon your data. In > situations where you have a small, fixed collection of objects of possibly > differing types, use a tuple. In situations where have a collection of > objects of uniform type which might grow or shrink, use a list. For > example, an address might best be represented as a tuple: > > itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201") > caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866") > > Though all elements are actually strings, they are conceptually different > types. That's a good example, because it makes for a nice segue. If you were holding data from a form that looked like: Street: ___________________________ City: ___________________________ State: ___________________________ Zip: ___________________________ Then I agree you're looking at a 4-tuple (assuming you didn't want to go whole-hog and define an Address class). But, imagine a somewhat more generic form that looked like: Address line 1: ________________________ Address line 2: ________________________ Address line 3: ________________________ Address line 4: ________________________ You might fill in exactly the same data, but now if feels like it should be a list. From lutz at rmi.net Tue Dec 2 20:41:43 2003 From: lutz at rmi.net (Mark Lutz) Date: 2 Dec 2003 17:41:43 -0800 Subject: portable development -- python for the pda? References: <20031126220246.GA63148@clarkevans.com> <3fcc9577$0$7676$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote in message news:<3fcc9577$0$7676$3a628fcd at reader1.nntp.hccnet.nl>... > lutz at rmi.net (Mark Lutz) wrote: > > >I'm using Python on a Sharp Zaurus C760 these days, > >one of the Japan models that you can get converted > >to English from a number of importers. It comes > >with a full VGA (640x480) swivel screen, and a nice > >keyboard. The keyboard isn't full size, but it's > >much better than the thumbs-key input of most PDAs. > > > >Python runs well on this machine too, with the Sharp > >ROM; you can code and run both console and Qtopia > >GUI applications. You can also run vim, gcc, mySql, > >SQLite, Apache, and so on. With gcc, you can even > >code and compile Python C extensions right on the PDA. > >There's a new X11 ROM as well (haven't tried it yet). > > This machine is very interesting for me too. But three things have > kept me from acquiring it. > > First it's a bit pricey, probably about 700 euros or so? Prices tend > to get better so maybe it will become possible in a few months. This might be a bit off-topic for c.l.py, and I'm not a Sharp sales rep, but I'll try to answer what I can here. I have no idea where prices will go on this line. There is a cheaper model (C750) if you're willing to go with less flash memory and a smaller battery (of these, the battery is the bigger sacrifice--the 760 typically lasts 8 hours). Of course, whether these PDAs are too pricey in general depends on the value of such a machine to you. They cost more than an average PDA, but they are not average PDAs. They are near laptop replacements. For me, the extra functionality was worth the price increment. It runs a full and up-to-date Python, with threads, sockets, os.popen/fork, and so on, and has a real filesystem and multitasking. It also lets me leave a laptop at home more often than before, and provides a much better PDA experience than I had under PalmOS. But YMMV arbitrarily; these are completely subjective remarks. > Secondly it's not really possible to have a look at it before buying, > because one has to mail order it, but maybe this will change too in > the near future. There are a few photos and review links on the page I mentioned (http://www.rmi.net/~lutz/pic22.html), but some general googling would be a good idea. Most mail order places allow returns (you get 5 days at dynamism), albeit usually with a restocking fee. Some people think that Sharp will start selling these outside Japan eventually, but afaik it's still an unknown. > Third and most important point for me is that I have some application > I want to use it for, it's my own little pygobo freeware script that > "nobody" wants to download but which is in my opinion the best > sgf-file viewer for baduk there is (at least for someone that can > program Python). However this viewer is written using TKinter and > there seems to be no such thing as Tkinter on any pda. The Zaurus runs Qt directly on the frame buffer, so there is nothing like X11 in the mix. Because of that, the Tk library, and hence Tkinter, won't run out of the box, afaik. You can build GUIs with Qt using the freely available PyQt package for the Zaurus, but this would require a recoding of the GUI parts of your program. Qt is a fairly typical and feature-rich API; it has a unique slot/signal coding paradigm, the merits of which you should judge for yourself (he says, desperately trying to avoid sparking a GUI war :-). But it seems like a reasonable toolkit if you're willing to translate. I have no idea if anyone's trying to port the Tk to the Zaurus or not; that would be ideal. Barring that, you could try the X11 ROM for the C7x0 series. In principle, that might enable Tk and Tkinter (I'd like to try this myself, if I get some free time). Other ideas: the anygui Python module has been reported to work atop Qt on the Zaurus too. anygui isn't as feature-rich as Qt, but it's simpler, and your scripts should be portable to platforms other than the Zaurus, even if they don't have a Qt installed. Because the Zaurus runs a Java VM, you might have some luck with Jython too (no idea). > Could you please comment on any of these points and give some > guesstimate of the time frame in which such a machine will become > feasible for me. I'd *really* like to review go-files while lying in > bed or while walking in the woods or whatever and my script is already > ideally suited for use on such a machine with its full-screen mode and > rotatable go-board (sorry for the plugging) I think it's a nice machine, and a great Python platform, but again, I'm just a satisfied customer. You might also consult some of the Zaurus forums on the web. --Mark Lutz (http://www.rmi.net/~lutz) From mcherm at mcherm.com Tue Dec 16 08:37:34 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 16 Dec 2003 05:37:34 -0800 Subject: rexec.py unuseable Message-ID: <1071581854.3fdf0a9eba3ea@mcherm.com> Luke writes: > i think the only really sensible way forward is to begin from a > sound basis... I agree completely. > proposal: how about building ACLs into the python codebase? Actually, I rather prefer the approach that has been mentioned before of trying to use capabilities. See, for instance, the threads on Capabilities found here: http://mail.python.org/pipermail/python-dev/2003-March/thread.html#33854 Of course, that's not trivial to add either, since some way would need to be provided for disabling Python's powerful introspection. > the algorithm for evaluating an acl has been worked out already, > and implemented originally by matthew chapman of the samba team, > so code under the GPL already exists [in an NT-like environment which > is over-the-top]. Unfortunately, code under the GPL is of no use at all for Python which is released with a more flexible (but GPL compatible) liscense. And I'm not quite sure what you mean by an "NT-like environment" being "over-the-top". > an empty acl also means that there is no performance penalty for having > acl code in the python codebase. Sorry, but I simply don't believe this. Really. Think about it a bit, and if you still think you're right, I'll provide some reasons, but I suspect you'll realize that it's simply not true. I *DO* think though, that some amount of slow-down *IS* acceptable (pie or no pie ) if it provided powerful new capabilities like *reliable* restricted execution environments. -- Michael Chermside From glenfant at NOSPAM.bigfoot.com Mon Dec 15 14:46:03 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Mon, 15 Dec 2003 20:46:03 +0100 Subject: Spell checking and Python Message-ID: Hi pythonists, Any experience or pointer on using a spell checker (aspell, ispell ?) with a Python app ? Many thanks by advance -- Gilles From claird at lairds.com Mon Dec 8 14:53:22 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 08 Dec 2003 19:53:22 -0000 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> <4redncaHtOe2LEmiRVn-ig@comcast.com> Message-ID: In article <4redncaHtOe2LEmiRVn-ig at comcast.com>, Terry Reedy wrote: . . . >beauty and ease-of-use of Python. Demotion of functions would point toward >'calculator Python'. . . . ... still a shockingly useful language. I know of many, many applications which do nothing which requires func- tion-first-classness, and quite a number which define no new classes. -- Cameron Laird Business: http://www.Phaseit.net From tim.one at comcast.net Tue Dec 30 18:56:50 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 30 Dec 2003 18:56:50 -0500 Subject: selecting a random item from a set In-Reply-To: Message-ID: [Alexander Schmolck] > Quite a few algortihms prominently feature choosing/removing a single > random element from a set at a time. Really? I'm aware of a great many algorithms that need to remove an *arbitrary* element from a set, where arbitrary means "it doesn't matter which one you pick", not "you must have an equal chance of getting each one". The existing set.pop() is fine for that. > On first sight I can't think of anything better to achieve this with > `sets.Set` than something along the lines of: > > for dummy, randomElement in zip(range(randrange(len(s)+1)), s): pass It's too obscure for my tastes, but something like that would certainly work. > # possibly followed by > s.remove(randomElement) > > Is there a better way? If not, how about something like > Set.randompop()? Probably not. I'm not convinced there's a real need, and given the implementation of sets there's no way to do it essentially more efficient than the way you've already figured out (it can be done using O(1) space instead, but it still takes O(len(s)) time -- the implementation of sets is lumpy, so the O(1)-time indexing trick used by random.choice() can't apply). If you think this is important enough to be worth the bother , you could define a hybrid data structure combining a set and a list, keeping them in synch. random.choice() can then be applied to the list part to get a random element in constant time. The only tricky part is deletion of an element. You need another dict under the covers to map each key to its index in the list. When it comes time to delete a key, you *overwrite* the list position it occupied with the last key in the list (and update that key's index), then reduce the length of the list by 1. That keeps deletion constant-time (expected-case) too. From joconnor at cybermesa.com Wed Dec 3 19:15:16 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 03 Dec 2003 17:15:16 -0700 Subject: String length ... len(str) In-Reply-To: References: Message-ID: Jeff Wagner wrote: >Can someone please explain the following to me: > > > >>>>str1 = "here" >>>>str2 = "here", "we", "are" >>>>len(str1) >>>> >>>> >4 > > >>>>len(str2) >>>> >>>> >3 > >Why is len(str1) = 4 and len(str2) = 3? > >If we were to say it's because the len() functions returns the number of elements in a string, then >len(str1) should be = 1 > >It's a little confusing. > > str2 =is a tuple of three strings, not a concatenated string. So you are getting the number if strings in the tuple, not the number of characters in a longer string. You have to use join to concatenate the strings with either join() or + >>> str2 = "here", "we", "are" >>> >>> str2 ('here', 'we', 'are') >>> type (str2) >>> len (''.join (str2)) 9 >>> str3 = "here" + "we" +"are" >>> str3 'hereweare' >>> len (str3) 9 From francisgavila at yahoo.com Sat Dec 13 23:38:18 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sat, 13 Dec 2003 23:38:18 -0500 Subject: connection to samba server References: <3fdbc954$0$218$e4fe514c@news.xs4all.nl> Message-ID: Przemo Drochomirecki wrote in message ... >There's a task: >1) connect to linux samba server from windows application After <5 minutes of googling, and knowing nothing about windows programming, it seems that the function you need is WNetAddConnection2: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wnet/wnet/w netaddconnection2.asp There is a (very popular) Python package out there which exposes the win32 api. I'm not sure what it's called. (win32api? pythonwin? win32all?) >2) compare files from samba server with files from choosen windows >catalog(s) What's a windows catalog? >3) make backup if it's necessary. > >So my problem is how to make connection with samba server having triple (IP >server, login, password) and download/upload >files. I'm working on Wk2. I was searching for suitable library but found >nothing. You need the share name, too, I think, not just server/login/password. Given what I think you want to do (it's not crystal clear), shouldn't you be using rsync? My guess is that you have a bunch of windows clients and you want to back them all up to a linux server out there somewhere. Rsync lives for this stuff. Random Google for rsync on windows: http://optics.ph.unimelb.edu.au/help/rsync/rsync_pc1.html Hey, look! Rsync is hosted by samba! http://rsync.samba.org/ There's also a port of rsync to python and java (presumably, so you don't need cygwin?) Don't know how useful they are, or if they can interop. Why isn't the network share always connected to the windows clients? That way you wouldn't need to back up clients to a server, but just the one server (whose shares all the windows clients mount) to some other server/media/drive/whatever, and you can keep all that backup machinery in a *nix environment. This is far less complex, no? Of course, I don't administer windows clients in big, heterogeneous networks, so feel free to ignore my babblings. -- Francis Avila From jmiller at stsci.edu Fri Dec 12 17:20:59 2003 From: jmiller at stsci.edu (Todd Miller) Date: 12 Dec 2003 17:20:59 -0500 Subject: ANN: numarray-0.8 released Message-ID: <1071267659.946.3.camel@halloween.stsci.edu> Release Notes for numarray-0.8 Numarray is an array processing package designed to efficiently manipulate large multi-dimensional arrays. Numarray is modelled after Numeric and features c-code generated from python template scripts, the capacity to operate directly on arrays in files, and improved type promotions. I. ENHANCEMENTS 1. Peter Verveer's nd_image package! Peter Verveer has contributed a fully documented and tested multi-dimensional image processing package, numarray.nd_image. Thanks Peter! (A manual for numarray-0.8 is currently unavailable but will be forthcoming) 2. Masked Arrays Numarray now features a port of Paul Dubois Masked Array package, MA, now called numarray.ma in numarray. 3. Improved packaging The entire distribution is now a single package. This means binary installations can be accomplished with a single install file. 4. Unified testing The selftest format has been improved so that doctest is used for all packages and can be executed via a single top level command: numarray.testall.test(). II. BUGS FIXED 839415 Error mode comments from Tim Hochberg 839409 array comparison return booleans 839407 ``take`` is really only useful for array types 839404 ``array_repr`` no longer supports `suppress_small`` 839396 ``Error.popMode`` should raise if last mode is popped 839395 ``anArray.conjugate()`` acts in place 839393 ``argmax`` returns shape () arrays instead of scalars 839388 ``where`` and others do not appear to use asarray 839385 add.reduce takes dim as an argument instea 839382 na.searchsorted does not accept scalars for 2nd argument 839378 numarray.dot doesn't accept scalars, Numeric.dot does 839377 Assigning a Numeric slice to a numarray array fails 839374 linear_algebra.determinant` returns length-1 vector 839372 Mixing arrays and lists in array() fails 839370 sqrt, power, ** fail on complex zero* 832609 Bug in putmask type casting 830219 Segmentation fault 829184 [Numpy-discussion] Incorrect OverflowError 827013 numarray.convolve.correlate2d option fft=1 826311[Numpy-discussion] Possible bug in scalar array 824840 add.reduce return array with wrong shape 820813 Arnaud's Comments 816841 readonly memmaps segfault on assign 816182 Small integers not promoted for calculations 813318 imports fail from numarray's directory 810940 Erratic Behavior when subclassing NumArray 803757 problem with complex log10 796739 Resized memmapped chararray fails 857207 sometrue caching bug? 856611 takeNBytes fails 853508 zero length memmap 839397 underflow behavior should default to 'ignore' not 'warn' 839389 take() now requires a keyword argument for axis 837310 argsort is non-deterministic 805349 Proper dot product for a rank>2 arrays (tensors) See http://sourceforge.net/tracker/?atid=450446&group_id=1369&func=browse for more details. III. CAUTIONS 1. numarray extension writers should note that the documented use of PyArray_INCREF and PyArray_XDECREF (in numarray) has been found to be incompatible with Numeric and has therefore been deprecated. numarray wrapper functions using PyArray_INCREF and PyArray_XDECREF should switch to ordinary Py_INCREF and Py_XDECREF. WHERE ----------- Numarray-0.8 windows executable installers, source code, and manual is here: http://sourceforge.net/project/showfiles.php?group_id=1369 Numarray is hosted by Source Forge in the same project which hosts Numeric: http://sourceforge.net/projects/numpy/ The web page for Numarray information is at: http://stsdas.stsci.edu/numarray/index.html Trackers for Numarray Bugs, Feature Requests, Support, and Patches are at the Source Forge project for NumPy at: http://sourceforge.net/tracker/?group_id=1369 REQUIREMENTS ------------------------------ numarray-0.8 requires Python 2.2.2 or greater. AUTHORS, LICENSE ------------------------------ Numarray was written by Perry Greenfield, Rick White, Todd Miller, JC Hsu, Paul Barrett, Phil Hodge at the Space Telescope Science Institute. Thanks go to Jochen Kupper of the University of North Carolina for his work on Numarray and for porting the Numarray manual to TeX format. Thanks also to Edward C. Jones, Francesc Alted, Paul Dubois, Eric Jones, Travis Oliphant, Pearu Peterson, Colin Williams, Peter Verveer, Nadav Horesh, Sebastian Haase, Tim Hochberg, and everyone who has contributed with comments and feedback. Numarray is made available under a BSD-style License. See LICENSE.txt in the source distribution for details. -- Todd Miller jmiller at stsci.edu From alan.gauld at btinternet.com Sat Dec 27 19:10:26 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Dec 2003 00:10:26 GMT Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> Message-ID: <3fee1d7d.350511859@news.blueyonder.co.uk> On Sat, 27 Dec 2003 21:37:07 GMT, MidasOneTwo at hotmail.nospam.com (Midas) wrote: > It looks like you hardcoded the name ObjectB within ClassA. > I'd like to avoid all hardcoding of names. In other words, > I'd like ObjectA to be *told*, at run time, which object > to call and which method to call. While what you ask is possible it does kind of mess up the ideas of good OO design. For this to happen the caller of A's methods must know that A contains a B (not too bad but not pure OOD) and, much worse, know that B contains a method called foo which it tells A to call. The law of demeter suggests you should create a method on A that knows what to do, which may entail calling a method on B but it may equally entail looking up a third object which is a message dispatcher or ORB and getting it to do the work. The client of A shouldn't really know how A's internals work. So I guess I'm querying whether your design is as decoupled as it should be. The only thing that should know what A has inside is A... To do what you request something outside of A has to know about B, give it to A then request A to call a known method of the B givento A. Why not just have the external agency manage B directly since it is already tightly coupled to it? However I can equally guess that in the real world there may be some cases, especially in data driven applications where you want to dynamically control the internals of A, although even there creating a dispather mechanism may be worth the extra work... Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From http Sat Dec 13 07:52:26 2003 From: http (Paul Rubin) Date: 13 Dec 2003 04:52:26 -0800 Subject: "Do this, and come back when you're done" References: <7x8ylg5252.fsf@ruckus.brouhaha.com> Message-ID: <7xekv8vq0l.fsf@ruckus.brouhaha.com> Kamus of Kadizhar writes: > No, actually, both machines are under my control (and in my house). > I'm slinging large (1GB MOL) files around on an unreliable, slow > wireless network. I am trying to detect an incomplete copy across the > network. The local machine is the video player and the remote machine > is the archive server. My kids have a habit of just shutting down the > video server, resulting in incomplete transfers to the archives. If > it's appropriate for this newsgroup, I'd like to post the entire > effort for comments (it's my first bit of pyton code.) So far, python > has been the easiest language to learn I've ever come across. I tried > learning perl, and it was a disaster.... Too convoluted. Python is a > breath of fresh air. Also, the docs and support here is > excellent. :-) My thanks to all the volunteers who put in time to > build python. Why don't you look at the rsync program. It brings two machines into sync with each other by automatically detecting differences between files and sending only the deltas over the network. From tjreedy at udel.edu Wed Dec 10 15:47:34 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2003 15:47:34 -0500 Subject: cell object dereferencing References: <3FD5FD4A.9060406@jandecaluwe.com> <3FD6EA60.2000905@jandecaluwe.com> <3FD761EA.6070407@jandecaluwe.com> Message-ID: "Jan Decaluwe" wrote in message >(Next thing I would like to understand is how the hell you came up with this!) I can't speak for Pedroni, but... If you start with the two facts I initially stated -- cells are externally accessible as .func_closure tuple members but their values are only internally accessible -- and treat them as design guidelines (as Pedroni did) rather than as deniers of possibility (my mistake), one is pretty much lead to the conclusion that you need to attach the cells to a function that reads and returns the value. This is Pedroni's template function. The third fact -- that .func_closure is read-only, dictates the near-copy via new instead of simple reuse of the template. Terry From yan at NsOeSiPnAeMr.com Sun Dec 14 07:57:49 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sun, 14 Dec 2003 07:57:49 -0500 Subject: intro to python books Message-ID: I'm looking for a good intro to python book. I'm very familiar with programming, but know nothing of OOP or systems (OS type) programming. All of my programming experience is in number crunching and generic graphics engines (read: gobs and gobs of matrix manipulations and super-efficient sorts), all of it in C. I've written exactly one program in Python. So, I need something that covers the finer points of Python - difference between ' and " for example - and the greater things beyond that, like implicit lists and classes. I've had good luck with the O'Reilly books in the past, but I have to buy everything mail order, so I can't browse easily and see what I'm buying. Thanks, -Kamus -- o__ | If you're old, eat right and ride a decent bike. ,>/'_ | Q. (_)\(_) | Usenet posting` From tim at zope.com Sat Dec 6 22:54:30 2003 From: tim at zope.com (Tim Peters) Date: Sat, 6 Dec 2003 22:54:30 -0500 Subject: memory usage In-Reply-To: <9_wAb.451548$Fm2.447978@attbi_s04> Message-ID: [Dave] >> I'm writing code which deals with lists of millions to tens of >> millions of elements. It seems to me that python gobbles up memory >> faster than it should in these cases. >> >> For example, I start the python interpreter and then execute the >> following code: >> >> >>> f = [] >> >>> for i in range(1e7): >> ... f.append(0.1) >> >> In another window on my Linux system I then run top. The python >> process is now using 155 MB of memory. Why is python using such a >> large amount of memory, nearly nearly 16 bytes for a float in this >> case? [Robert Toop] > 8 bytes for each float, As was pointed out before, there are only two floats in that snippet (the float object 1e7, and the float object 0.1; the example reuses the single float object for 0.1 10 million times). The memory is actually consumed by the 10 million distinct integer objects in giant list constructed by range(). > and I'm guessing 8 bytes for 2 pointers to form the list. Nope, Python lists are contiguous vectors. Accessing an element by index is constant-time. > One needs 2 pointers in order to facilitate nearby forward/backward > reference, and to be able to remove an element without having to > search from the start. An extensible list cannot be a pointer-free > contiguous array unless all elements are copied each time you append > to it. Python uses mildly exponential over-allocation, sufficient so that growing a list takes *amortized* O(1) time per append. Speed of indexed list access is much more important in most apps than speed of append, but Python has good O() behavior for both. O() behavior for deleting (or inserting) "in the middle" of a list is atrocious, though (O(len(list)). Life is a never-ending sequence of tradeoffs . > Access to a linked list like this requires not only extra memory, > but extra time, to say nothing of large RAM to avoid virtual memory > paging. You'd be better off with static-dimensioned (hence > contiguous) arrays. Of course, that might be impractical for your app. Python's lists are contiguous vectors, of pointers to Python objects. The standard array module embeds data directly in contiguous vectors, but the kinds of data an array.array can hold are limited to simple scalar types (floats, bounded integers, characters). The NumPy extension has extensive facilities for slinging numeric arrays at high speed and memory efficiency. > If your lists require dynamic extension and sparse random access, > you'd be better off with an indexed tree (database-like) storage > scheme. I'm too new to python to know if such packages exist, but > I'll bet they do. ZODB (the object-oriented database underlying Zope) contains a Python BTree package coded in C that's quite capable. Not only O(log(N)) time for lookups, and for inserts and deletes in arbitrary positions, but it performs range searches very efficiently too (BTrees are always in "sorted order"), and provides transparent persistence backed by a ZODB database (if you want that -- using ZODB's BTrees from Python doesn't *require* that you use anything else in ZODB -- they can be used as in-memory Python objects just as easily). You can even have BTrees much bigger than your RAM that way -- although typical RAM sizes are growing so fast, I'm not sure how much longer I can say that with a straight face. but-so-long-as-they-pay-me-i-won't-crack-a-shadow-of-a-smile-ly y'rs - tim From rupole at hotmail.com Mon Dec 1 04:22:52 2003 From: rupole at hotmail.com (Roger Upole) Date: Mon, 1 Dec 2003 01:22:52 -0800 Subject: PyArg_ParseTupleAndKeywords and optional unicode arguments Message-ID: <3fcada7e_1@127.0.0.1> I'm having a problem with an extension module using PyArg_ParseTupleAndKeywords with 2.3.2. Distilled down: PyObject *wtf(PyObject *self, PyObject *args, PyObject *kwargs) { WCHAR *dummy1=NULL; WCHAR *dummy2=NULL; WCHAR *dummy3=NULL; static char *dummyelements[]={"dummy1","dummy2","dummy3",0}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|uuu:wtf", dummyelements, &dummy1, &dummy2, &dummy3)) return NULL; Py_INCREF(Py_None); return Py_None; } >>> wtf(dummy1=u'xxxxxx',dummy3=u'dummy3') Traceback (most recent call last): File "", line 1, in ? TypeError: wtf() argument 2 impossible [17300 refs] >>> Anybody seen this before, or is this a known problem, or am I just missing something obvious ? Any help greatly appreciated. Roger From mfranklin1 at gatwick.westerngeco.slb.com Mon Dec 8 04:31:26 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 08 Dec 2003 09:31:26 +0000 Subject: Nub needs help withTkinter In-Reply-To: <1cca69c7.0312061523.6b73b4fa@posting.google.com> References: <1cca69c7.0312061523.6b73b4fa@posting.google.com> Message-ID: <1070875885.1165.13.camel@m-franklin> On Sat, 2003-12-06 at 23:23, Agency wrote: > I'm trying to program a utility that counts the beats per minute in a > song > by tapping the spacebar. I already have a program that does this, but > I wanted to make my own. The "enter" key resets the counter to zero > along with one of two displays. I'm importing Tkinter and this is what > I have so far. I get a syntax error at this spot -----> > > Any thoughts how to get the keypress to increase the counter better? > Is it possible to convert it to an int or something? > ------------------------------------------------------------------ > from Tkinter import * > > root = Tk() > w = Label(root, text="The BPM Counter") > w.pack() > > class display1: > def beat(): > beat = 0 > if beat > 10000: > beat += > > root.mainloop() You will need to __bind__ a callback to the key press on a widget. something like :- from Tkinter import * root=Tk() lab = Label(root, text = "Beat Counter : ") lab.pack() beats = 0 def beatCounter(event): print "increment counter" global beats beats = beats + 1 lab.config(text = "Beat Counter : %d" %beats) def beatReset(event): print "reset counter" global beats beats = 0 lab.config(text = "Beat Counter : %d" %beats) root.bind("", beatCounter) root.bind("", beatReset) root.mainloop() You should rewrite the above so it does not use the global statement ('cause thats cheating!) HTH Martin -- Martin Franklin From hans at zephyrfalcon.org Fri Dec 12 21:41:03 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 12 Dec 2003 21:41:03 -0500 Subject: Kinda newb-ish question In-Reply-To: References: <5c27220b.0312111650.7f0a128d@posting.google.com> Message-ID: <3FDA7C3F.7060505@zephyrfalcon.org> Harald Massa wrote: > File "C:\Python23\Prime Number.py", line 8, in -toplevel- > >>> q=x%y > > >>An infinite loop is probably not a good idea either. :-) > > > Why should it not be a good idea? Are there any ideas that the number of > primes is limited? > > :-) :-) No, but the program will never finish, which doesn't make it very useful except for staring at its output while eating tons of pretzels and listening to The Orb. -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From eugine_kosenko at ukr.net Tue Dec 2 17:35:13 2003 From: eugine_kosenko at ukr.net (=?windows-1251?b?xeLj5e3o6SDK7vHl7eru?=) Date: Wed, 3 Dec 2003 00:35:13 +0200 Subject: Python for web ? In-Reply-To: <20031201032949.GC19977@frobozz> References: <20031201031650.34627.qmail@web21301.mail.yahoo.com> <20031201032949.GC19977@frobozz> Message-ID: <200312030035.13893.eugine_kosenko@ukr.net> ? ????????? ?? 1 ??????? 2003 05:29 Andrew Bennetts ???????(a): > On Sun, Nov 30, 2003 at 07:16:50PM -0800, black wrote: > > Howdy everyone~ > > > > i heard Python could be used in web programming and aftering searching > > many docs just found something on Python and CGI. the fact is i know > > nothing about CGI and most of my projects(both of company and myself) > > are established with PHP and ASP. now the questions come: > > The answers are, in general, "yes". This URL might help you: > > http://www.python.org/cgi-bin/moinmoin/WebProgramming I also recommend to see mod_python. This is a powerful Apache module, for the transparent publishing of web pages like mod_php for Apache From whiteywidow at yahoo.com Mon Dec 8 23:58:36 2003 From: whiteywidow at yahoo.com (RT Lange) Date: Mon, 08 Dec 2003 23:58:36 -0500 Subject: Instance Exception Oddity: Implicit and Explicit not the same? References: Message-ID: On Sun, 07 Dec 2003 18:39:54 +0100, Peter Otten <__peter__ at web.de> wrote: > RT Lange wrote: > >>>>> class E1(Exception): pass >> >>>>> class E2(E1): pass >> >>>>> i = E2('foo') >>>>> raise E1(i) >> Traceback (most recent call last): >> File "", line 1, in ? >> raise E1(i) >> E1: foo >>>>> raise E1, i >> Traceback (most recent call last): >> File "", line 1, in ? >> raise E1, i >> E2: foo >>>>> >> >> Is there a reason the exception type is not the same? >> Is this behavior something that should be expected? > > This is interesting. I thought of > > raise E, o # 1 > > and > > raise E(o) # 2 > > as equivalent. Well, until today: > > "If the first object is a class, it becomes the type of the exception. > The > second object is used to determine the exception value: If it is an > instance of the class, the instance becomes the exception value. If the > second object is a tuple, it is used as the argument list for the class > constructor; if it is None, an empty argument list is used, and any other > object is treated as a single argument to the constructor. The instance > so > created by calling the constructor is used as the exception value." > > (quoted from http://www.python.org/doc/current/ref/raise.html) > > So, if isinstance(o, E), the first form is indeed equivalent to > > raise o > but if o is an instance of an E subclass (hence isinstance(o, E) is still true), shouldn't the first form raise an exception with type E (not E's subclass) and value o? -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From jjl at pobox.com Fri Dec 19 17:47:45 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Dec 2003 22:47:45 +0000 Subject: dynamic typing questions References: Message-ID: <87iskcwhke.fsf@pobox.com> "Robert Brewer" writes: > John Roth wrote: [...] > > Also, pervasive testing has so many other advantages > > that I'm beginning to think that debuggers were the > > single worst invention in history. > > Zuh? Unit testing doesn't replace a good debugger; they work together. > Unit testing can only show you THAT a test has failed--it can't show you > where, how, or why. Think of exception handling (and especially [...] But it can show you where and when and precisely how you broke something (or failed to get it working in the first place), while the change is still fresh in your mind. That encourages thinking about the cause of a bug rather than chasing after the details of what happened. John From sales at virtualkey.co.uk Mon Dec 1 22:03:12 2003 From: sales at virtualkey.co.uk (Virtualkey) Date: Tue, 2 Dec 2003 03:03:12 -0000 Subject: Website Design Message-ID: <4121656-2200312223312840@changeme> Dear Sir / Madam, I am writing to inquire as to whether you would be interested in our services. We offer Low-Cost High-Quality Website Design, Development and Hosting. We pride ourselves in the way we treat our customers. We can work with you to create a Website that you can be proud of, based on your design specifications and budget. Not only do our websites give you a great point of information for your staff and customers, they are also excellent revenue generators. To find out more about how we can help you, please visit http://www.virtualkey.co.uk or email sales at virtualkey.co.uk We can undertake any work, from Small Informative Websites through to Full E-Commerce Solutions. Whatever you want, we can provide a solution! Please feel free to email me directly at gary at virtualkey.co.uk to discuss your requirements. Regards Gary Sumpter Virtualkey www.virtualkey.co.uk gary at virtualkey.co.uk **************************************************************************************** we do not wish to inconvenience you with emails that are not relevant to you. If you received this email in error, or wish to be removed from our correspondence list, please send a blank email to remove at virtualkey.co.uk You will then be automatically removed. Thank you. **************************************************************************************** From bmgz at dev.null Sat Dec 13 05:38:29 2003 From: bmgz at dev.null (bmgz) Date: Sat, 13 Dec 2003 12:38:29 +0200 Subject: Tk -- stupid blank dialog opens up in background Message-ID: <3fdaec17.0@news1.mweb.co.za> I am just starting with python, I found it anoying that when I use Tk, a blank dialog always opens up behind tkMessageBox or whatever other gui element one executes.. Is their a way of disabling this? From http Fri Dec 26 18:57:36 2003 From: http (Paul Rubin) Date: 26 Dec 2003 15:57:36 -0800 Subject: Project dream References: Message-ID: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> hwlgw at hotmail.com (Will Stuyvesant) writes: > What would your favorite be? A CVS-like system for email. You'd receive all your messages on a server somewhere. You'd then be able to connect your laptop to the internet, download ("check out") your mail, and read and reply to it offline (not necessarily all of it). When you dial up again, the replies get sent out and stored ("checked in") on the server, the messages that you read get marked as read, the ones you didn't read don't get marked, etc. The CVS-like aspect is that you can do the same thing from your office computer, your friend's computer, etc., so you have the same messages checked out on multiple clients at the same time. The server automatically merges the "change sets" when you check any in. Finally, the server shouldn't need any special protocol to check messages in or out. It should be able to create a single tarball or zipfile that you download, and accept a single tarball or zipfile when you upload I've been wanting for a while to write something like this. Everyone I've mentioned it to wants to use it. I'm amazed it doesn't exist already, at least in any well-known form. From bokr at oz.net Mon Dec 29 04:08:19 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Dec 2003 09:08:19 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: On 29 Dec 2003 00:36:09 -0800, danb_83 at yahoo.com (Dan Bishop) wrote: >engsolnom at ipns.com wrote in message news:<6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com>... >> Hi, >> I've been using constructs(?) like the below. >> >> def display(instance, start = None, end = None): >> if instance.__class__.__name__ == 'UPCA': > >You might want to try the isinstance function. That's the usual idiom, but it should be noted that it's not exactly the same, e.g., >>> class A: pass ... >>> class B(A): pass ... >>> a=A(); b=B() >>> isinstance(a, A) True >>> isinstance(b, A) True >>> a.__class__.__name__ == 'A' True >>> b.__class__.__name__ == 'A' False That last, again, is not the same as >>> isinstance(b, A) True Regards, Bengt Richter From peter at engcorp.com Mon Dec 1 12:36:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Dec 2003 12:36:11 -0500 Subject: leftmost longest match (of disjunctions) References: Message-ID: <3FCB7C0B.D4B844AE@engcorp.com> Joerg Schuster wrote: > > The program given below returns the lines: > > a > ab > > Is there a way to use python regular expressions such that the program > would return the following lines? > > ab > ab > > ######################################################################## > > import re > > rx1 = re.compile("(a|ab)") > rx2 = re.compile("(ab|a)") Have you checked the documentation for "re"? It reads: "|" A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the "|" in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by "|" are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the "|" operator is never greedy. ------ Seems pretty clear and explicit to me. Your example is basically a working proof of the above code, so I'm not sure what you were expecting differently. -Peter From mrroach at okmaybe.com Fri Dec 12 12:34:50 2003 From: mrroach at okmaybe.com (Mark Roach) Date: Fri, 12 Dec 2003 17:34:50 GMT Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> <7xhe0781tc.fsf@ruckus.brouhaha.com> <3fd8f5bd$0$17127$626a54ce@news.free.fr> Message-ID: On Fri, 12 Dec 2003 00:12:45 +0100, Bruno Desthuilliers wrote: > You can build wxWindows with the free (as in free beer) Borland's bcc5.x > compiler, or with free (as in free beer and free speech) compilers like > Minwg's gcc. but not wxPython. You must use MSVC for compiling on Windows. However, unless you have patches or extensions to compile, the precompiled version should work just fine. -Mark From mark at mceahern.com Mon Dec 29 23:02:40 2003 From: mark at mceahern.com (Mark McEahern) Date: Mon, 29 Dec 2003 22:02:40 -0600 Subject: Question about packages In-Reply-To: References: Message-ID: <1072756960.27658.189.camel@dev.internal> On Mon, 2003-12-29 at 21:44, djw wrote: > So, the question is, how do you import into a sub-package to allow both > a script at the root level to import the module ("library mode") and for > the module itself to run in "test harness" mode with the same import? You could do something like: try: import X.modX1 except ImportError: if __name__ == '__main__': # Hmm, must be running the test harness, adjust # sys.path appropriately, then retry import import sys sys.path.insert(0, whatever) import X.modX1 but that smells. Maybe it's best to separate tests from code? Cheers, // m From vincent at visualtrans.de Wed Dec 10 11:53:36 2003 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 10 Dec 2003 17:53:36 +0100 Subject: Problems with interpreter References: Message-ID: "Boris Breidenbach" schrieb im Newsbeitrag news:slrnbteh8f.807.boris at rhodos.itap.physik.uni-stuttgart.de... | Hello! | | I recently switched from Python2.1, which was installed on my system, to | Pyhton2.3, which I compiled on my own and installed it in my $HOME. For some | reason the interpreter of Python2.3 does no longer recognize the arrow keys. | Instead of showing the last command on [ARROW UP], I get a strange escape | sequence ^[OA. Why does it behave like that? Did I miss a configure option? Your Python23 was probably compiled without readline... See http://groups.google.nl/groups?hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=87lluaeiy9.fsf%40pobox.com HTH Vincent Wehren | I would be grateful for any suggestion. | | Cheers, Boris | From eric.brunel at N0SP4M.com Mon Dec 8 04:30:13 2003 From: eric.brunel at N0SP4M.com (Eric Brunel) Date: Mon, 08 Dec 2003 10:30:13 +0100 Subject: how to display clock? References: <1cca69c7.0312070850.79db07ee@posting.google.com> Message-ID: Agency wrote: > I'm still working on the bpm counter. > > I need to have at least 2 displays that are not static. One would be a > clock/running time and the other would should the current beat count. > > How would I do this in Tkinter? I was thinkning of canvas-text, but > there must be a widget for doing this kind of display. I'm a bit lost > and would appreciate some help. What's your exact problem here? Is it a problem with the display itself or the fact that it is not static? As for the display itself, a simple label should be enough if you use its textvariable option to make changes to its text easier. If the problem lies in the dynamicity, here is a simple example showing how to display two dynamic displays at the same time using only Python and Tkinter: --clock-n-beat.py------------------------- from Tkinter import * ## Main window root = Tk() ## The tempo to use for the beat tempo = 90 ## Tkinter variables for clock and beat clockVar = IntVar() beatVar = IntVar() ## First beat in measure is 1 beatVar.set(1) ## This function will be called periodically to update the clock def clockPulse(): ## Increase clock value clockVar.set(1 + clockVar.get()) ## Call again current function in 1000 micro-seconds = 1 second root.after(1000, clockPulse) ## This function will be called periodically to update the beat def beatPulse(): ## Increase beat beat = beatVar.get() + 1 ## Assuming a 4/4 measure, wrap beat if it's too high if beat > 4: beatVar.set(1) else: beatVar.set(beat) ## Call again this function in the correct amount of micro-seconds ## depending on tempo root.after(int(60000.0 / tempo), beatPulse) ## Title and display for clock Label(root, text="Clock:").grid(row=0, column=0, sticky=W) Label(root, textvariable=clockVar).grid(row=0, column=1, sticky=W) ## Title and display for beat Label(root, text="Beat:").grid(row=1, column=0, sticky=W) Label(root, textvariable=beatVar).grid(row=1, column=1, sticky=W) ## Quit button Button(root, command=root.quit, text='Quit').grid(row=2, column=0, columnspan=2) ## Make sure the first calls to the functions updating the clock and beat ## will be made root.after(1000, clockPulse) root.after(int(60000.0 / tempo), beatPulse) ## Go! root.mainloop() ------------------------------------------ HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From p at trick.lu Mon Dec 8 11:45:22 2003 From: p at trick.lu (Patrick Useldinger) Date: Mon, 08 Dec 2003 17:45:22 +0100 Subject: OT: Spell checker References: Message-ID: On Sun, 7 Dec 2003 11:31:09 -0600, Jay Dorsey wrote: >Assuming ispell and aspell aren't viable for you I must admit I didn't know/find those. I'll have a look at ispell. Thanks. -PU -- visit my homepage at http://www.homepages.lu/pu/ From jacek.generowicz at cern.ch Tue Dec 9 12:00:25 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 18:00:25 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > Waitasec .... okay, I see what your problem is, assuming you're > describing it correctly. The problem is that you're calling Python > functions in an inner loop. ... indeedy ... > I think you're going to need to write a solution that doesn't call > functions (function unrolling, so to speak). Instead of returning a > memoizer function, just use a dict of dicts. Sounds interesting. But how do I get the dictionary to use the function which it is memoizing, to calculate values which haven't been cached yet? Hmm ... maybe by subclassing dict, I can add the necessary functionality ... but even then I don't see how to avoid wrapping the dictionary access in a function call ... and then we're back to square one. From exarkun at intarweb.us Wed Dec 17 14:17:52 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 17 Dec 2003 14:17:52 -0500 Subject: [Python-Dev] Re: rexec.py unuseable In-Reply-To: <20031217190652.GE2117@lkcl.net> References: <1071669397.3fe06095c9f3c@mcherm.com> <20031217190652.GE2117@lkcl.net> Message-ID: <20031217191752.GA5281@intarweb.us> On Wed, Dec 17, 2003 at 07:06:52PM +0000, Luke Kenneth Casson Leighton wrote: > [snip] > > i believe that it _is_ possible to express what nick coghlan > defines capabilities to be _into_ an ACL. > > how? > > by creating a security permission called "can you see it and execute it?" > let's call it SEE_AND_EXECUTE > > then, the language (interpreter) does this (following the example of the > SamrCreateUser function, above): > > MakeFunctionCall(Context *stack, CodeObject *code) > { > char *callee_fn_name = GetCalleeName(stack); > SEC_DES *sd = GetSecurityDescriptorForCode(code); > > /* check the capability to even _see_ this function! */ > if (!check_sec_des(sd, callee_fn_name, SEE_AND_EXECUTE)) > { > return Exception("Function name %s does not exist", > code->function_name); > } > > /* okay, they can see it [and execute it] */ > > .... > .... > > } > > does that make sense at all? > What appears to be missing here is the ability for a piece of code to take the existing permissions which it does posess and create new permissions within them. With the system you propose, if a function `foo' has permission to call function `bar', how does foo delegate that permission to `foobar'? If it cannot, then it becomes very difficult to write well factored code which can also exist within the security framework. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tomas.bouda at systinet.com Fri Dec 5 11:38:20 2003 From: tomas.bouda at systinet.com (Tobbi) Date: Fri, 5 Dec 2003 17:38:20 +0100 Subject: Object finalization Message-ID: <000c01c3bb4e$313c1450$6c00000a@in.idoox.com> Hi, I have a question about Python object finalization. I would like to be notified when an Object is deallocated. The problem is I would like to do it in C. The only way to register a finalizer I found out is to create a weak reference object and give it a callback. But the callback must be a Python function not C. That seems to be too difficult. Is there any (undocumented) way to do PyObject_RegisterFinalizer(PyObject *o, C-Callback-Func)? Thanks a lot. Best Regards, Tobbi -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Fri Dec 12 14:06:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Dec 2003 14:06:09 -0500 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> <3FD8C13F.6BC2B2DD@engcorp.com> <3fd8c97b$0$574$b45e6eb0@senator-bedfellow.mit.edu> <3FD9D3F9.2304606D@engcorp.com> Message-ID: <3FDA11A1.9F44C879@engcorp.com> Peter Hansen wrote: > > Brian Kelley wrote: > > > > When I said "why isn't > > there a .write(...) method for these widgets? Why can't I use a text > > widget like" that wasn't a specious Robin should do this > > for me question. It really was more like, is this a way a text widget > > should behave? > > That wasn't clear from the wording you used. Thanks for clarifying. :-) > It's a good question... I don't have the answer. And by the way, I do appreciate your efforts on KitViewer and such... apologies for the slight. -Peter From rchuso at aol.com Thu Dec 11 12:17:07 2003 From: rchuso at aol.com (rand c huso) Date: Thu, 11 Dec 2003 09:17:07 -0800 Subject: wbxml DOM for Wireless Village 1.1 Message-ID: <3FD8A693.5050202@aol.com> Does anybody have a library for encoding and decoding Wireless Village wbxml? I've found tools in Java, PERL, and C, but nothing for Python. thanks. rand. From andreif at mail.dntis.ro Tue Dec 23 15:54:39 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 23 Dec 2003 12:54:39 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> Message-ID: <21bb8d55.0312231254.4514d450@posting.google.com> Jp Calderone wrote in message news:... > On Tue, Dec 23, 2003 at 04:35:50AM -0800, Stormbringer wrote: > > Hi, > > > > I want to implement a fulltext search for messages in a forum. More > > exactly for each message I store pairs (wordId, msgId) for each > > identified word and when I search something I want to be able to > > retrieve very quickly all msgId for a given wordId. > > > > A pure Python fulltext indexer - http://divmod.org/Lupy/index.html Thanks ! This is exactly what I needed, and the size of the indexes is around 30%, much much less than what I could have achieved with my code. Not to mention the fact that I get phrase search and some other goodies :) The only thing that bothers me a little is the speed for building the index, I tried with around 5000 messages and I am not quite thrilled, it's not _extremly_ slow but it has to be faster for what I need. Perhaps I'll use the C++ version with some Python bindings. Cheers, Andrei From raims at dot.com Sun Dec 21 14:18:59 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 21 Dec 2003 20:18:59 +0100 Subject: Is anyone using Python for .NET? References: <02e201c3c758$f7707e20$2c00a8c0@eden> Message-ID: <87oeu2kmho.fsf@mobile.foo> Doveclaw writes: > One question, since I do not know much about .NET or it's reason to > exist.. How does it handle the gui/widgets? The MS .NET implementation has a GUI framework called Windows Forms which is essentially a wrapper around win32 APIs. See www.windowsforms.net for furthere infos. Mono (open source .NET implentation) has an alpha support for them since the only way to go is through wine emulation. Additionally, mono, provides GTK#, a GTK binding for C# language > Through its own libraries or > must you rely on what is made available to you by your chosen > programming language? No, the core programming model and one of the main features of dotNET is the indipendence of the framework from the language. You virtually can do the same things with C#, VB.NET, C++.NET, Eiffel.NET and Python .NET in the future. The only requirement is to adhere to the official standard (C# and the Common Language Interface of dotNET are ISO standards) and generate the same intermediate language. > I'm not sure how "open" .NET is intended to be, The openess of dotNET is not total but as I said above, some parts of it are covered by ISO standards. > support.) The alternative, through what was already provided by the > programming language would seemingly cut severely into attempts to be > open and portable since a good many systems for example, may not have > wxWindows, tk, or other popular alternatives in Python's case. The more portable way to go to code GUI things in dotNET today is to use GTK#. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From birdiepageANTI at SPAMciudad.FILTERcom.ar Wed Dec 17 10:07:01 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Wed, 17 Dec 2003 12:07:01 -0300 Subject: Standalone client database for Python? Message-ID: What are our options for a standalone (that is one that's not client/server) easily accesible from Python? I'm not going to ask for special features as this is only to see what is avaiable and used (most used most probably meaning well maintained project). Thanks in advance Gedece From grey at despair.dmiyu.org Sat Dec 20 16:19:55 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 20 Dec 2003 21:19:55 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On 2003-12-20, John Roth wrote: > It doesn't matter. As you can see by my reply to Bengt, > the crux of the issue is that, in Ruby, the function call > syntax is *optional.* There is no way to make it optional > in Python, and it is not clear whether it should be. It is quite clear. I, and others, have shown why several times. > What I'm missing, however, is any *thoughtful* > discussion of the issues involved. Your [perjoritive > adverb deleted] response makes it clear that you > didn't think of the issues, you just reacted. No, I didn't react and I have thought. Want to know my thinking? 5+ years of programming Perl professionally and being damned tired of trying to debug not only other people's code but even *my own code* which I wrote before I restricted myself to using as few implicit calls as I could get away with. I've gone on to argue against main implicit calls in various different languages in several different venues (here, Debian lists, in the workplace, in private discussions, etc) and provided examples why the ambiguity sets up the programmer, the program and the maintainer for problems down the road. Now just because you weren't around to see all of this or be in on any of it doesn't mean it didn't happen. Furthermore it also does not mean that every time some neophyte comes in throwing languages wishes which have been discussed at great length several times before that we have to engage in the same weeks long discussion AGAIN just for his sole benefit! No, we give concise examples on why that position is the way it is. That's what you got. You chose to ignore it. Instead of engaging in the valid points present you ignored them and flamed me. Bravo, way to get your point across. So until you can address these points I strongly suggest you not reply because the chances of you making any serious headway without addressing them is on you. Great thought HAS been put into them. So far no thought has apparently been put in your position. 1: Calling a function or method without parameters occurs far, far less than calling a function or method with parameters. This constitutes a special case. 2: Making the calling syntax optional creates ambiguity because one does not know if we're making an assignment to the function/method object or an assignment to the results of the function/method. 3: Making the calling syntax optional creates ambiguity for the maintainer since it muddles the visual difference between variables and function/method names. 4: Making the calling syntax optional dictates that to maintain functionality additional syntax need be created to address the case where one wants to assign to a function/method ojbect and not to the return of said object. 5: In doing all of the above we have now introduced multiple ways to do the same thing on 2 different occasions. The onus is on you to explain, given these statements that we Python programmers tend to like to adhere to... Explicit is better than implicit. Simple is better than complex. Special cases aren't special enough to break the rules. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. ...why the behavior is desireable when it is implicit, complex guess on a special case that introduces an additional way to do something which combined means the language is harder to read and maintian all so you can save two whole shifted keystrokes. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From frobozz_electric at hotmail.com Wed Dec 3 13:27:28 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 3 Dec 2003 18:27:28 GMT Subject: Newbee needs Help ref Using Function Statements not Loops(For) References: Message-ID: "jstreet10" wrote in message news:DLozb.41415$Ac3.27964 at lakeread01... > How would i use function statements instead of loops(for) in this code? i > have tried some, but not working. [snip] I'm sure someone else will ask you why you want to do it this way, since your code was already very clean and understandable, so I won't bother - I'll just show you one way that it can be done without for loops, and without list comprehensions (which use "for"). Someone else will probably show you the list comprehension version. # requires python 2.3+ import string input_file = open("grades.txt","r") records = input_file.readlines() input_file.close() commasplit = lambda record: string.split(record,",") record_items = map(commasplit, records) student_table = dict(record_items) grade_counter = len(records) # sum is a builtin in python 2.3 total = sum(map(int, student_table.values())) average = total/grade_counter student_names = student_table.keys() student_names.sort() output_file = open("processed.txt", "w") rebuild_info = lambda student_name: \ student_name +"," + student_table[student_name] student_info = map(rebuild_info, student_names) map(output_file.write, student_info) output_file.write("Average grade is " + str(average)) output_file.close() Perhaps I misunderstood what you were asking for with "function statements". Perhaps you wanted to define some functions of your own? Or maybe you were looking for some builtin functions that did this sort of processing? I'm not sure. Anyway, HTH, Sean p.s. Small note on your original code: > for record in input_file.readlines(): in later versions of python this can be written as for record in input_file: From alanmk at hotmail.com Mon Dec 8 08:26:02 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 08 Dec 2003 13:26:02 +0000 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: <3FD47BEA.8FAB8D67@hotmail.com> [David McNab] >>a framework which allows mountable linux filesystems to be >>implemented in pure python. [Rene Pijlman] > Serious question: why? One very serious usage that springs to mind is to implement a versioned virtual file system, in combination with a version control system like subversion (subversion.tigris.org). ClearCase (the versioning system) has the concept of such virtual file systems. You specify a view of the "Versioned Object Base" (VOB): the view is specified using dates/labels/revision numbers/etc, and is specified inside a "config spec" file. [1] Once you have specified your configspec, ClearCase creates a virtual file system, in which every file and directory actually resides inside the ClearCase VOB, so you are actually working directly on versioned files, even though your filesystem just looks like a plain ordinary file system: no special tools or techniques required. Subversion supports python fantastically well:- o Python scripts can be executed pre- and post-commit[2] o Python interfaces to all the important subversion libraries are available, through SWIG[3] It seems to me that David's work could be the last link in the chain to creating a complete VFS-based versioning system, using python and subversion. And that's just one idea that occurred to me: I'm sure that there are *plenty* of others. Nice one David! regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan [1] http://www.agsrhichome.bnl.gov/Controls/doc/ClearCaseEnv/v4.0doc/cpf_4.0/ccase_ux/ccdev/ccdev-6.html [2] http://svnbook.red-bean.com/html-chunk/ch05s02.html#svn-ch-5-sect-2.1 [3] http://svnbook.red-bean.com/html-chunk/ch07s02.html#svn-ch-7-sect-2.3 From skip at pobox.com Wed Dec 17 16:11:39 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Dec 2003 15:11:39 -0600 Subject: why are these exec times so different? In-Reply-To: References: Message-ID: <16352.50827.662296.38262@montanaro.dyndns.org> res> To show that what I'm seeing isn't because of local/global res> differences, here are dummy functions that exhibit the same res> behavior. (And I've tried to minimize os background activity, etc, res> when testing.) res> The results are consistently repeatable: For the given string s, res> f1(s) takes >10 times longer to run than f2(s) -- f1(s) and f2(s) res> return the same value, and contain essentially the same code, res> except that f2 calls function g to do the common inner loop: ... On my machine, f2 runs about twice as fast as f1. The only obvious difference I can see is that in f1 D grows to length 491678, while in g the dictionary D is always much smaller than that. The resizing cost of f1.D may outweigh the creation costs of all the smaller g.D instances. Here's a slightly modified version of your script which prints the distribution of g.D sizes (modulo 10) at the end of f2. Those which are very small won't need to be resized at all. A dictionary of length 490000 will have to be resized quite a bit. Also, the larger dictionary (depending on how the key hashing works) may incur a much larger number of collisions than the many smaller dictionaries, further decreasing performance. Skip def f1(s): """ do outer & inner loop """ D = {} for i in xrange(len(s)): for j in xrange(len(s)-i+1): D[s[j:j+i]] = True return len(D) def f2(s): """ same as f1, but call g to do inner loop """ count = 0 dsizes = {} for i in xrange(len(s)): c = g(s,i) n = dsizes.get(c%10, 0) + 1 dsizes[c%10] = n count += c print dsizes return count def g(s,i): """ the common inner loop """ D = {} for j in xrange(len(s)-i+1): D[s[j:j+i]] = True return len(D) def string01(n): """Return first n chars of a fixed pseudorandom string.""" random.seed(0) return ''.join([ random.choice('01') for i in xrange(n) ]) import random, time s = string01(1000) for func in (f1, f2): t0 = time.clock() count = func(s) t1 = time.clock() print func.func_name, count, t1-t0 From mcfletch at rogers.com Wed Dec 3 15:34:21 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 03 Dec 2003 15:34:21 -0500 Subject: diferences between 22 and python 23 In-Reply-To: <3FCE44AE.C415D6FA@engcorp.com> References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> Message-ID: <3FCE48CD.8010908@rogers.com> Peter Hansen wrote: >"Mike C. Fletcher" wrote: > > ... >>Which doesn't actually mention the breakage of code that results. True, >>theoretically the code was never valid, but *lots* of people used 8-bit >>encodings quite happily with earlier versions and do find their code >>breaking in 2.3 because of this. >> >> > >Wait a sec... are you telling me that my code, which has strings containing >binary data (which I believe has *always* been permitted), and which from >time to time might, say, produce an error traceback containing the content >from one such string and write it to a log file, then continue processing >safely, will now fail with an ugly crash because I haven't changed it to >specify a default encoding? (!!!) > > Yes, though as Fredrik points out, not just yet. For now you'll get a DeprecationWarning with 2.3. >I've been watching this "value XX with high bit set was never a valid 7-bit >ASCII" discussion with only one eye for quite some time now, somewhat curious >why so many people were having troubles. I assume it was merely that they >were using *names* that contained non-ASCII characters, in their source code. > >Are you saying that this change is actually breaking code that happens to >have these perfectly valid binary strings stored in string constants? > > AFAIK, that's the plan. IIRC, rationale was that there would be some other type for 8-bit data, while all "normal" strings would become Unicode strings. Of course, I've been known to catch fragments of conversations and read too much into them. For all I know, it may only be unicode literals that will be affected. Though I know some of my users were reporting DeprecationWarnings from resourcepackage, which doesn't do any Unicode at all (just stuffs binary data into string constants). >I'm very unimpressed with this decision if that's the case. > > Doesn't make me ecstatic, either, as I like the simple 8-bit-clean string type. But maybe we'll luck out and it will turn out that I'm all wet on this one :) . Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From davidb at mcs.st-and.ac.uk Thu Dec 4 14:49:19 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 4 Dec 2003 11:49:19 -0800 Subject: [ python-l ] scrolling a frame References: Message-ID: <4de76ee2.0312041149.6d73df28@posting.google.com> "Toph" wrote in message news:... > Hi, > > I am developing a software in Python using Tkinter. The choice of > my team is not to use pyton MegaWidgets. > I would like to scroll a frame. First of all, I recommend that you look at the following example. I found it to be very useful when addressing a similar problem: http://mail.python.org/pipermail/python-list/1999-October/013255.html Cutting and editing from now on... > This is a peace of my code : [...] > canvas = Canvas(global frame) Is that valid syntax? I'm not able to successfully use the "global" keyword in similar circumstances. > # My problem > is that i would like the scrollregion to scroll only the space taken by > > # the frame but my program does not do it well... Sorry not to address your exact problem. I haven't used Tkinter seriously for quite a while. Still, I hope that the above reference is of some use. David From adsl5lcq at tpg.com.au Sun Dec 14 01:02:30 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Sun, 14 Dec 2003 17:02:30 +1100 Subject: continue and break frustration References: <7xiskk6jhn.fsf@ruckus.brouhaha.com> Message-ID: On 13 Dec 2003 21:44:52 -0800, Paul Rubin wrote: >Glen Wheeler writes: >> I've been coding in python for a reasonable amount of time now >> (coding in total for approx. 20 years) and am writing a performance >> intensive program in python. >> The problem I'm having is I want to use break and continue to get >> out from more than one level of loop. If I set a variable and then >> check it my program will take too much of a performance hit. >> Are there any alternatives people can think of? > >Raise an exception and catch it. However, if your function is that >sensitive to a little thing like that, maybe you need to write it >differently, for example in Pyrex or as a C extension. You could >also try the Psyco compiler. I've been using the psyco compiler, and it does help (by about 60%). I'm trying to leave writing the function as a C extension as a last resort. I will try with exceptions (get it? :). To the people in the know, does adding this kind of construct detract from the speed of the code much? I do know that try+except can be slower than if+else if exceptions are generated more often than not, but how much slower? Thanks, Glen From alan.gauld at btinternet.com Wed Dec 31 13:07:32 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 31 Dec 2003 18:07:32 GMT Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> Message-ID: <3ff30f2f.674586974@news.blueyonder.co.uk> On Wed, 31 Dec 2003 09:48:07 -0500, "Aubrey Hutchison" wrote: > Why do we need to do some tinkering with IDLE if is a mature design? There > should never be a need for special names of program files for it to work > otherwise it requires tinkering. If you use any development tool to create a DLL called msvcrt.dll and save it in the wrong place then try to run your system you will find quite a few problems. Does that mean there are no mature development tools out there? Maybe by your definition of mature. But again to use your analogy if I put diesel in my car when its designed to run on unleaded gas it won't work. Users of development tools are expected to know some basics, users of cars are expected to know what fuel to use.... If you save your select.py in a place where Python/IDLE won't look for it then its OK but if you replace a system file then of course it won't work. That's not Python or IDLE's fault. > > >Save this simple single line program as "select.py" and try to run it. > > > > > >Then exit IDLE and try to restart IDLE. > > > > You might try renaming your module to something that is not a standard > > library module imported by IDLE itself... ;-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From tjreedy at udel.edu Sat Dec 6 14:18:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Dec 2003 14:18:44 -0500 Subject: How to use the outp(...) command References: <9b849915.0312060146.7630d752@posting.google.com> Message-ID: "Todd Gardner" wrote in message news:9b849915.0312060146.7630d752 at posting.google.com... > I think all I have to do is figure out how to use the outp(...) > command. Python itself does not have such a command. Is there something in standard lib? > This is my first project in python and it seems a bit daunting. I am > trying to communicate to a custom device via the parallel port. At > this point I only want to write data to the data port. In my case the > memory address is x378. Python itself is, generally, unaware of 'memory addresses'. > I installed: Python 2.2, giveio_setup.exe and > pyparallel-0.1.win32-py2.2.exe. I was running Python2.3 but I don't > think that it will matter for this newbie project. Perhaps giveio... and pyparallel... (which I don't remember any clp mention of before today) have outp() and one of the docs will tell you more about how to use it. TJR From mir4uu at yahoo.com Fri Dec 19 02:48:18 2003 From: mir4uu at yahoo.com (mir nazim) Date: 18 Dec 2003 23:48:18 -0800 Subject: HELP: zipped html vresion of zope book Message-ID: <425cc8d1.0312182348.c2ad3ec@posting.google.com> hi, i have just started out with zope. i downloaded pdf version of zope book from zope.org. but the print quality is so bad that it is a hell to read it. especially the code samples and figures is very unreadable. it would be very helpful if anybody could point me to a downloadable html version(zip,tar,bz,bz2 stc). thanks in advance. blesses-n-luck From jjl at pobox.com Mon Dec 1 09:17:11 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Dec 2003 14:17:11 +0000 Subject: SGMLParser eats ä etc References: Message-ID: <87oeussjvc.fsf@pobox.com> Eric Brunel writes: > Anders Eriksson wrote: > > Hello! > > I'm using smgllib (ActivePython 2.3.2, build 230) and I have some [...] > So there are two solutions: > - either your document is HTML, and you should use an HTML parser as > it was already suggested > - or your document is not HTML, and you should define all entities you > may use in your DTD. This is done for example with: [...] sgmllib only really does HTML. John From usenet at soraia.com Fri Dec 5 04:02:13 2003 From: usenet at soraia.com (Joe Francia) Date: Fri, 05 Dec 2003 09:02:13 GMT Subject: Lists and Tuples In-Reply-To: References: Message-ID: Jeff Wagner wrote: > I've spent most of the day playing around with lists and tuples to get a really good grasp on what > you can do with them. I am still left with a question and that is, when should you choose a list or > a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it > than just that. Everything I tried with a list worked the same with a tuple. So, what's the > difference and why choose one over the other? > According to the Python FAQ: ------------------------------------------------------------------------ 4.15 Why are there separate tuple and list data types? Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, os.listdir('.') returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory. Tuples are immutable, meaning that once a tuple has been created, you can't replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list's elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys. http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types ------------------------------------------------------------------------ Of course, this information will prevent neither flame wars, nor you from using them how you wish (within the boundaries of the language). However you choose to use them, just be clear and consistent. Peace, Joe From lists at webcrunchers.com Mon Dec 15 19:07:31 2003 From: lists at webcrunchers.com (JD) Date: Mon, 15 Dec 2003 16:07:31 -0800 Subject: Terminal "hang up" problem In-Reply-To: <9eabe547.0311131610.4dd7819c@posting.google.com> References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: What is the best way to debug a Python program if when i run it, it totally hangs up the terminal console. Control-c or control-d has NO effect, so it's hung up somewhere, but we have no idea where. We are using Python 2.3, on an openBSD box, running the python script from the shell. Is it possible to somehow find out what is making it hang up? From gh at ghaering.de Thu Dec 4 09:33:54 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2003 15:33:54 +0100 Subject: Simple newbie question In-Reply-To: <20031204153611.7939a260.secchi@sssup.it> References: <20031204153611.7939a260.secchi@sssup.it> Message-ID: <3FCF45D2.4000800@ghaering.de> Angelo Secchi wrote: > Hi, > I'm trying to remove lines with zeros from a list "lista". > The code i'm using is the following: > > for line in lista: > if sum(line == 0) > 0: > lista.remove(line) > > > The problem is that the loop stops at the first line with zeros and it > doesn't remove the other lines with zeros (at least if I do not re-run > the loop). Probably I do not understand how the loop works. Two problems here: 1) Don't modify lists while looping over them. Instead, build a new temporary list. Something like: # l is the original list, tmp_l is the temporary list tmp_l = [] for line in l: if {some condition}: tmp_l.append(line) # Now bind l to the modified list: l = tmp_l 2) "if sum(line ==0) > 0" most probably doesn't do what you want it to do. Hint: "line == 0" is a boolean expression that will return either True or False (or 1 and 0, in older Python versions). -- Gerhard From lyle at users.sourceforge.net Tue Dec 30 09:55:00 2003 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Tue, 30 Dec 2003 08:55:00 -0600 Subject: Programming language from python In-Reply-To: <3ff14d10$0$317$e4fe514c@news.xs4all.nl> References: <3ff14d10$0$317$e4fe514c@news.xs4all.nl> Message-ID: <3FF191C4.3020602@users.sourceforge.net> Irmen de Jong wrote: > Alejandro Lombardo wrote: > >> Is python the best computer programming language development tool in >> the entire universe? If it isn?t could you please tell me the name of >> the best computer programming language development tool in the entire >> universe? > > While Python approaches this almost, I believe the Sqiwrnsyivstblz++ > toolkit, available on the third rock circling Betelgeuse, > is highly superior at the moment. I hear that the port of Sqiwrnsyivstblz++ for the .NET platform (named "Sqiwrnsyivstblz++#") is even better. From fredrik at pythonware.com Mon Dec 8 09:00:19 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 15:00:19 +0100 Subject: Problem installing gadfly on Mandrake 9.2 References: <8a27e309.0312080551.331fb053@posting.google.com> Message-ID: "R.Marquez" wrote: > I tried installing gadfly 1.0 on Mandrake 9.2 and got the following: > > [root at localhost gadfly-1.0.0]# python setup.py install > running install > error: invalid Python installation: unable to open > /usr/lib/python2.3/config/Makefile (No such file or directory) > [root at localhost gadfly-1.0.0]# > > Of course, the error is correct in that there is no such file. There > is not even a python2.3/ config directory. Is the Mandrake > installation of 2.3 cripled? I have gadfly working fine with Python > 2.3 on Windows. > > If someone has any pointers or tips they will be much appreciated. make sure you've installed the python-devel package. From ddubin at lindev.isrl.uiuc.edu Wed Dec 3 10:51:49 2003 From: ddubin at lindev.isrl.uiuc.edu (ddubin) Date: 03 Dec 2003 09:51:49 -0600 Subject: SGMLParser eats ä etc References: <87he0mn0c7.fsf@pobox.com> <19cbe1rfd2rx$.dlg@amez.homeip.net> Message-ID: Anders Eriksson writes: > the strange thing is that the Character entity (i.e. å) is > stripped from the text. I don't want to change it since I'm feeding > the output to a browser. Inconvenient for you, but not strange. An SGML parser is supposed to expand general entity references. > I will try the HTMLParser instead but it seems to me that there is a > bug in SMGLParser... No, it's consistent with the standard that the entity reference disappears. The question is what replacement text has been put in its place, and why can't you see it? Dave Dubin From miki.tebeka at zoran.com Wed Dec 24 10:22:22 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 24 Dec 2003 07:22:22 -0800 Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: <4f0a9fdb.0312240722.5ae49169@posting.google.com> Hello Michael, > > On my cygwin installation the libpython2.3.dll goes from 2.9MB to > > 1.1MB. On machines with little RAM (embdded ...) this matters a lot. > > Oh sure, but if you're in an embedded situation, I would *hope* that > you don't just blindly use the default compile options! Just toying with the idea... Miki From wade at lightlink.com Tue Dec 30 18:39:47 2003 From: wade at lightlink.com (Wade Leftwich) Date: 30 Dec 2003 15:39:47 -0800 Subject: Newbie: sort list of dictionaries References: <7xy8su7a1k.fsf@ruckus.brouhaha.com> Message-ID: <5b4785ee.0312301539.461467e7@posting.google.com> D'oh! That sortlist() function was needlessly clever. This is nicer: >>> def sortlist(L, decorator=None): ... if decorator is None: ... L.sort() ... return ... newL = [(decorator(x), x) for x in L] ... newL.sort() ... L[:] = [y for (x,y) in newL] From mwh at python.net Thu Dec 4 11:40:38 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Dec 2003 16:40:38 GMT Subject: Why 'string' functions i.e. rstrip, upper, lower are 'not found'......... References: <2c82369d.0312040836.7374c789@posting.google.com> Message-ID: John_Dutcher at urmc.rochester.edu (John F Dutcher) writes: > There must be a 'fundamental' reason why 'string' functions are > reported as 'not found' even though the 'import string' statement > is present. If the script has user-defined functions at its beginning > and I remove them...doing all code inline, the 'not found' error goes away. > Is there some 'placement of user functions' issue that explains why > the 'import string' doesn't make the various string functions visible > when I use various 'def userfunc's in the script ?? If you do >>> import string to get at, eg, maketrans, you need to do >>> string.maketrans Cheers, mwh -- One of the great skills in using any language is knowing what not to use, what not to say. ... There's that simplicity thing again. -- Ron Jeffries From steve at ferg.org Fri Dec 26 12:11:33 2003 From: steve at ferg.org (Stephen Ferg) Date: 26 Dec 2003 09:11:33 -0800 Subject: ANN: Python Language Reference Message-ID: An attempt to produce a complete, alphabetized reference of all of Python's language features. The purpose is support developers, who need a quick way to look up information about a language feature. The table of contents was extracted from: * the index of the language reference * the index of the library reference * the global module index http://www.ferg.org/pyref/index.html From tchur at optushome.com.au Tue Dec 16 13:51:10 2003 From: tchur at optushome.com.au (Tim Churches) Date: 17 Dec 2003 05:51:10 +1100 Subject: Zen of ... In-Reply-To: <20031216183852.GA4318@nl.linux.org> References: <20031216183852.GA4318@nl.linux.org> Message-ID: <1071600670.1207.3.camel@emilio> On Wed, 2003-12-17 at 05:38, Gerrit Holl wrote: > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! > > Hi, shouldn't the Zen of Python really be called the Zen of Programming? It is entirely possible to do programming in Perl, but the results bear little resemblance to these desiderata. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From fumanchu at amor.org Sat Dec 6 16:15:45 2003 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 6 Dec 2003 13:15:45 -0800 Subject: list.sorted() Message-ID: On python-dev, Raymond Hettinger wrote: > When working on itertools.groupby(), the tutorial updates, and > exercising the newer features, I've made frequent use of > list.sorted(). ... > Part of the reason for making it a classmethod was that it *is* > effectively an alternative constructor for lists. OTOH, that could be > said for any function that returns a list. > > The two disadvantages of having it as a classmethod are the mandatory > list dot prefix and that it is confusing when called with an existing > list: > > [f(elem, arg) for elem in [3,2,1].sorted(anotherseq)] My question for python-list is: I've been looking through my code and can't find a single case where I declared a classmethod, then called it from an instance, as in the above example. Are there any cases where this is useful? Notice that the reverse is not true: you can't call normal instance methods from the class--you get a TypeError by not passing an instance for "self" to bind to. If nobody can come up with one, perhaps classmethods shouldn't be callable from instances. IMO, that's the root of the "confusion" in the example. Robert Brewer MIS Amor Ministries fumanchu at amor.org From sillyfaith at hotmail.com Tue Dec 9 02:23:01 2003 From: sillyfaith at hotmail.com (Faith) Date: 8 Dec 2003 23:23:01 -0800 Subject: popen Message-ID: <36153c56.0312082323.67249ea@posting.google.com> hi all, I am trying to run a batch file from my python program, in the end of the batch file I call a command called creterelease but for some reason its not being executed.. I know there is nothing wrong with the bacthfile cause it worked fine when I run it from the command line .. so if anyone knows about why could that be happenning please let me know.. by the way I tried to use system and the othe popen version and I still got nothing.. well ... hope you can help.. thanks, Faith From nessus at mit.edu Fri Dec 5 02:48:40 2003 From: nessus at mit.edu (Douglas Alan) Date: Fri, 05 Dec 2003 02:48:40 -0500 Subject: Python's simplicity philosophy References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: BW Glitch writes: > Douglas Alan wrote: >> C'mon -- to make robust programs you have to assume the worst-case >> scenario for your data, not the best case. I certainly don't want >> to write a program that runs quickly most of the time and then for >> opaque reasons slows to a crawl occasionally. I want it to either >> run quickly all of the time or run really slowly all of the time >> (so that I can then figure out what is wrong and fix it). > In theory, I'd agree with you Douglas. But IRL, I agree with > Alex. If I have to choose between two algorithms that do almost the > same, but one works on an special case (that's very common to my > range) and the other works in general, I'd go with the special > case. There is no compelling reason for getting into the trouble of > a general approach if I can do it correctly with a simpler, special > case. When people assert that reduce(add, seq) is so much harder to use, read, or understand than sum(seq) I find myself incredulous. People are making such claims either because they are sniffing the fumes of their own righteous argument, or because they are living on a different planet from me. On my planet, reduce() is trivial to understand and it often comes in handy. I find it worrisome that a number of vocal people seem to be living on another planet (or could use a bit of fresh air), since if they end up having any significant influence on the future of Python, then, from where I am standing, Python will be aimed at aliens. While this may be fine and good for aliens, I really wish to use a language designed for natives of my world. Reasonable people on my world typically seem to realize that sum() is just not useful enough that it belongs being a built-in in a general-purpose programming language that aims for simplicity. This is why sum() occurs rather infrequently as a built-in in general purpose programming languages. sum(), however, should be in the dictionary as a quintessential example of the word "bloat". If you agree that sum() should have been added to the language as a built-in, then you want Python to be a bloated language, whether you think you do, or not. It is arguable whether reduce() is useful enough that it belongs as a built-in, but it has many more uses than sum(), and therefore, there's a case for reduce() being a built-in. reduce() may carry the weight of its inclusion, but sum() certainly does not. > One example. I once wrote a small program for my graphic calculator to > analyze (rather) simple electrical networks. To make the long story > short, I had two approaches: implement Gaussian Elimination "purely" (no > modifications to take into account some nasty problems) or implement it > with scaled partial pivoting. Sure, the partial pivoting is _much_ > better than no pivoting at all, but for the type of electrical networks > I was going to analyze, there was no need to. All the fuzz about > pivoting is to prevent a small value to wreck havoc in the calculations. > In this *specific* case (electric networks with no dependent sources), > it was impossible for this situation to ever happen. > Results? Reliable results in the specific range of working, which is > what I wanted. :D You weren't designing a general purpose programming language -- you were designing a tool to meet your own idiosyncratic needs, in which case, you could have it tap dance and read Esperanto, but only on second Tuesdays, if you wanted it to, and no one need second guess you. But that's not the situation that we're talking about. >>> [Alex Martelli:] Me too! That's why I'd like to make SURE that >>> some benighted soul cannot code: >>> onebigstring = reduce(str.__add__, lotsofstrings) >> The idea of aiming a language at trying to prevent people from >> doing stupid things is just innane, if you ask me. It's not just >> inane, it's offensive to my concept of human ability and >> creativity. Let people make their mistakes, and then let them >> learn from them. Make a programming language to be a fluid and >> natural medium for expressing their concepts, not a straight-jacket >> for citing canon in the orthodox manner. > It's not about restraining someone from doing something. It's about > making it possible to *read* the "f(.)+" code. A language should make it *easy* to write readable code; it should not strive to make it *impossible* to write unreadable code. There's no way a language could succeed at that second goal anyway, and any serious attemtps to accomplish that impossible goal would make a langauge less expressive, more bloated, and would probably even end up making the typical program less readable as a consequence of the language being less expressive and more complex. > Human ability and creativity are not comprimised when restrictions > are made. That would depend on the restrictions that you make. Apparently you would have me not use reduce(), which would compromise my ability to code in the clear and readable way that I enjoy. > In any case, try to program an MCU (micro-controller unit). Python's > restrictions are nothing compared with what you have to deal in a > MCU. I'm not sure what point you have in mind. I have programmed MCU's, but I certainly didn't do so because I felt that it was a particularly good way to express the software I wished to compose. >> Furthermore, by your argument, we have to get rid of loops, since >> an obvious way of appending strings is: >> result = "" >> for s in strings: result += s > By your logic, fly swatters should be banned because shotguns are > more general. That's not my logic at all. In the core of the language there should be neither shotguns nor fly-swatters, but rather elegant, orthogonal tools (like the ability to manufacture interchangable parts according to specs) that allow one to easily build either shotguns or fly-swatters. Perhaps you will notice, that neither "shotgun" nor "fly-swatter" is a non-compound (i.e., built-in) word in the English language. > :S It's a matter of design decisions. Whatever the > designer thinks is better, so be it (in this case, GvR). Of course it is a matter of design decisions, but that doesn't imply that all the of design decisions are being made correctly. > At least, in my CS introductory class, one of the things we learned > was that programming languages could be extremely easy to read, but > very hard to write and vice versa Or they can be made both easy to read *and* easy to write. >> You are correct, sorry -- I misunderstood your proposed extension. >> But max() and min() still have all the same problems as reduce(), and >> so does sum(), since the programmer can provide his own comparison >> and addition operations in a user-defined class, and therefore, he can >> make precisely the same mistakes and abuses with sum(), min(), and >> max() that he can with reduce(). > It might still be abused, but not as much as reduce(). But > considering the alternative (reduce(), namely), it's *much* better > because it shifts the problem to someone else. We are consenting > adults, y'know. Yes, we're consenting adults, and we can all learn to use reduce() properly, just as we can all learn to use class signatures properly. >>> So, you're claiming that ALL people who were defending 'reduce' by >>> posting use cases which DID "abuse this generality" are >>> unreasonable? >> In this small regard, at least, yes. So, here reduce() has granted >> them the opportunity to learn from their mistakes and become better >> programmers. > Then reduce() shouldn't be as general as it is in the first place. By that reasoning, you would have to remove all the features from the language that people often use incorrectly. And that would be, ummm, *all* of them. >> And Python suits me fine. But if it continues to be bloated with a >> large number special-purpose features, rather than a small number of >> general and expressive features, there may come a time when Python >> will no longer suit me. > reduce() ... expressive? LOL. I'll grant you it's (over)general, but > expressive? Hardly. You clearly have something different in mind by the word "expressive", but I have no idea what. I can and do readily express things that I wish to do with reduce(). > It's not a bad thing, but, as Martelli noted, it is > overgeneralized. Not everyone understand the concept off the bat (as > you _love_ to claim) and not everyone find it useful. If they don't find it useful, they don't have to use it. Many people clearly like it, which is why it finds itself in many programming languages. > What I understand for simplicity is that I should not memorize anything > at all, if I read the code. There's no way that you could make a programming langauge where you don't have to memorize anything at all. That's ludicrous. To use any programming language you have to spend time and effort to develop some amount of expertise in it -- it's just a question of how much bang you get for your learning and memorization buck. > That's one of the things I absolutely hate > about LISP/Scheme. You have to remember a hell of lot more to understand Python code than you do to understand Scheme code. (This is okay, because Python does more than Scheme.) You just haven't put in the same kind of effort into Scheme that you put into Python. For instance, no one could argue with a straight face that seq[1:] is easier to learn, remember, or read than (tail seq) > Now, what's so hard about sum()? There's nothing hard about sum() -- it's just unneccessary bloat that doesn't do enough to deserve being put into the language core. If we put in sum() in the language core, why not quadratic_formula() and newtons_method(), and play_chess()? I'd use all of those more frequently that I would use sum(). The language core should only have stuff that gives you a lot of bang for the buck. sum() doesn't. >> That's because I believe that there should be little distinction >> between features built into the language and the features that users >> can add to it themselves. This is one of the primary benefits of >> object-oriented languages -- they allow the user to add new data types >> that are as facile to use as the built-in data types. > _Then_ let them *build* new classes to use sum(), min(), max(), > etc. These functionality is better suited for a class/object in an > OO approach anyway, *not* a function. No, making new classes is a heavy-weight kind of thing, and every class you define in a program also should pay for its own weight. Requiring the programer to define new classes to do very simple things is a bad idea. >>> and you claimed that reduce could be removed if add, mul, etc, would >>> accept arbitrary numbers of arguments. This set of stances is not >>> self-consistent. >> Either solution is fine with me. I just don't think that addition >> should be placed on a pedestal above other operations. This means that >> you have to remember that addition is different from all the other >> operations, and then when you want to multiply a bunch of numbers >> together, or xor them together, for example, you use a different >> idiom, and if you haven't remembered that addition has been placed on >> this pedestal, you become frustrated when you can't find the >> equivalent of sum() for multiplication or xor in the manual. > Have you ever programmed in assembly? It's worth a look... Yes, I have. And I've written MCU code for microcontrollers that I designed and built myself out of adders and other TTL chips and lots of little wires. I've even disassembled programs and patched the binary to fix bugs for which I didn't have the source code. > (In case someone's wondering, addition is the only operation available > in many MPU/MCUs. Multiplication is heavily expensive in those that > support it.) If your point is that high-level languages should be like extremely low level languages, then I don't think that you will find many people to agree with that. >>>The point is that the primary meaning of "reduce" is "diminish", and >>>when you're summing (positive:-) numbers you are not diminishing >>>anything whatsoever >> Of course you are: You are reducing a bunch of numbers down to one >> number. > That make sense if you are in a math related area. But for a layperson, > that is nonsense. It wasn't nonsene to me when I learned this in tenth grade -- it made perfect sense. Was I some sort of math expert? Not that I recall, unless you consider understanding algebra and geometry to be out of the realm of the layperson. >> Yes, I taught a seminar on Python, and I didn't feel it necessary >> to teach either sum() or reduce(). I taught loops, and I feel >> confident that by the time a student is ready for sum(), they are >> ready for reduce(). > But why didn't you teached reduce()? If it were so simple, it > was a must in the seminar. I did teach lamda in the seminar and no one seemed to have any difficulty with it. I really couldn't fit in the entire language in one three-hour seminar. There are lots of other things in the language more important than reduce(), but *all* of them are more important thhan sum(). > Now in a more serious note, reduce() is not an easy concept to > grasp. That's why many people don't want it in the language. The > middle land obviously is to reduce the functionality of reduce(). That's silly. Reducing the functionality of reduce() would make it *harder* to explain, learn, and remember, because it would have to be described by a bunch of special cases. As it is, reduce() is very orthogonal and regular, which translates into conceptual simplicity. > You mention here "general-purpose programming". The other languages > that I have done something more than a small code snippet (C/C++, Java > and PHP) lack a reduce()-like function. Lots of languages don't provide reduce() and lots of languages do. Few provide sum(). Higher-order functions such as reduce() are problematic in statically typed langauges such as C, C++, or Java, which may go a long way towards explaining why none of them include it. Neither C, C++, or Java provide sum() either, though PHP provides array_sum(). But PHP has a huge number of built-in functions, and I don't think that Python wishes to go in that direction. >> You have to educate people not to do stupid things with loop and sum >> too. I can't see this as much of an argument. > After reading the whole message, how do you plan to do *that*? You put a line in the manual saying "As a rule of thumb, reduce() should only be passed functions that do not have side-effects." > The only way to effectively do this is by warning the user > explicitly *and* limiting the power the functionality has. Is this the only way to educate people not to abuse loops? I didn't think so. > As Martelli said, APL and Numeric does have an equivalent to > reduce(), but it's limited to a range of functions. Doing so ensures > that abuse can be contained. Doing so would make the language harder to document, remember, and implement. >> You hardly need a zillion warnings. A couple examples will suffice. > I'd rather have the warnings. It's much better than me saying "How > funny, this shouldn't do this..." later. Why? Because you can't > predict what people will actually do. Pretending that most people > will act like you is insane. If the day comes where Python starts telling me that I used reduce() incorrectly (for code that I have that currently works fine), then that is the last day that I would ever use Python. > Two last things: > 1) Do you have any extensive experience with C/C++? (By extensive, I > mean a small-medium to medium project) Yes, quite extensive. On large projects, in fact. > These languages taught me the value of -Wall. There are way too many > bugs lurking in the warnings to just ignore them. I don't use C when I can avoid it because I much prefer C++. C++'s strong static type-checking is very helpful in eliminating many bugs before the code will even compile. I find -Wall to be useless in the C++ compiler I typically use because it will complain about all sorts of perfectly okay things. But that's okay, because usually once I get a progam I write in C++ to compile, it typically has very few bugs. > 2) Do you have any experience in the design process? Yes, I design and implement software for a living. |>oug From doeringm at gmx.de Tue Dec 2 09:55:22 2003 From: doeringm at gmx.de (Martin Doering) Date: Tue, 02 Dec 2003 15:55:22 +0100 Subject: un-tuple (newbie) References: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> Message-ID: On Tue, 02 Dec 2003 14:09:54 +0100, Peter Otten <__peter__ at web.de> wrote: >Martin Doering wrote: > >> I could find out, how to create a tuple with just one member, but I >> can not find out how to get a value from a tuple with just one member. >>... > >You already got the above solution. Here is another one: > >>>> item, = tpl >>>> item >'first item' Cool. And I don't find it too ugly. You just see the ',' and know, that it is a sequence. Sound's logical, even if it is just one item. -- Martin From tzot at sil-tec.gr Tue Dec 9 01:29:03 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 09 Dec 2003 08:29:03 +0200 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: On 08 Dec 2003 23:08:22 -0500, rumours say that Nick Vargish might have written: >> Serious question: why? > >How about providing a selection of ways of accessing an mp3 >collection? At the top level you could have /artist, /album, /genre, >/year... And suppose the mp3 files are spread over many computers in the local network... perhaps the vfs could substitute a file of momentary silence for every song not available at the moment, so that you never have to change the playlist... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From gnari at simnet.is Sat Dec 20 15:45:56 2003 From: gnari at simnet.is (Ragnar Hafstað) Date: Sat, 20 Dec 2003 20:45:56 -0000 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: "Xah Lee" wrote in message news:7fe97cc4.0312201204.7accda32 at posting.google.com... > i have a bunch of java files that has spaced-out formatting that i > want to get rid of. I want to replace two end of line characters by > one end of line characters. The files in question is unix, and i'm > also working under unix, so i did: > > perl -pi'*~' -e "s@\n\n@\n at g" *.java > > but this to no avail. > snipped long rant about perldocs the problem is not your understanding of regular expressions, but rather that you are forgetting what -p does you are applying the -e commands to each line of input in turn before printing it. no line of the input contained \n\n as then they would not have been ONE line. now, to do what you want, try: perl -0 -pi'*~' -e 's@\n\n@\n at g' *.java From swalters_usenet at yahoo.com Wed Dec 31 00:28:08 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Wed, 31 Dec 2003 05:28:08 GMT Subject: Graceful failures References: <85b54e91.0312291414.6e61e535@posting.google.com> Message-ID: On Mon, 29 Dec 2003 14:14:43 -0800, Jacob H wrote: > I'm somewhat reluctant to write a bunch of code for pretty windows that > pop up with some message to the effect of, "internal error, game > exiting." My main reservation here is it doesn't seem it can be done > cross platform, and since my game is in a graphical console there's no > place for stdout to write. However, if this is the best way to go about > error handling, I'm willing to write the code. And I would appreciate > advice about how to handle the cross platform problem. :) I can't speak for any "canonical" way of doing things, but I do have some thoughts on the matter from my experience in customer service and some computer tutoring I used to do. Maybe they can be of some use to you. Forgive me as I ramble for a minute, but I haven't spent time collecting these thoughts. Most computer users react to error messages with fear and panic. They feel like the computer is telling that *they* have done something wrong. This misconception is compounded by the generally unintelligible error messages thrown by most programs. Computers have a way of making even some of the most intelligent people feel stupid. The second most common type of user understands that they didn't necessarily do anything wrong, and just wishes the program would work. They might thumb through the manual to see if it has anything on the matter. If they are given an obvious way to find a solution to the problem, they will take it, but they generally won't work that hard. The rest of us will dig in and try to solve the problem. This could be anything from using google, to posting on usenet, to reading a disassembly of the core dump. My "dream error dialog box" would do the following: Tell the user in a very neutral and nontechnical manner that it has encountered a problem and tell the user what it was trying to do when it failed. for instance: """ Foo has encountered a problem. Foo was unable to load the necessary images to continue. """ The program should avoid words like "error." You might consider having the program keep a stack of descriptions of what it's trying to accomplish at any given moment. That allows you to differentiate between being unable to open the configuration file with the intent of initially loading the configuration and opening the configuration file with the intent of reverting to original settings. Next, tell the user whether or not they can continue and what some of the consequences of continuing might be. The error dialog box should allow the user the option of viewing technical details, but should clearly label them as technical details. If possible, the user should be presented with possible courses of action to correct the problem. Finally, I really, really wish that users were presented with the option of being automagically taken to the technical support website where they're allowed to see and discuss with others how to solve their particular problem. This is where I get a little bit hazy in my ideas. I envision a website/forum where a user can read and discuss possible solutions to their problem *and* similar problems. The proper web page could be located from the stack trace. If they're the first one to encounter that particular stack trace, then tell them that they're the first, politely ask them to describe the problem (even if the description's useless to you, it makes the user feel included) and tell them that your development staff has been notified and will be making contact with them soon. Offer to keep them updated via email when other people post about having the same problem. This type of system could be very useful to your development team and tech support staff by allowing you to identify, track and fix the real life errors that your users are encountering. anyways... HTH Sam Walters P.S. If you haven't already, look at the Interface Hall of Shame to see what *not* to do: http://digilander.libero.it/chiediloapippo/Engineering/iarchitect/shame.htm From parken at ferger.de Sun Dec 21 03:08:19 2003 From: parken at ferger.de (Olaf Ferger) Date: Sun, 21 Dec 2003 09:08:19 +0100 Subject: Module for Informix Database? References: Message-ID: <2hkauv80a1dg6682vcvmr88b1n3e63e6iq@4ax.com> Jan Kesten wrote: >So if you still know, how you got "informixdb" to work with Python 2.x >please let me know. I did it a year ago. I'll try to reproduce it one of these days and tell you the results. Regards, Olaf -- EOP From mike at nospam.com Thu Dec 11 20:41:08 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 11 Dec 2003 17:41:08 -0800 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: John Roth wrote: >> Some who I suspect know a thing or two about python and .NET seem to >> disagree: >> >> http://primates.ximian.com/~miguel/activity-log.php Read only that http://primates.ximian.com/~miguel/archive/2003/Dec-09.html > This is real good news, but the fact that it's only at 0.1 makes me > suspect that they might find some real issues later that will slow > things down. But then, I'm old and cynical. >From that benchmark I conclude Iron shall be compared with psyco, not CPython. Mike From donn at drizzle.com Sun Dec 14 00:47:26 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 14 Dec 2003 05:47:26 -0000 Subject: "Do this, and come back when you're done" References: <1071338254.885587@yasure> <7xsmjojuc6.fsf@ruckus.brouhaha.com> Message-ID: <1071380844.471267@yasure> Quoth Paul Rubin : ... | Can the remote process time out if the local side takes too long to | read from the socket? That could happen if the two machines aren't | the same speed. I wouldn't expect so. I'm no expert in such things, but I would expect the remote process to return from send(), and exit; the data would be waiting in a kernel mbuf on the local side Donn Cave, donn at drizzle.com From jjl at pobox.com Fri Dec 5 15:38:01 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Dec 2003 20:38:01 +0000 Subject: When is bare except: justified? References: <873cbzmbld.fsf@pobox.com> Message-ID: <87n0a7uhjq.fsf@pobox.com> "Dave Brueck" writes: > > When *is* it justified to use except:, then? [...] > The rule of thumb I use is that a bare except is bad if it hides the fact that > an exception occurred. So, for example, using a bare except in code like this > is okay: > > for worker in workers: > try: > worker.process() > except: > LogException() > > It's considered "okay" because even though the code prevents the exception from > propagating, it doesn't lose record of the fact that something went wrong. [...] Now that you say that, it's obvious :-) In fact, IIRC just the other day I fixed code to work that way in the same package I discussed in my post: try: __import__(module_name) except ImportError: + traceback.print_exc() sys.exit("Import of test module failed -- Couldn't find tests?") (this is in a hack to import all tests from a bunch of test_foo.py files) I guess I can keep the bare except:s I discussed in the first part of my post after all, but just make sure I emit a warning (with the warnings module in 2.3, I suppose). Thanks! John From jepler at unpythonic.net Mon Dec 8 14:35:53 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Dec 2003 13:35:53 -0600 Subject: sorting slovak utf In-Reply-To: <20031208173121.GQ11102@unpythonic.net> References: <3FD45B2C.1080107@kios.sk> <3FD47794.40902@kios.sk> <20031208173121.GQ11102@unpythonic.net> Message-ID: <20031208193550.GU11102@unpythonic.net> On Mon, Dec 08, 2003 at 11:31:29AM -0600, Jeff Epler wrote: > There are several problems all going on at the same time: [...] One more thing -- in the first message you were setting LC_CTYPE. The rules for locale.strcoll and locale.strxfrm depend on LC_COLLATE, not LC_CTYPE. Jeff From martin at v.loewis.de Mon Dec 29 05:43:28 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 29 Dec 2003 11:43:28 +0100 Subject: print arabic characters In-Reply-To: References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Peter Otten wrote: >>Then, for AL runs, you need to replace European numerals with Arabic >>numerals (but keeping the LTR order). > > > I always thought of numbers as most significant digit first. But the above > suggests that they are least significant digit first, preserving the > original RTL directionality. I'm actually uncertain: I recently learned that our (the European's) number system was *not* copied from the Arabs, but instead, both the Arabs and the Europeans copied the numbers from the Indians in the same time frame. So it may be that the Arabs have LTR for numbers as it is an imported writing system. As I said, I'm uncertain: It may also be that you are right, and numbers "properly" have the least significand digit first, and we copied the order from the Arabs. Regards, Martin From jepler at unpythonic.net Wed Dec 24 21:38:41 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 24 Dec 2003 20:38:41 -0600 Subject: Is re thread-safe? In-Reply-To: References: Message-ID: <20031225023841.GA26961@unpythonic.net> I don't know of anything about regular expression objects that would not be thread safe. They don't have any data attributes that depend on the current or last matching operation, for instance. Internally, the C implementation of regular expressions is either thread-safe or else runs with Python's GIL held to avoid thread-safety issues. It's possible that there's a particular concern I've overlooked--for instance, REs can refer to character classes such as "alphanumeric" (with \w, it looks like [:CLASS:]es are not supported). That means that the meaning of a regular expression can depend on the state of the program's locale, which is not a per-thread attribute. Jeff From a.schmolck at gmx.net Mon Dec 1 09:08:38 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 01 Dec 2003 14:08:38 +0000 Subject: comparing nan "number" References: Message-ID: Bo?tjan Jerko writes: > Hello ! > > I need to know if the result of math formula is nan (Not a number). > How can I do that? The only non-hacky way I know of is installing scipy and using scipy.isnan. 'as From gagenellina at softlab.com.ar Fri Dec 19 01:32:42 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 19 Dec 2003 03:32:42 -0300 Subject: Default attribute in base class precludes delegation In-Reply-To: <3FE24CB7.894.651DF56B@localhost> References: <5.2.1.1.0.20031219020923.01fe2040@192.168.0.115> <3FE2866A.3090500@zephyrfalcon.org> Message-ID: <5.2.1.1.0.20031219032025.01f3e020@192.168.0.115> At 19/12/2003 00:56, you wrote: > > My workaround was to *really* set an instance attribute 'bar' in > Derived, and > > try to ensure that it's always in sync with Worker: > > > > def __init__(self, worker): > > self.worker = worker > > self.bar = worker.bar > > > > def setBar(self, bar): > > self.worker.bar = bar > > self.bar = bar > > > > This works if a) all people always use setBar on Derived, and b) no one > > assigns to worker.bar directly. > >Hm. Maybe you can define a __setattr__ for Derived, then. Something like >(untested): > > def __setattr__(self, name, value): > if name == 'bar': > self.worker.bar = bar > self.__dict__[name] = value > >That way, people can assign to d.bar (where d is an instance of Derived) >directly, and it will/should still keep the sync. Yes, thanks, that would work for all assignments to d.bar But item b) is still a problem: anyone who has a reference to a Worker instance could write w.bar = xxx and things would go out of sync... Maybe I could make Worker aware of its container somehow (ouch... avoiding a circular reference?) and update it whenever w.bar is changed... But unless someone gives a better answer, I will just shout aloud all people involved: DONT DO THINGS THIS WAY!!! and hope nobody forgets it... Gabriel Genellina Softlab SRL From peter at engcorp.com Wed Dec 3 08:01:58 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Dec 2003 08:01:58 -0500 Subject: Can Python be run off of a CD-ROM? References: <3FCC8C92.406@ghaering.de> <3FCC9F83.7050405@ghaering.de> <8ylv6pq0.fsf@python.net> <3FCD4B38.CCECD83F@engcorp.com> <1xrm42w1.fsf@python.net> Message-ID: <3FCDDEC6.9A3836FB@engcorp.com> Thomas Heller wrote: > > Hehe, you know that you can import modules in the .pth file itself, > don't you? 'import ...' lines are executed. Nope! Even better... thanks, Thomas! :-) -Peter From charleshixsn at earthlink.net Wed Dec 17 13:46:34 2003 From: charleshixsn at earthlink.net (Charles Hixson) Date: Wed, 17 Dec 2003 10:46:34 -0800 Subject: Sound generation recommendations? Message-ID: <3FE0A48A.7060207@earthlink.net> I'm looking for a simple means of generatings sounds. Basically what I want to do is play music from the information available in sheet music. I would like to send the commands to the player in relatively short bursts (the initial application is desired to be a rising diatonic scale everytime the ball bounces off a paddle in a game of pong, based on tomspong.py (an SDL application). I think that the beep function in the winsound module would work, but I want this to work on Linux and the Mac, and I don't even have a Windows box to test it on. It would be nice if I could also specify the "instrument", for some definition of instrument. But this would be useful only if I had access to a library of instruments. Stereo might be a nice feature to add in later, but not yet unless it were really easy. My feeling about this part right now is "KISS, or you'll be diverted from the parts that are more important.". All the sound modules I've looked at seem to run off of sampled wave forms ... and this is nearly the opposite of what I want. From remco at localhost Mon Dec 15 05:17:57 2003 From: remco at localhost (remco) Date: Mon, 15 Dec 2003 11:17:57 +0100 Subject: Idle won't start References: Message-ID: <3fdd8a7e$0$214$e4fe514c@news.xs4all.nl> >kmneilso at yahoo.com (Kerry Neilson) writes: > >> For the past couple of months, Idle won't start when I invoke it. I >> am at a complete loss for why this is. When this happens, they python >> command line still starts, and python works fine otherwise. >> Most interesting to me is that a reboot won't fix the problem. But if >> I just try it again sometime later it will work. Anyone have any >> ideas? I'm running python 2.3 on windows 2000 professional. Have you tried running it from the command line? like: \lib\idlelib\idle.py and see if it produces any error messages? Cheers! Remco Boerma From michael at stroeder.com Tue Dec 2 12:26:49 2003 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 02 Dec 2003 18:26:49 +0100 Subject: ANN: python-ldap-2.0.0pre16 Message-ID: Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.0pre16 2003-12-02 Changes since 2.0.0pre15: Modules/: * Removed definition of unused constant RES_EXTENDED_PARTIAL since the corresponding symbol LDAP_RES_EXTENDED_PARTIAL seems to not be available in OpenLDAP-HEAD (pre 2.2) anymore. All in Lib/: * Fixed some subtle bugs/oddities mentioned by pychecker. dsml: * Renamed DSMLWriter._f to DSMLWriter._output_file * Added wrapper method DSMLWriter.unparse() which simply calls DSMLWriter.writeRecord() ldap.ldapobject: * Simplified LDAPObject.search_subschemasubentry_s() ldap.functions: * Moved ldap._ldap_function_call() into ldap.functions. * apply() is not used anymore since it seems deprecated ldap.async: * Added class DSMLWriter ldap.schema: * Removed unused key-word argument strict from ldap.schema.subentry.SubSchema.attribute_types() * Fixed backward compability issue (for Python prior to 2.2) in ldap.schema.subentry.SubSchema.listall() From jbarham at jbarham.com Sat Dec 13 20:44:00 2003 From: jbarham at jbarham.com (John E. Barham) Date: Sun, 14 Dec 2003 01:44:00 GMT Subject: Examples and Tutorials of SocketServer? References: <826b6ec2.0312131313.10769cda@posting.google.com> <7xiskkjtub.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Milo K. Piffenpauffer writes: > > I've looked on Google for examples of using the SocketServer module, > > but I'm not having much luck. The online documentation is pretty > > sparse, and PyDoc isn't very clear. Does anyone know where I could > > find an example of SocketServer that explains what the various > > features of the code do? > > "Use the source, Luke". Ditto. Admittedly it can be confusing figuring out which of the methods you need to override. Here's a slightly edited minimal echo server from the printed Python Cookbook (i.e., I couldn't find it in the Cookbook on the ActiveState website): import SocketServer class EchoHandler(SocketServer.BaseRequestHandler): def handle(self): while 1: data = self.request.recv(1024) if not data: break self.request.send(data) EchoServer = SocketServer.TCPServer(("", 8881), EchoHandler) EchoServer.serve_forever() Run the above and see it in action by doing "telnet localhost 8881" and typing away. The characters you type should be repeated (i.e., echoed). At least that's what happens for me on XP... Note that you don't even have to derive your server from one in SocketServer. All you have to do minimally is sub-class the BaseRequestHandler class and override the handle() method. Note too that the standard library's SimpleHTTPServer is based on SocketServer.TCPServer (via HTTPServer in BaseHTTPServer) so it's a good, albeit more complex, example of a SocketServer server. But at some point you should read and try to trace the source to SocketServer. Really, it's not that complicated. John From t_therkelsen at hotmail.com Sat Dec 27 06:43:57 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 27 Dec 2003 11:43:57 GMT Subject: ANN: Python Language Reference References: Message-ID: In article , Stephen Ferg wrote: > An attempt to produce a complete, alphabetized reference of all of > Python's language features. The purpose is support developers, who > need a quick way to look up information about a language feature. > > The table of contents was extracted from: > * the index of the language reference > * the index of the library reference > * the global module index > > http://www.ferg.org/pyref/index.html Very very nice work :-) If I may make a suggestion, it would be to have a letter index for the Global Module Index as you have for the two other main categories. Or, alternatively not put each module on its own list. While it is possible to use the 'find' feature of the browser to access the information, using that feature still requires that you move your hand away from your mouse. To me, it would be preferrable to be able to find the module I want in, say, 3-4 clicks, rather than pressing several keys on the keyboard. Again, great work! /Troels Therkelsen From francisgavila at yahoo.com Thu Dec 25 19:55:23 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Thu, 25 Dec 2003 19:55:23 -0500 Subject: 2.3 list reverse() bug? References: <26vmuvooh62ko48t7m8n2cumg0se7dd7v5@4ax.com> Message-ID: Arthur wrote in message <26vmuvooh62ko48t7m8n2cumg0se7dd7v5 at 4ax.com>... > >> >>Try reading this: >> >> http://starship.python.net/crew/mwh/hacks/objectthink.html >Generally speaking, it is hard to understand how someone's intutition >can be flawed. It's just an "is". Clearly there is an equivocation going on here. A distinction must be made. Intuition (your meaning): Direct or immediate perception of truth. Intuition (link's meaning): An unconscious or implicit conjecture or expectation. Certainly, by the first meaning, intuition just *is*: you either percieve the truth directly or you don't. No right or wrong. (Philosophy: Aristotle called this "simple apprehension", and he said the same thing about it: no right or wrong.) By the second meaning, however, one can certainly say that the expectation is correct or not. By the first meaning, to say "one's intution is wrong" in the face of Pythonic behavior is certainly an arrogant thing to say, because it implies that Python is the template from which all language behavior is wrought. I'm not prone to attribute such to others when another explaination presents itself, so I offer the above distinction. HTH. Merry Christmas! -- Francis Avila From spamfilter at macspeno.com Sun Dec 21 10:20:47 2003 From: spamfilter at macspeno.com (John P. Speno) Date: Sun, 21 Dec 2003 15:20:47 +0000 (UTC) Subject: Handling states with HTTP References: Message-ID: >In other words, I'm looking for a package that will use cookies or CGI >variables to save the state of the program in between HTTP requests. Packages >like Albatross seem to require class definitions for each page, which isn't >as natural or convenient as treating an HTML form as an input function (like >raw_input()). I'm sure many of the packages you can find here: http://www.python.org/cgi-bin/moinmoin/WebProgramming have some form of session managment that you'll be able to use. Take a look at pso (Python Service Objects): http://sourceforge.net/projects/pso/ Having just recently used it, I think pso has exactly what you want. Here are some examples of its usage for session managment: http://www.scriptfoundry.com/modules/pso/doc/session-cgi.html Take care. From brendano at stanford.edu Sun Dec 21 16:48:47 2003 From: brendano at stanford.edu (Brendan O'Connor) Date: Sun, 21 Dec 2003 13:48:47 -0800 Subject: web programming: experiences with non-zope frameworks? In-Reply-To: References: <7xu13u7gko.fsf@ruckus.brouhaha.com> Message-ID: On 21 Dec 2003, Ville Vainio wrote: > Brendan O'Connor writes: > > > > I'll give some heretical advice: if > > > you're doing a big project, set aside some of the development time to > > > evaluate what's out there and adopt or develop something that's best > > > for your specific needs, with the understanding that you're going to > > > have to maintain it yourself. If you're doing a small project and > > > That's certainly a shame to hear. I'm very concerned that any given > > python framework I'd choose might not be around a few years from now; it > > Umm... I guess that's not what he meant. It's the framework you > developy yourself you would have to maintain. Yeah, that's the problem: it really helps to use a framework that's supported by a community of users, not just yourself. > > > seems that none of them have the popularity needed to sustain a large > > community to test and achieve maturity, write books and top-quality > > documentation, etc. > > If having these qualities is so important, why not just bite the > bullet and go Zope? I may, in the future. I was just hoping there was an alternative; I mean, even the Zope people say it's too complex and they're rewriting Zope 3 to simplify things. We'll see I guess. Brendan From hungjunglu at yahoo.com Wed Dec 10 19:37:15 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 10 Dec 2003 16:37:15 -0800 Subject: Prototype-based programming Message-ID: <8ef9bea6.0312101637.33574fb9@posting.google.com> Hi, Description of PBP (Prototype-based programming) can be found at: http://en.wikipedia.org/wiki/Prototype_based http://www.dekorte.com/Proto/Chart.html ("Self" is an example of a PBP language: http://research.sun.com/self/language.html) The most naive PBP would imply a overwhelming redundancy in namespace entries. (E.g: all object instances carry bindings for their methods.) Efficient in time, but not very efficient in space (memory usage). But I am sure people have looked at lookup-precedence strategies, much like how Python finds names first in the local, then the global, then the built-in namespace, or how instance attributes are looked up in multiple inheritance. I got looking into PBP because Python starts to look evil when you use descriptors, metaclasses, etc. And that's not just Python: the fundamentals of most well-known languages are getting more and more complicated. The current programming world reminds me of the situation of the time when RISC came up against CISC. I mean, it's OK for a lot of additional features to be built on top of the fundamentals, but nowadays the fundamentals themselves are getting too complicated. Is it time to take a break and say: "there is gotta be a simpler way!"? >From the little I read about Haskell it seems that it's possible to keep the fundamentals clean and do complex things at the same time. The usage of classes is just weird... it's a concept from the 1970s and should probably be retired by now. Because you use classes, you then hit upon metaclasses, (and meta-metaclasses... ad-infinitum), and also come up with funny "patterns" like Singletons, or define "static" class attributes. I mean, aren't all these the symptoms that we are doing something wrong? regards, Hung Jung From usenet_spam at janc.invalid Sun Dec 28 04:17:35 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 28 Dec 2003 09:17:35 GMT Subject: Project dream References: <0ghpuv88km9oaq2ub0slu898i3u6ea0p28@4ax.com> Message-ID: hwlgw at hotmail.com (Will Stuyvesant) schreef: > I wonder how healty it is: their wiki is empty, the Mitch Kapor blog > is stopped, there is not much recent news. But interesting certainly. Mitch Kapor is not only chairman of OSAF, but (at least) also of the wxWindows Foundation and the Mozilla Foundation. He might have a very busy schedule... :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From matt.gerrans at hp.com Wed Dec 17 19:38:19 2003 From: matt.gerrans at hp.com (Matt Gerrans) Date: Thu, 18 Dec 2003 00:38:19 GMT Subject: Lanching application References: Message-ID: <%F6Eb.10980$Bl7.7345@news.cpqcorp.net> Since you mentioned Windows specifically, you can use win32api.WinExec(). From richie at entrian.com Tue Dec 2 02:49:42 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 02 Dec 2003 07:49:42 +0000 Subject: Separation of content and code for web (was Re: Python for web ?) In-Reply-To: <3FCB8535.F8F89132@engcorp.com> References: <3FCB8535.F8F89132@engcorp.com> Message-ID: <5ogosvocun9cpabch2f1u4152o8tvko5i2@4ax.com> [Peter] > By far the most rigorous separation that I've seen to date, and one > we're experimenting with more right now, is to have a pure-HTML (or XHTML) > web page with *no* code or funky little embedded crap of any kind at > all, and rely exclusively on "id" attributes on the dynamic parts. > > The code is built to work on the appropriate ids, generally working with > an in-memory model of the data, with serialization back to [X]HTML > when the job is done. > > Web folks get their HTML page without code, programmers get nice > code without embedded HMTL, and everyone is happy. > [...] > Anyone know of a Python-based approach using the same core concept? You've just described PyMeld (www.entrian.com/PyMeld) better than I ever have. May I replace my web page with your post? 8-) (Note that PyMeld's performance can stink with large page, but there are ways around that - mail me for more info if PyMeld looks like a good fit for you. I'll probably create a wiki for it if there's the demand, and put up some hints and tips there.) -- Richie Hindle richie at entrian.com From jepler at unpythonic.net Mon Dec 22 17:11:42 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 22 Dec 2003 16:11:42 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <16359.27380.260552.535448@montanaro.dyndns.org> References: <21bb8d55.0312221204.51d86182@posting.google.com> <16359.24377.5101.789601@montanaro.dyndns.org> <20031222213900.GC24252@unpythonic.net> <16359.27380.260552.535448@montanaro.dyndns.org> Message-ID: <20031222221142.GE24252@unpythonic.net> On Mon, Dec 22, 2003 at 04:06:44PM -0600, Skip Montanaro wrote: > Then it looks like a bug in one or the other to me. Add 'assert len(c) == 1' at the top of mine, then. Jeff From peter at engcorp.com Fri Dec 5 10:26:42 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 10:26:42 -0500 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> Message-ID: <3FD0A3B2.4DD3B518@engcorp.com> Douglas Alan wrote: > > mis6 at pitt.edu (Michele Simionato) writes: > > > I never understood why you advocate case insensitivity. I would > > expect case insensitivity to be a source of bugs: for instance, > > identifiers with similar names could be confused (es. myfunction > > vs. myFunction): one would expect them to be different (at least > > people coming from case insensitive languages) whereas they would be > > the same. > > When you use a case-insensitive language, you do not typically use > StudlyCaps at all, so you wouldn't ever write "myFunction". Instead, > you would write "my_function" or "my-function", depending on the > language. This is the second ludicrous thing I've seen you write today. The first was when you claimed Fredrik Lundh was "dead wrong" about the use of tuples vs. lists, when your own view is in direct contradiction to a very widely used convention in the Python programming world, and supported by the FAQ entry and Guido's own views. When *I* have used case-insensitive languages, I have certainly used various forms of capitalization to represent different types of information, such as functions or constants. I am definitely not alone in this approach, as I have learned it from reading others' code. *You* might not do so, but your opinions are clearly not held by all other programmers, nor perhaps even the majority, so please stop writing as though they are. -Peter From marcos at nordesia.org Mon Dec 22 13:43:21 2003 From: marcos at nordesia.org (Marcos Eimil Pardo) Date: Mon, 22 Dec 2003 19:43:21 +0100 Subject: Remembering In-Reply-To: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Message-ID: <3FE73B49.4010401@nordesia.org> MComp escribi?: > Hey guys, I'm another new to programming guy. I have one quick > question. How do you make a program not forget everything you input, > once it shuts down? Thanks in advance. you can save read data to a file: data=raw_input("type some data> ") # open a file to write text f=file("savedata","wt") # save data to file f.write(data) # close file f.close() and when you reload your program you can read data from file: # open a file to read text f=file("savedata","rt") # save data to file data=f.read() # close file f.close() well this is a very simplistic solution, if you want to save multiple data, you must save it following some convention, for example if you have read name and age, you can save it in a text file, with two lines, the first with name and the second with age, and when you restart your program you should read from file in the same order: #to write multiple data item on multiple lines name=raw_input("name> ") age=raw_input("age> ") # open a file to write text f=file("savedata","wt") # save name to file f.write(name) # write newline character f.write("\n") # save age to file f.write(age) # close file f.close() #to read multiple data item on multiple lines # open a file to read text f=file("savedata","rt") # read name from file (name is in first line) # attention: we use readline to read one line, read() gets entire # file (read manual for more information) name = f.readline() # read age from file (age is in second line) age = f.readline() # age and name are strings terminated with a new-line character, # we may want to strip this last char, we can do it this way: age = age[:-1] name = name[:-1] # close file f.close() hope, gives some help. greets, marcos. From paulo.pinto at cern.ch Wed Dec 17 05:10:09 2003 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Wed, 17 Dec 2003 11:10:09 +0100 Subject: Build classes/packages dinamicaly In-Reply-To: References: Message-ID: Thanks for the replies. I have now a working solution. From admin at ferger.de Tue Dec 16 07:42:07 2003 From: admin at ferger.de (Olaf Ferger) Date: Tue, 16 Dec 2003 13:42:07 +0100 Subject: I am lookin' for Python magazines References: Message-ID: On Tue, 16 Dec 2003 11:04:40 +0100, JZ wrote: >I would like to buy a subscription to some good Python oriented >magazines. I found only ZopeMagazine. Do you know any other worth to >buy? Have a look at: www.pyzine.com Regards, Olaf -- EOP From piir at earthlink.net Thu Dec 25 05:06:02 2003 From: piir at earthlink.net (Todd Gardner) Date: 25 Dec 2003 02:06:02 -0800 Subject: hex array to array of 16 bit numbers? Message-ID: <9b849915.0312250206.61d89841@posting.google.com> Hello everyone, I would really appreciate some of your expertise or even just pointers. How do I convert this hex array variable "buffer" to array of 16 bit numbers? >>> >>> from ctypes import * >>> buffer = c_buffer(8) >>> status = ni.DAQ_Op (deviceNumber, chan, gain, buffer, count, sampleRate) >>> print "repr(buffer.raw) =", repr(buffer.raw) repr(buffer.raw)= '\xcd\x00\xce\x00\xce\x00\xce\x00' >>> Any ideas would be greatly appreciated! Todd From mir4uu at yahoo.com Thu Dec 11 01:17:02 2003 From: mir4uu at yahoo.com (mir nazim) Date: 10 Dec 2003 22:17:02 -0800 Subject: online examination system References: <425cc8d1.0312090932.697fd6c6@posting.google.com> <3fd618d1$0$108$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <425cc8d1.0312102217.1b7e17d6@posting.google.com> "Fedor" wrote in message news:<3fd618d1$0$108$3a628fcd at reader2.nntp.hccnet.nl>... > Have you looked at http://zope.org/Wikis/zope-edu? > > Fedor i tried the url but could not get what i wanted. Plaese be specific From usenet03q2 at hczim.de Tue Dec 16 05:53:56 2003 From: usenet03q2 at hczim.de (Heike C. Zimmerer) Date: Tue, 16 Dec 2003 11:53:56 +0100 Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: William Park writes: > hokiegal99 wrote: >> import os, string >> setpath = raw_input("Enter the path: ") #This can be hard coded. >> for root, dirs, files in os.walk(setpath, topdown=False): >> for fname in files: >> s = string.find(fname, '.mp3') >> if s >=1: >> fpath = os.path.join(root,fname) >> os.remove(fpath) >> print "Removed", fpath, "\n" > > FYI, in shell, you would go > find . -type f -name '*.mp3' | xargs rm Which will fail if the file name contains any spaces or other special characters (not too unusual for .mp3 - Files). - Heike From claird at lairds.com Thu Dec 4 07:44:06 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Dec 2003 12:44:06 -0000 Subject: customize Tkinter window button~ References: Message-ID: In article , Howard Lightstone wrote: >black wrote in >news:mailman.89.1070511965.16879.python-list at python.org: > >> i am with Win2k and had built a window with Tkinter, it has 3 button >> on its topright corner as common window, but what i want is just one >> or tow of them. ie, is there any way i can configure the appearance >> of minimize, maximize and close button ? > >Basically, no. Those buttons are a function of the Windows standard window >creation logic. It is possible to add to or change those buttons (using >ctypes) - but you are looking at some pretty hairy and poorly documented >routines (such as the required callbacks for each button). > >What you CAN do is use the overrideredirect method to turn off the entire >top bar and instead put one of your own (Tkinter) buttons there. Just >don't forget to handle the (closing, moving the window, etc.,) events for >the window. All true. Yet another possibility: leave the buttons in place, but bind alternate actions to them. -- Cameron Laird Business: http://www.Phaseit.net From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 12 11:15:59 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 12 Dec 2003 17:15:59 +0100 Subject: python on websites References: Message-ID: Sebastian Kress: >Now my Webhoster sent an eMail that they now offer support for >Python on their servers, too. How precisely? CGI, mod_python, ...? >Since I only programmed stand-alone-software in Pyhton, I don't have a >clue how to integrate Python-skripts into websites. Could anybody please > tell me where to find a good online-tutorial on that? http://www.python.org/topics/web/ -- Ren? Pijlman From bokr at oz.net Mon Dec 1 13:31:00 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Dec 2003 18:31:00 GMT Subject: Extract double in binary file References: Message-ID: On 1 Dec 2003 08:45:04 -0800, pascal.parent at free.fr (Pascal) wrote: >First thanks for trying! > >May be these values will tell you somethings: >1 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x81 >-1 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x81 >2 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x82 >-2 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x82 >3 0x0 0x0 0x0 0x0 0x0 0x0 0x40 0x82 >-3 0x0 0x0 0x0 0x0 0x0 0x0 0xc0 0x82 >1.1 0xcd 0xcc 0xcc 0xcc 0xcc 0xcc 0xc 0x81 >1.2 0x9a 0x99 0x99 0x99 0x99 0x99 0x19 0x81 >1.3 0x66 0x66 0x66 0x66 0x66 0x66 0x26 0x81 >1.4 0x33 0x33 0x33 0x33 0x33 0x33 0x33 0x81 >1.01 0x48 0xe1 0x7a 0x14 0xae 0x47 0x1 0x81 >0.01 0xd7 0xa3 0x70 0x3d 0xa 0xd7 0x23 0x7a >1.02 0x8f 0xc2 0xf5 0x28 0x5c 0x8f 0x2 0x81 >0.02 0xd7 0xa3 0x70 0x3d 0xa 0xd7 0x23 0x7b This needs some cleanup and optimization, but for the above it seems to work: ====< PascalParent.py >================================= #First thanks for trying! #May be these values will tell you somethings: data = """\ 1 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x81 -1 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x81 2 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x82 -2 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x82 3 0x0 0x0 0x0 0x0 0x0 0x0 0x40 0x82 -3 0x0 0x0 0x0 0x0 0x0 0x0 0xc0 0x82 1.1 0xcd 0xcc 0xcc 0xcc 0xcc 0xcc 0xc 0x81 1.2 0x9a 0x99 0x99 0x99 0x99 0x99 0x19 0x81 1.3 0x66 0x66 0x66 0x66 0x66 0x66 0x26 0x81 1.4 0x33 0x33 0x33 0x33 0x33 0x33 0x33 0x81 1.01 0x48 0xe1 0x7a 0x14 0xae 0x47 0x1 0x81 0.01 0xd7 0xa3 0x70 0x3d 0xa 0xd7 0x23 0x7a 0.0 0x0 0x0 0x0 0x0 0x0 0x0 0x7F 0x0 """ def bytes2float(bytes): if bytes == [0,0,0,0,0,0,0x7f,0]: return 0.0 b = bytes[:] sign = bytes[-2]&0x80 b[-2] |= 0x80 # hidden most significant bit in place of sign exp = bytes[-1] - 0x80 -56 # exponent offset acc = 0L for i,byte in enumerate(b[:-1]): acc |= (long(byte)<<(i*8)) return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) for line in data.splitlines(): nlist = line.split() fnum = float(nlist[0]) le_bytes = map(lambda x:int(x,16) ,nlist[1:]) test = bytes2float(le_bytes) print ' in: %r\nout: %r\n'%(fnum,test) ======================================================== Result: [10:44] C:\pywk\clp>PascalParent.py in: 1.0 out: 1.0 in: -1.0 out: -1.0 in: 2.0 out: 2.0 in: -2.0 out: -2.0 in: 3.0 out: 3.0 in: -3.0 out: -3.0 in: 1.1000000000000001 out: 1.1000000000000001 in: 1.2 out: 1.2 in: 1.3 out: 1.3 in: 1.3999999999999999 out: 1.3999999999999999 in: 1.01 out: 1.01 in: 0.01 out: 0.01 in: 0.0 out: 0.0 HTH Regards, Bengt Richter From andreb at warpmail.net Wed Dec 17 02:05:07 2003 From: andreb at warpmail.net (Andre Brightway) Date: 16 Dec 2003 23:05:07 -0800 Subject: A GUI toolkit for Python that is NOT x-windows dependent Message-ID: <88f9e356.0312162305.58718893@posting.google.com> I need a script to draw a keyboard to the screen and animate the marking each key when the key is pressed (among other things like being able to draw menus). This script is for testing keyboards and needs to be run by people who may never have touched a computer before so it needs to have an easy to follow GUI interface. But the Linux boxes these will be runned on are very low-end, 'diskless' terminals where running a full X-Windows system would be very slow. Does anybody know of a GUI toolkit (or a way to draw to the screen) that can be used from Python script in Linux without having to run X-Windows? From tiltonj at erols.com Sat Dec 20 16:36:48 2003 From: tiltonj at erols.com (Jay Tilton) Date: Sat, 20 Dec 2003 21:36:48 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: <3fe4bd0e.68951468@news.erols.com> xah at xahlee.org (Xah Lee) wrote: : i have a bunch of java files that has spaced-out formatting that i : want to get rid of. I want to replace two end of line characters by : one end of line characters. The files in question is unix, and i'm : also working under unix, so i did: : : perl -pi'*~' -e "s@\n\n@\n at g" *.java : : but this to no avail. Of course it's not. Perl's -p switch processes one line at a time. A line cannot have more than one newline character. Perl's "paragraph" reading might be useful to you, where any number of consecutive newline characters mark the end of a record. See "$/" in perlvar for details. perl -i'*~' -lpe "BEGIN{$/=''}" *.java : after many minutes of checking and rechecking and lots of trial and : error with frustration, i realized that the fucking perl to my : expectations again cannot do this simple fucking thing. Complete nonsense. Don't blame your own incompetence on Perl. : Fucking stupid perl : documentation and Larry Wall moron who is i believe incapable of : writing clearly and logically in English masquerading as humor. If you feel you can explaint it more clearly, quit bellyaching about it and submit a documentation patch. Preferrably one that is less petulant and profane than your article. Frustration is no excuse for incivility. From bokr at oz.net Fri Dec 19 00:41:01 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Dec 2003 05:41:01 GMT Subject: Default attribute in base class precludes delegation References: Message-ID: On Fri, 19 Dec 2003 00:44:28 -0300, Gabriel Genellina wrote: >Hi > >In the following code sample, I have: >- a Worker class, which could have a lot of methods and attributes. In >particular, it has a 'bar' attribute. This class can be modified as needed. >- a Base class (old-style) which defines a default class attribute 'bar' >too. I can't modify the source code of this class. Note that Workes does >not inherit from Base. >- a Derived class which must inherit from Base and is a wrapper around >Worker: it contains a Worker instance and delegates almost anything to it. >This class can be modified as needed too. In what sense a "wrapper"? > >For most attributes, as they are not found in the Derived instance's dict, >__getattr__ is called and the attribute is retrieved from the Worker instance. Why do you (think you) need an explicit __getattr__ ? Usually there's better ways. >But for the 'bar' attribute, it is found in the Base class and just the >default value is returned. __getattr__ is never called. >I need to avoid this, and return Worker instance's value instead of Base's >default value. >That is, in the last line of the example, I want: d.bar == 'Hello' >How could it be done? > >--- cut --- ># This class does the "real" work and I can modify it as needed >class Worker: class Worker(object): > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > ># This is just a base class from which I must inherit but I can't modify it >class Base: > bar = None > ># This is a wrapper for Worker and I can modify it. ># I want to get most attributes from Worker class ># but for 'bar' I always get the default from Base, ># its declaration there effectively hides the attribute ># from the delegated Worked instance. >class Derived(Base): class Derived(Worker, Base): """never mind any methods at this point yet""" > def __init__(self, worker): > self.worker = worker > > def __getattr__(self, name): > return getattr(self.worker, name) > >w = Worker(1234, 'Hello') >print 'w.foo', w.foo # prints 1234 >print 'w.bar', w.bar # prints Hello >d = Derived(w) d = Derived(6578, 'Goodbye') >print 'd.foo',d.foo # prints 1234 >print 'd.bar',d.bar # prints None, I want to get Hello > >--- cut --- Does this do anything for you? (you could inherit differently than below too, of course) ====< genellina.py >========================================================================= # This class does the "real" work and I can modify it as needed class Worker(object): def __init__(self, foo, bar): print 'Worker init: Initializing %s instance' % self.__class__.__name__ self.foo = foo self.bar = bar # This is just a base class from which I must inherit but I can't modify it class Base: def __init__(self,*args, **kw): print 'Base init:', args, kw bar = None baz = 'Base baz' # This is a wrapper for Worker and I can modify it. # I want to get most attributes from Worker class ##### why not just inherit them from ^^^^^^^^^^^^ ? # but for 'bar' I always get the default from Base, # its declaration there effectively hides the attribute # from the delegated Worked instance. class Derived(Worker, Base): """dummy until something to do""" if __name__ == '__main__': w = Worker(1234, 'Hello') print 'w.foo of %s instance: %s' %(w.__class__.__name__, w.foo) # prints 1234 now print 'w.bar of %s instance: %s' %(w.__class__.__name__, w.bar) # prints Hello now d = Derived(5678, 'Goodbye') #w) print 'd.foo of %s instance: %s' %(d.__class__.__name__, d.foo) # prints 5678 now print 'd.bar of %s instance: %s' %(d.__class__.__name__, d.bar) # prints Goodbye now print 'd.baz of/via %s instance: %s' %(d.__class__.__name__, d.baz) d.baz = 'd instance baz' print 'd.baz of/via %s instance: %s' %(d.__class__.__name__, d.baz) ============================================================================================= Result: [21:52] C:\pywk\clp>genellina.py Worker init: Initializing Worker instance w.foo of Worker instance: 1234 w.bar of Worker instance: Hello Worker init: Initializing Derived instance d.foo of Derived instance: 5678 d.bar of Derived instance: Goodbye d.baz of/via Derived instance: Base baz d.baz of/via Derived instance: d instance baz Or do you actually need to have different unknown types of workers so you can't inherit? Regards, Bengt Richter From theller at python.net Wed Dec 3 05:22:22 2003 From: theller at python.net (Thomas Heller) Date: Wed, 03 Dec 2003 11:22:22 +0100 Subject: Can Python be run off of a CD-ROM? References: <3FCC8C92.406@ghaering.de> <3FCC9F83.7050405@ghaering.de> <8ylv6pq0.fsf@python.net> <3FCD4B38.CCECD83F@engcorp.com> Message-ID: <1xrm42w1.fsf@python.net> Peter Hansen writes: > Thomas Heller wrote: >> >> win32all is growing in a direction where it makes fewer use of the >> registry than in the past, and the sandbox py2exe is already able to >> create frozen com servers which work fine with python23.dll in the >> executable directory, so I assume somewhere in the future Python >> releases don't need dlls in the system directory anymore. > > Technically, no release since at least 2.0 has required DLLs in > the system directory, but it has taken some work (growing less by > the release) to make that possible. We've used a shared network > installation of Python for each release from 2.0 on, with only > minor tweaking. > > Initially we had to move the DLLs manually from the installation > machine's SYSTEM directory to the network drive. Now the non-admin > option resolves that issue. > > win32all is for us the only remaining issue. We need to include > a .pth file with two or three paths in it (even though the package > installs itself under site-packages now!). We also still need to > set up a sitecustomize.py file which does imports on pythoncom and > pywintypes, or an import of win32api (for example) will fail. Hehe, you know that you can import modules in the .pth file itself, don't you? 'import ...' lines are executed. > I don't recall the explanation, but without first importing those > (or perhaps just one?) modules you can't import the win32 stuff, > but if they have been imported first, then it works fine. Because win32api.pyd links against pywintypes23.dll, but the latter is not on the DLL load path. So it must be imported first by pywintypes.py, which then replaces it's module dict by pywintypes23's dict. Or something like that. Thomas From spiffy at worldnet.att.net Wed Dec 10 18:13:58 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Wed, 10 Dec 2003 23:13:58 GMT Subject: running non-python progs from python References: Message-ID: "Marc Boeren" wrote in message news:mailman.30.1071062337.9307.python-list at python.org... > > Hi, > > > Spiffy wrote: > > > > that indicates that it's supposed to work, don't you think? > > > IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? > > I can understand that you get frustrated that os.system doesn't seem to > work, but there's no need to shout. > Shout? That's funny, I like that. If I appear to have been angry, it was directed solely at one person, who for some unknown reason, was more interested in harassing than helping me. > I've read the thread, and noticed one odd thing. You said that if you > execute: > > C:\Python22>playb Canyon.mid > > from the command line, it works. > Later, you try to execute 'C:\Python22\playb.exe' with Canyon.mid as a > parameter. > > Did it occur to you that playb.exe may not be located in C:\Python22\ at > all? ....playb.exe is located in C:\Python22\ > The command-line you said you executed starts playb from within the Python22 > folder, but it could have found playb.exe anywhere in your Windows PATH. > > Can you locate playb.exe on you hard-drive using the Windows Explorer? What > is the exact location the program appears in? Try to use that in you call to > os.system. > > One other useful technique to track down a problem: > > import os > program = r"C:\Windows\playb.exe" > filename = r"D:\MIDI\anyfile.mid" > commandline = "%s %s" % (program, filename) > print commandline > os.system(commandline) > > This will print the complete command-line first. You can copy/paste this to > a DOS-box and execute it (from within any directory) and see what happens. > > Good luck, > > Cheerio, Marc. > Thanks for responding and trying to help. Fredo emailed me with a solution for the problem and now I have working code. yay! From genjox at yahoo.com Tue Dec 9 14:29:42 2003 From: genjox at yahoo.com (Robert) Date: 9 Dec 2003 11:29:42 -0800 Subject: 2.3.2 Memory Leaks ? Message-ID: Hi, I am building with VS 6.0 under WinXP, and building with the default python configuration & settings. I build a test python app with just the following code: /* testing for memory leaks */ long tmp_flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); tmp_flag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag( tmp_flag ); Py_Initialize(); Py_Finalize(); For some reason I am seeing a *bunch* of memory leaks. Does anyone know what the problem could be? From michael at foord.net Fri Dec 5 09:32:31 2003 From: michael at foord.net (Fuzzyman) Date: 5 Dec 2003 06:32:31 -0800 Subject: Threading - Why Not Lock Objects Rather than lock the interpreter Message-ID: <8089854e.0312050632.72cbfb44@posting.google.com> Looking at threading code it seems that the Global Interpreter Lock is a bit of a 'brute force' way of preventing two threads attempting to access sensitive objects simultaneously.... Why not have a new type of object with a 'lock' facility... if an object is locked then any thread trying to access the object other than the one obtaining the lock is blocked until the lock is released..... rather than blocking *all* threads until one thread has finished with the object..... It could be implemented as a new attribute of existing objects... or new types of objects..... Fuzzy From edreamleo at charter.net Fri Dec 5 09:54:53 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 5 Dec 2003 08:54:53 -0600 Subject: ANN: Leo 4.1 beta 5: An outlining editor Message-ID: Leo 4.1 beta 5 is now available at: http://sourceforge.net/projects/leo/ For the first time in months there are no serious bugs outstanding. Warning: By default Leo 4.1 creates .leo files that can not be read by older versions of Leo. Warning: Use the __wx_gui.py plugin with _extreme_ caution until further notice: bugs in this plugin could cause body text to be lost when changing nodes. Beta 5: * Leo runs in batch mode when invoked with --script aScriptFile.py - Created "null gui" classes that do not write to the screen. * Leo supports Unicode characters (e.g. Chinese) in path and file names. * Fixed several long-standing bugs: - Fixed several minor problems with the Extract Section and Import commands. - Fixed problem that prevent the Find panel from working on the Mac. - Improved @url handling so that @url file:\\path\x.leo works properly. - Improved support for @lineending platform. - Leo honors outline/body pane ratio when opening .leo files. - Leo now ensures that newly-opened windows fit entirely on the screen. - Fixed a crasher when Undoing a Change All command when searching headlines. - Fixed other bugs resulting from the 4.1 reorg: - Fixed problem loading plugins on Linux. - Fixed crashers in the Extract Section and Extract commands. - Fixed crasher when writing a file containing an undefined section. - Removed duplicate bindings in popup menus. - Made sure to show Leo's windows in wx gui plugin. Beta 4: * Allow @directives and section references when executing scripts! - Fixed several "reorg" bugs, some of which affected plugins. - More than one section reference may now appear on the same line. - Use "utf-8" encoding for filenames under MacOS (Darwin) - Allow command or cmnd prefix for menu shortcuts under Darwin. Beta 3: - Completed the reorg, making _many_ changes to the code base. - Fixed a LaTeX coloring bug Beta 2: - Fixed a startup problem on Linux: the "mbcs" text encoding is not valid on Linux. Beta 1: * New script-based find/change commands. - Hoist & DeHoist commands for viewing parts of an outline. - Check Outline command finds user clone mistakes. * New configuration settings: - use_gnx specifies whether .leo files use integers as indices: use_gnx = 0 makes .leo files compatible with previous versions of Leo. use_gnx = 1 makes .leo files cvs-friendly - config_encoding specifies the encoding of leoConfig.txt. * Several significant code-level changes: - The 4.1 code base has been reorganized to support gui plugins. - An example wx_gui plugin is partly functional. - Created a flexible framework for creating & running regression tests. - app.forceShutdown now works when called from plugins. Quotes of the month ------------------- "I like Leo more the more I use it...It's an unexpected pleasure to see my (linearly written) code outlined in Leo. I can't wait to use Leo to start a new project, going from outline to code...Thanks again for providing the computing community with such a fine piece of software." -- Jim Shapiro, Ph.D. "If you think you have used all possible programmer's editors, but have not yet tried Leo, you are wrong...I rate Leo as a 'must have' for Python programmers. The code makes for a good read." -- John Tobler http://weblogs.asp.net/Jtobler/ What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.1 or above and tcl/tk 8.3 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Wiki: http://leo.hd1.org/ Edward K. Ream December 5, 2003 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From cartermark46 at ukmail.com Wed Dec 10 11:25:35 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 10 Dec 2003 08:25:35 -0800 Subject: Email attachments and text Message-ID: Section 12.2.13 (from the email module) gives examples of how to send attachments with emails. The problem is, it does not explain how to send text in the body of the message. One line of code that is gives is: outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' So how do I arrange it so that the text *will* be seen? From ville.spammehardvainio at spamtut.fi Mon Dec 15 06:16:50 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 15 Dec 2003 13:16:50 +0200 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: Gustavo Niemeyer writes: > I really don't see Python and Lua overlapping in their fields right > now. Lua is clearly not developed with general system tasks in mind, > and Python is clearly not developed to be a configuration language, I think there was some flame wars on TCL/whatever a while (well, ages) back, where RMS was insisting that people should not settle for stripped down languages in favor of "complete" languages. I tend to agree. Python is a wonderful configuration language, and I don't see the need to do much "configuring" on systems that can't handle Python. BTW, how big is something like Guile or other minimal Scheme anyway? Why wouldn't it do? > or as small as possible. This may change in the future, but I belive > (and hope) that instead of Lua becoming a general purpose language, > the Python core will get smaller, with something like the pypy > project. How small does it need to be for your application? -- Ville Vainio http://www.students.tut.fi/~vainio24 From ville.spammehardvainio at spamtut.fi Sun Dec 28 04:06:13 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 28 Dec 2003 11:06:13 +0200 Subject: PHP and Python References: Message-ID: "Pythonious" writes: > I want to do this using Tkinter but what I want to do is be able to use some > sort of network protocal to remotely log in to my database I guess you could > call it SSH or telnet to be able to edit the records in my database from my > computer. But through a Graphical environment without having to execute > mysql commands. You might want to check out Rekall - it's an Access-like frontend for SQL databases. Haven't tried it, but it seems to be on mark: http://thekompany.com/products/rekall/ -- Ville Vainio http://www.students.tut.fi/~vainio24 From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 10 05:19:21 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 10 Dec 2003 11:19:21 +0100 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? In-Reply-To: <87ekvdgig0.fsf@hugin.valhalla.net> References: <87ekvdgig0.fsf@hugin.valhalla.net> Message-ID: <3fd6f329$0$209$e4fe514c@news.xs4all.nl> Sean Richards wrote: > Tab completion for keywords and methods etc (you can get this in the > standard python shell as well of course) You can? How? --Irmen From tjreedy at udel.edu Mon Dec 8 12:47:29 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Dec 2003 12:47:29 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: "Jacek Generowicz" wrote in message news:tyf7k171jbq.fsf at pcepsft001.cern.ch... > I have a program in which I make very good use of a memoizer: > > def memoize(callable): > cache = {} > def proxy(*args): > try: return cache[args] > except KeyError: return cache.setdefault(args, callable(*args)) > return proxy ... > I've got to the stage where my program is still not fast enough, and > calls to the memoizer proxy are topping profiler output table. So I > thought I'd try to see whether I can speed it up by recoding it in C. Have you tried psyco on above? Or rather, on the proxies? Can any of your callables be memoized by list rather than dict? (ie, any count or restricted int args?) If you have just a few wrapped functions, faster, special-cased proxies (with exact arg lists) would be feasible and possibly easier for psyco. Special-casing would include inlining the callable when possible -- or rather, inlining the memoization within the function. TJR From timr at probo.com Wed Dec 31 03:06:57 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 31 Dec 2003 00:06:57 -0800 Subject: ishexdigit() References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: <4l05vvs0ril5a2lr35pp52vq98n990jmef@4ax.com> Ben Finney wrote: > >More Pythonish is to use string.hexdigits and map() to write your own: > > >>> import string > >>> def ishexdigit( char ): > ... result = ( char in string.hexdigits ) > ... return result > ... > >>> def ishexstring( str ): > ... resultmap = map( ishexdigit, str ) > ... result = ( False not in resultmap ) > ... return result > ... > >>> ishexstring( '010101' ) > True > >>> ishexstring( 'deadb00f' ) > True > >>> ishexstring( 'foob' ) > False Well, more Pythonish yet is to avoid the extraneous local variables, avoid the use of a type as a parameter name, and use as many little-used builtins as possible: def ishexdigit(char): return char in string.hexdigits def ishexstring(strng): return filter(ishexdigit, strng) == strng -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From etzwane at schwag.org Fri Dec 5 14:36:07 2003 From: etzwane at schwag.org (S McAfee) Date: Fri, 05 Dec 2003 19:36:07 -0000 Subject: Perplexing buffering(?) problem Message-ID: Consider this fairly basic pipe/fork program: -------------------- import os, sys, time r, w = os.pipe() pid = os.fork() if pid == 0: os.dup2(w, sys.stdout.fileno()) os.close(w) os.close(r) sys.stdout.write("This should appear right away!\n") sys.stdout.close() time.sleep(3) sys.exit(0) os.close(w) r = os.fdopen(r, "r") str = r.readline() print 'Got line "%s"\n' % str os.wait() -------------------- The child process dups the write end of the pipe to stdout, closes both ends of the pipe, writes a line to stdout, closes stdout, and waits a few seconds before exiting. Meanwhile, the parent closes the write end of the pipe, reads a line from the read end, prints it, and waits for the child to exit. What I *expected* to happen was that the parent would immediately report the line printed by the child, since the child's stdout stream should be flushed when it is closed. Instead, the parent waits three seconds before printing the line! I can't figure out where the data is getting hung up. When I write the equivalent program in C or Perl, I get the text from the child right away. Strangely, if I skip the dup-to-stdout step and write directly to the pipe, like this: if pid == 0: os.close(r) w = os.fdopen(w, "w") w.write("This should appear right away!\n") w.close() time.sleep(3) exit(0) ...then the text does indeed appear right away. Bizarrely, if I print any text at all to stdout before forking: r, w = os.pipe() print "*", sys.stdout.flush() pid = os.fork() ...then that ALSO makes the child-generated text appear in the parent immediately! WTF? I am seriously bamboozled here. Can anyone explain to me what the hell is happening? Thanks in advance. ...OK, just before I was about to post this article, I discovered that if I change sys.stdout.close() to sys.stdout.flush() in my original program, I get the expected behavior! Gah! Am I to understand that in Python, closing a file does not flush the file? -- Sean McAfee etzwane at schwag.org From daniels at dsl-only.net Wed Dec 31 10:21:29 2003 From: daniels at dsl-only.net (sdd) Date: Wed, 31 Dec 2003 07:21:29 -0800 Subject: position in a for loop? In-Reply-To: References: <5.2.0.9.0.20031230213049.034cf0f8@mail.zomething.com> Message-ID: <3ff2f541@nntp0.pdx.net> Mark McEahern wrote: > On Tue, 2003-12-30 at 23:30, EP wrote: >>How I can tell where I am in a for loop? > Great question. Use enumerate (new with Python 2.3, I believe). >... So that'd be: > > hits = [] > foodItems = ['linguine','Spam','clams','Spam','steak'] > for i, item in enumerate(foodItems): > if item == 'Spam': > hits.append(i) or, to play along: foodItems = ['linguine','Spam','clams','Spam','steak'] hits = [i for i,food in enumerate(foodItems) if food == 'Spam'] -Scott David Daniels Scott.Daniels at Acm.Org From cliechti at gmx.net Sat Dec 6 17:44:34 2003 From: cliechti at gmx.net (Chris Liechti) Date: Sat, 6 Dec 2003 22:44:34 +0000 (UTC) Subject: Installing Python 232 onto CD-ROM References: Message-ID: Barry Newberger wrote in news:bnsbp- F285E6.14070206122003 at news.texas.net: > Wanted to install Python 2.3.2 for Windows onto a CD-ROM. Problem, my is there a reson to NOT use py2exe ? chris From joshway_without_spam at myway.com Tue Dec 30 11:08:34 2003 From: joshway_without_spam at myway.com (JCM) Date: Tue, 30 Dec 2003 16:08:34 +0000 (UTC) Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> <79v2vv0ijgdvqu354uh4mh21v4b3liurj0@4ax.com> <1072798233.200308@news.liwest.at> Message-ID: EsC wrote: > hy! > thanks for your explanations! > i want to avoid performance-problems by repeated (very often) > function-calls with very long strings. > in some languages (C, PHP, Powerbuilder, ...) i have the opportunity, > to pass "by value" or "by reference/pointer)". The text of the string is not copied; a reference to the string/object is passed into the function. You can modify objects passed into functions (but only if they're mutable--strings and integers are examples of immutable objects), but you cannot rebind the variable holding the value in the caller's scope. There have been some discussions in this newsgroup about whether Python is call-by-value or not. I'm not sure if I want to recommend looking for them; there was no good consensus about the terminology. From no at spam.invalid Thu Dec 18 14:45:39 2003 From: no at spam.invalid (Russell E. Owen) Date: Thu, 18 Dec 2003 11:45:39 -0800 Subject: Tkinter / Threads: "Invalid command name" References: <3fe1e985$0$11374$91cee783@newsreader01.highway.telekom.at> Message-ID: In article <3fe1e985$0$11374$91cee783 at newsreader01.highway.telekom.at>, Michael Schutte wrote: >...I want to write a server application; like telnet is a client. The user >should be able to bind() to a port and wait for a client. The written >and recieved data is stored in a Text widget, self.__text. The >accept()ing is done in a seperate thread (using the threading module), >in method self.__tryConnect(). >But the seperate thread raises an exception at > self.__text["state"]="normal" . >A part of the code: You should only deal with Tkinter from the main thread. (That was most certainly true in the past. I'm not quite positive that it is still supposed to be true, but I can assure you that it doesn't work well on my system.) I suggest you use a Lock or Queue or some other inter-thread communication object to let the accept thread communicate with the rest of the application. -- Russell (You might also want to use Twisted framework.) From jepler at unpythonic.net Fri Dec 5 11:37:47 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Dec 2003 10:37:47 -0600 Subject: Turning f(callback) into a generator In-Reply-To: References: Message-ID: <20031205163739.GM11102@unpythonic.net> On Wed, Dec 03, 2003 at 06:07:08PM -0800, Jimmy Retzlaff wrote: > My solution used threads. I'd love to know if someone comes up with a > solution not involving threads. Here's a simple example of my > thread-based approach: [...] In standard Python, this is the only approach that can work. It's possible that Stackless Python might provide a solution that doesn't involve OS threads, but I don't have any actual experience with Stackless. One problem with your code is the use of a sentinel value. Another poster suggested using multiple queues and a timeout to return exceptions or end-of-queue. Instead, you should use a queue but insert easily distinguishable items in it. For instance: None: end of iterator, raise StopIteration (0, a, b): exception in f, raise a, None, b (re-raise exception) (1, blah): callback got blah, return it from next() import sys, Queue, threading class CallbackGenerator: def __init__(self, func, pre=(), post=()): self.func = func if type(pre) is not tuple: pre = (pre,) if type(post) is not tuple: post = (post,) self.args = pre + (self.cb,) + post self.queue = Queue.Queue(maxsize=1) self.thread = threading.Thread(target=self.go) self.thread.start() def __iter__(self): return self def next(self): item = self.queue.get() if item is None: raise StopIteration if item[0] == 0: raise item[1], None, item[2] else: return item[1] def go(self): try: self.func(*self.args) except: info = sys.exc_info() self.queue.put((0, info[1], info[2])) else: self.queue.put(None) def cb(self, *args): self.queue.put((1, args)) # Example 1: os.path.walk -> generator import os for i in CallbackGenerator(os.path.walk, "/tmp", None): print i # Example 2: Prints 1, 2 then shows a traceback def f(cb): cb(1) cb(2) 1/0 for i in CallbackGenerator(f): print i From aahz at pythoncraft.com Sun Dec 7 11:05:44 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2003 11:05:44 -0500 Subject: Best structure for (binary) trees? References: Message-ID: In article , Rasmus wrote: > >As partly novice in python I would like a piece of advise of how to >implement (binary) trees the best way? Assuming that nodes also contain data: class Node: def __init__(self, data): self.data = data self.left = self.right = None Assuming that you're a CS student looking for homework help, I'll leave the rest of the implementation as an exercise. You might also consider looking at the bisect module. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From rudy.schockaert at pandoraSTOPSPAM.be Sat Dec 6 12:17:28 2003 From: rudy.schockaert at pandoraSTOPSPAM.be (Rudy Schockaert) Date: Sat, 06 Dec 2003 17:17:28 GMT Subject: FAQ or HOWTO on windows event logs In-Reply-To: References: Message-ID: David Bear wrote: > I would like to develop some tools to better understand/analyze > windows event logs. What I've done is export the event log as a > delimited file, then try to use awk or python to parse the info. > There must be an easier way... The format of the event changes with > the event, so it seems impossible to write a generalized parser. > > I guess i'm look for tricks -- recommendations on what others have > found to be effective ways to deal with windows events log data. My > goal would be to get the data in a format where I can run correlations > on events. For example, I would like to see when a system event (a > dcom buffer overflow) occurs and then see if an event in the > application log like a crashed ocx occurred at the same > time.. Obviously this is for intrusion analysis... > > Any advice? Have you had a look at Mark Hammond's Win32all? There is a module called win32evtlog that you can use to dump the windows eventlogs. You already have the data in a comfortable format there. Here's an example: import win32evtlog, win32security from win32evtlogutil import * def ReadLog(computer, logType="Application", dumpEachRecord = 0): # read the entire log back. h=win32evtlog.OpenEventLog(computer, logType) numRecords = win32evtlog.GetNumberOfEventLogRecords(h) print "There are %d records" % numRecords num=0 while 1: objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0) if not objects: break for object in objects: # get it for testing purposes, but dont print it. msg = SafeFormatMessage(object, logType).encode("mbcs") if object.Sid is not None: try: domain, user, typ = win32security.LookupAccountSid(computer, object.Sid) sidDesc = "%s/%s" % (domain, user) except win32security.error: sidDesc = str(object.Sid) user_desc = "Event associated with user %s" % (sidDesc,) else: user_desc = None if dumpEachRecord: if user_desc: print user_desc print msg num = num + len(objects) if numRecords == num: print "Successfully read all", numRecords, "records" else: print "Couldn't get all records - reported %d, but found %d" % (numRecords, num) print "(Note that some other app may have written records while we were running!)" win32evtlog.CloseEventLog(h) logType = "Application" computer = None # use local machine verbose = 1 ReadLog(computer, logType, verbose > 0) From mwh at python.net Sun Dec 28 13:50:02 2003 From: mwh at python.net (Michael Hudson) Date: Sun, 28 Dec 2003 18:50:02 GMT Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: bhoel at web.de (Berthold Hoellmann) writes: > Hello, > > When I use > > ./configure --with-thread --with-fpectl --with-signal-module \ > --with-pymalloc --enable-shared --with-cxx=g++ > > make test What platform, compiler, and versions thereof? > > on 2.3.3 I get > > ... > test_queue > test_quopri > test_random > test_re > make: *** [test] Speicherzugriffsfehler (Speicherauszug erstellt) > > gdb ./python core.29964 > GNU gdb 5.3.93 > Copyright 2003 Free Software Foundation, Inc. > ... > Reading symbols from /home/devel/compile/Python-2.3.3/build/lib.linux-i686-2.3/pyexpat.so...done. > Loaded symbols for /home/devel/compile/Python-2.3.3/build/lib.linux-i686-2.3/pyexpat.so [snippety] > Some kind of "infinite" recursion? Well, there's a test in tes_sre that uses quite a lot of C stack. I guess it's possible that something about shared library code uses more stack. Can you run 'ulimit -s ' and try again? Cheers, mwh -- Lisp does badly because we refuse to lie. When people ask us if we can solve insoluble problems we say that we can't, and because they expect us to lie to them, they find some other language where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp From karl at comet.ucar.edu Tue Dec 2 16:05:57 2003 From: karl at comet.ucar.edu (Karl Hanzel) Date: Tue, 2 Dec 2003 14:05:57 -0700 Subject: Build failing on Solaris In-Reply-To: <0vTyb.372175$0v4.19421587@bgtnsc04-news.ops.worldnet.att.net> References: <0vTyb.372175$0v4.19421587@bgtnsc04-news.ops.worldnet.att.net> Message-ID: > > ... > Certain versions of binutils do not correctly support dynamic linking on > Solaris, which gives rise to symptoms similar to the ones you are > seeing. I am pretty sure that binutils 2.13.2.1 works. To find out > whether the version on your machine works, you can execute the following > shell script... Thanks, Andrew. As you suspected, your script generates the seg fault & returns the same errant "139" observed during the build of Python. I'll install an updated 'binutils' package and try again. Karl *-----> From engsolnom at ipns.com Tue Dec 30 20:40:03 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Tue, 30 Dec 2003 17:40:03 -0800 Subject: NEWBIE: Sub-Classes Message-ID: <7e94vvkavbuhn6me8cruj1buj7ld20i5ku@4ax.com> I'm a bit baffled. In the code below, I expected that the import in tst_sub.py would expose all the contents of dir_a.py. But, as it turns out...it doesn't. I can understand (I think) why B has to be qualified in class A(dir_a.B), but why is dir_a.B.class_B required? Also, how can I expose self.B_self to A? Thanks......Norm DIRECTORY DIRA: DIR_A.PY: var = 13 class B: class_B = 21 def __init__ (self): self.B_self = 31 def B_meth_1(self): self.class_B = 19 DIRECTORY MYFILES: TST_SUB.PY: import dir_a print dir_a.var class A(dir_a.B): def __init__ (self): self.B_meth_1() # Run the base class B method self.class_a = self.class_B # Gets the value in B_meth_1 self.class_aa = dir_a.B.class_B # Gets B's 'static' var print self.class_a print self.class_aa # Prints 13 obj_1 = A() # Prints 19, 21 obj_2 = A() # Prints 19, 21 showing A.__init__() was run again From jobs at kandidates.com Tue Dec 2 15:46:19 2003 From: jobs at kandidates.com (Jobs) Date: Tue, 2 Dec 2003 15:46:19 -0500 Subject: Python/Zope Jobs Message-ID: <008d01c3b915$571128e0$0200a8c0@nyc.rr.com> I just added a Python/Zope section (kandidates.com/python.htm) to my website and I want to get some more profiles on it to attract more attention. If you are interested in getting listed (it's free), please send me an updated Word (or text) resume with your hourly and/or full time salary requirement, the locations you're willing to work and a brief description of your Python and/or Zope-related skills / years experience. Thank you, Beau Gould http://www.kandidates.com/python.htm Python and Zope Jobs Yahoo Group http://groups.yahoo.com/group/pythonzopejobs -------------- next part -------------- An HTML attachment was scrubbed... URL: From pythonguy at Hotpop.com Fri Dec 19 06:18:02 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 19 Dec 2003 03:18:02 -0800 Subject: Hiding console with program compiled in PY2EXE References: <4378fa6f.0312182234.42c4fe73@posting.google.com> Message-ID: <84fc4588.0312190318.5f679db1@posting.google.com> The way to prevent a py2exe program from throwing up a console is to pass the '--windows' option to it. i.e change your py2exe command line from %python setup.py py2exe to %python setup.py py2exe --windows HTH. -Anand mnations at airmail.net (Marc) wrote in message news:<4378fa6f.0312182234.42c4fe73 at posting.google.com>... > Hi all, > > I know that to hide a console normally you simply change the extension > from .py to .pyw. That's simple enough. However I can't seem to > accomplish the same thing after freezing the program. I've tried > building the setup file with the python script as a .pyw file, but it > crashes and doesn't give me a reason. This is of course because the > debug window doesn't open, so you don't know what happened (ahh, the > irony). > > Does anyone know how to successfully freeze a program with py2exe? > > Many thanks, > Marc From noemail at noemail4u.com Fri Dec 19 07:27:54 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 19 Dec 2003 12:27:54 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: On Thu, 18 Dec 2003 18:25:27 +1300, "Greg Ewing (using news.cis.dfn.de)" wrote: >Stian S?iland wrote: >> When is this issue going to be resolved? Enough newbie-pythoners have >> made this mistake now. > >Changes are rarely if ever made to Python for the sole reason >of reducing newbie mistakes. There needs to be a payoff for >long-term use of the language as well. I strongly concur with this principle. Too often, I've been on a team that goes to such efforts to make a system easy for newbies to learn that the normal/advanced users are then handicapped by a dumbed-down interface. E.g., after you've performed some process enough times, do you *really* need a step-by-step wizard? --dang From phleum_nospam at chello.se Thu Dec 11 12:46:49 2003 From: phleum_nospam at chello.se (Carl) Date: Thu, 11 Dec 2003 18:46:49 +0100 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I've been approached about writing a Windows app which will need a > really professional looking GUI. Forget TKinter, this has to actually > look good (real artists will be available to get the visual stuff > right). Assuming I write in Python, what's the best toolkit to use? > Some cost in implementation pain is tolerable if the finished > interface looks better as a result. It would be nice if the toolkit > runs on multiple platforms rather than being Windows-only. > > I'm thinking Glade. Is that reasonable? I don't know squat about > Windows and haven't done much fancy GUI programming since the early X > days. > > Thanks. What's wrong with Jython? I haven't used it myself, but have always wondered why it's not mentioned when different Python GUI:s are discussed. Carl From niemeyer at conectiva.com Sat Dec 13 15:18:36 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 13 Dec 2003 18:18:36 -0200 Subject: ANN: lunatic-python 0.1 In-Reply-To: References: Message-ID: <20031213201836.GA18475@burma.localdomain> > Why the https? > > I expect you have a good explanation, [...] Unbelievable... -- Gustavo Niemeyer http://niemeyer.net From birdiepageANTI at SPAMciudad.FILTERcom.ar Wed Dec 17 09:45:46 2003 From: birdiepageANTI at SPAMciudad.FILTERcom.ar (Gustavo Campanelli) Date: Wed, 17 Dec 2003 11:45:46 -0300 Subject: change dpi without changing pixels dimensions with PIL? In-Reply-To: <3fe01f2a$0$44014$e4fe514c@dreader9.news.xs4all.nl> References: <3fe01f2a$0$44014$e4fe514c@dreader9.news.xs4all.nl> Message-ID: duikboot wrote: > Hi there, > > In Photoshop I can, when I want to change the dpi(dots per inch) of a > picture, arrange that the picture won't be resized. Do you know of a way, I > can accomplish this in python with PIL? If I use this script it changes the > dpi, but the picture becomes huge. > > Thanks > I might be completely wrong, but I think you have an error here. Basically, a monitor has a set resolution (the resoultion at which you run your graphics card). That resolution has a certain number of dots per inch. So, if you increase the dots per inch of an image, you are making it bigger and will require more monitor space or page area to show or print it. What you are doing with Photoshop, most probably, is increase the Dots Per Inch (DPI) AND rescaling it only for viewing purposes on your screen. So although you see it the same size, the picture surely is bigger. If that's the case, your script is doing what it's supposed to do, but you need to "fit to screen" or something like that if you want it to remain the same size ONLY for viewing purposes. Gedece From jmdeschamps at cvm.qc.ca Sun Dec 7 15:55:38 2003 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 7 Dec 2003 12:55:38 -0800 Subject: Help: Uploading .zip to Python CGI References: Message-ID: <3d06fae9.0312071255.44609881@posting.google.com> hwlgw at hotmail.com (Will Stuyvesant) wrote in message news:... > I am uploading a .zip file to a Python CGI program, using a form on > a HTML page with > > ... > > In the Python CGI program I do: > > import cgi > fStorage = cgi.FieldStorage() > zipdata = fStorage['yourfile'].value > print "Content-type: text/plain" > print > print len(zipdata) > > Now the length of the zipdata is 100, where it should be about > 2635...and unzipping it with zipfile of course gives the "not a zip > file" error. > > The last part of the data that is received by the CGI script is: > > \xf2\xf1!0\xdbS\xa9 > > and the next one *should* be \x1a > > It seems that the .zip data is being truncated, but I don't know where > in my tool chain. > ... > Does anybody have a clue what is going on? > > Maybe the error is with the Windows version of Apache? Or is it a > Python problem (the unix server has Python 2.1.1). Had a similare problem with *.jpg uploads uploading files with a shebang such as: #! c:/python23/python -u reolved it for me the -u part telling Windows to get data "unbuffered", so I read somewhere... Good weekend, JM From piffenpauffer at yahoo.com Sat Dec 13 16:13:15 2003 From: piffenpauffer at yahoo.com (Milo K. Piffenpauffer) Date: 13 Dec 2003 13:13:15 -0800 Subject: Examples and Tutorials of SocketServer? Message-ID: <826b6ec2.0312131313.10769cda@posting.google.com> I've looked on Google for examples of using the SocketServer module, but I'm not having much luck. The online documentation is pretty sparse, and PyDoc isn't very clear. Does anyone know where I could find an example of SocketServer that explains what the various features of the code do? Milo From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 17 07:25:05 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 17 Dec 2003 13:25:05 +0100 Subject: udp broadcast example, please In-Reply-To: References: Message-ID: <3fe04b22$0$235$e4fe514c@news.xs4all.nl> Torsten Rueger wrote: > sorry, but I've searched and searched to find exact information on how > to do a simple udp broadcast client/server, but can find it: Have you searched on your hard drive? It's right there: Demo/sockets/udpecho.py in the python source tree. --Irmen From R.Brodie at rl.ac.uk Wed Dec 17 09:21:19 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 17 Dec 2003 14:21:19 -0000 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.247.1071669014.9307.python-list at python.org... > > I'm no big fan of Sun or Java, but that's quite some industry > > leadership you're showing us, Brandon. ;-) > > eh? are you saying that all Hejlsberg knows about programming language > design is stuff he picked up while working on a Java implementation? Surely not. There is little doubt that C# was in part a reaction to the failure of J++ to be a serious competitor to Java. Whether you regard it as taking a lead, or following Sun, is largely a matter of interpretation. That is independent of Hejlsberg's ability as a language designer. That said, Brandon's claim was fairly contentious and likely to get someone to bite. It's a well worn debate though, and c.l.py probably isn't the best place to renew it. From fredrik at pythonware.com Wed Dec 10 09:06:38 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Dec 2003 15:06:38 +0100 Subject: About the use of **args References: Message-ID: Jacek Generowicz wrote: > I find the suggestion that a mangled name is somehow "more private" > than one with a single leading underscore, mildly insulting to the > clients of your code. The implcation is that they can neither work out > the (very complicated and cryptic[*]) mangling scheme, not use dir(). no, the implication is that they can use their own __variables without having to think about what you're calling your private parts. in contrast, a _variable is not hidden at all. From hokiegal99 at hotmail.com Mon Dec 22 11:44:46 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 22 Dec 2003 11:44:46 -0500 Subject: Count Files in a Directory In-Reply-To: References: <93f5c5e9.0312211545.363b91a6@posting.google.com> <3FE717C5.1030102@hotmail.com> Message-ID: Peter Otten wrote: > hokieghal99 wrote: > > >>Thanks for the tip... this bit of code seems to work: >> >>def fs_object_count(path): >> file_count = 0 >> dir_count = 0 >> for root, dirs, files in os.walk(path): >> for fname in files: >> file_count += len(fname) >> for dname in dirs: >> dir_count += len(dname) > > # should return something, e. g: > return dir_count, file_count > >>fs_object_count() > > > No! You are calculating the total number of characters. Suppose path has two > subdirectories "alpha" and "beta". Your function would calculate a > dir_count of 9 instead of 2. > > Instead of the inner for loops just add the length of the dirs list which is > equal to the number of subdirectories: > > #untested > def fs_object_count(path): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > file_count += len(files) > dir_count += len(dirs) > return dir_count, file_count > fs_object_count("/home/alone/II") > > Peter Wow!!! What an obvious error. I've drank too much coffee this morning. We would have caught something this bad in testing. Thanks for the help... you've saved me a bit of embarassment. From jzgoda at gazeta.usun.pl Sat Dec 13 02:37:08 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 13 Dec 2003 07:37:08 +0000 (UTC) Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3FD9D38F.C85433C9@engcorp.com> Message-ID: Cameron Laird pisze: >>There are times, when Tkinter doesn't work at all, i.e. on >>"second-half-of-world" terminals (non-ASCII/non-LATIN1). wxPython has no >>problems there. Yes, I know, it's due to flaws in TCL/Tk, not in Tkinter >>itself. But all Pythons ship with this flawed, broken, unusable Tk. And >>don't even try to argue, that my customers can "build their own Tk with >>bcc32 or OpenWatcom", they dont need to do anything more than install >>wxPython from readily-available binary distribution. > . > It surprises me that you write that. I regard Tcl as the > language which has gone the farthest in internationalization, > apart from Java, and the one which makes such delights as > feasible. > > Do you know what it is that's broken? There are several > people on both the Tk and Python sides who are eager to learn > of faults, so that they can fix them as soon as possible; I'll > be glad to help you direct your report so that it's resolved > without delay. I raised your comments with the head of Tcl > support at ActiveState; he replied, in part, "Tk was the first > of the open source cross-platform UI toolkits to have full > unicode support, end-to-end. There are no flaws in Tcl/Tk in > this regards, and AFAIK this works just fine in Tkinter as well" > [reproduced with permission]. No, I don't mean "broken unicode support", the problem lies in Python interfacing with Tk, when Python's unicode means something different, than Tk unicode. I'll try to produce some examples of erroneous behavior on both X11 and Windows NT and file bug report on SF. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From zunbeltz at wm.lc.ehu.es.XXX Wed Dec 3 08:14:19 2003 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 03 Dec 2003 14:14:19 +0100 Subject: Python, xml, databases, ... References: <3fcdbd79@mail.netspeed.com.au> <3fcdd93f@mail.netspeed.com.au> Message-ID: Rasjid Wilcox writes: > >> On Windows, both MySQL and PostgreSQL rely on the Cygwin dll. It looks > >> like MySQL has an easier Windows install, but their use of the cygwin dll > >> outside of Cygwin proper has serious stability consequences if the user > >> installs another cygwin based program. PostgreSQL is a 'proper' cygwin > >> program, but will be harder for non-unix/linux people to > >> install/administer. > >> > >> You could also consider Firebird (http://firebird.sourceforge.net/) it > >> has a native Windows version as well as a Unix/Linux version) or SQLite > >> (http://www.hwaci.com/sw/sqlite/) with PySQLite > >> (http://pysqlite.sourceforge.net/manual.html). > >> > >> There is also GadflyB5 (http://gadfly.sourceforge.net/) which looks like > >> it > >> is written in pure python. There are probably other options too. > >> > > > > Can you give me an advaice about what has a better easy to > > use/performance ratio. > > Unfortunately, no, since I'm at about the same stage you are (ie, trying to > work out what to use). > > I have _personally_ rulled out MySQL on Windows (due to it packaging the > cygwin dll in a non-standard way, since I use Cygwin at work), and will > only consider PostgreSQL on Windows if I can make the install trivial for a > non-technical user. > > SQLite does not support Foreign Key constraints, so I think it is out for > me. Gadfly is not multi-user, so it is also out for me also. > > Firebird is the only full featured open-source database that I know of that > has native binaries (non-cygwin) for Windows, and also runs on Linux and > Mac (although a native Windows port of PostgreSQL is in progress). > > Another option that I have is to on Windows use the MDAC component and use a > MS Access backend database, and use MySQL or PostgreSQL on Linux/Mac. > See http://www.markcarter.me.uk/computing/python/ado.html for some info on > how to access a MS Access database from Python on Windows. > > Without knowing what SQL feature set _you_ are after, it is impossible to > know what is the best option for you. > Thanks for your advaice and i will think more carefully what i nedd and read information about the dbs you mention. > > > > I have no see the question yet :-) > > My question was entitled 'Building a GUI agnostic database application'. > I am reading it know. thanks Zunbeltz > Cheers, > > Rasjid. > -- Remove XXX from email: zunbeltz at wm.lc.ehu.esXXX From mgerrans at mindspring.com Tue Dec 16 03:07:25 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Tue, 16 Dec 2003 08:07:25 GMT Subject: Sleep()? References: <3fde71e8$1@clarion.carno.net.au> Message-ID: <13zDb.6531$Pg1.5718@newsread1.news.pas.earthlink.net> "Steve" wrote: > Is there some way to implement a timer in python? I want to open a > process and pipe a log out of it every 10 minutes. How can I do this? Thanks I think the Timer class in the threading module sounds like exactly what you want. From martin at v.loewis.de Thu Dec 11 16:08:40 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Dec 2003 22:08:40 +0100 Subject: minidom and pulldom References: Message-ID: pinto at map.com (David Pinto) writes: > I'm trying to use either the minidom or pulldom to find table tags in > html web pages. I've tried parsing two web pages that show up fine in > my browser, but I get errors when I call minidom.parse, or try to get > events with pulldom. Is there a parser that is as forgiving as web > browsers? minidom is an XML parser. Most Web pages are not XML, but some form of HTML. You should have better chances with parsing HTML using htmllib. Regards, Martin From lists at webcrunchers.com Tue Dec 16 18:37:22 2003 From: lists at webcrunchers.com (JD) Date: Tue, 16 Dec 2003 15:37:22 -0800 Subject: I see advice on how to debug a python module that hangs up the process In-Reply-To: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: On Dec 16, 2003, at 2:45 PM, Robin Munn wrote: > The first step I'd suggest is to sprinkle print statements all around > your code: > > print "About to call some_func()..." > some_func() > print "Returned from calling some_func()..." > > Then you can watch the console output (or redirect it to a file for > later perusal) and see when the thing hangs. We already know the function it hangs up at. It's a Python function we defined. Obviously, we put a print statement right at the beginning of the errant function, but it doesn't appear to be getting there. IE: print "before function call" my_function(some_arguments) print "after function call" def my_function(some_arguments): print "start of function call" <--- this never gets called, or we don't see the output So when this piece of code is called, we get: before function call Then, we have to do a "kill -9" the process. John From martin at v.loewis.de Tue Dec 16 15:08:37 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Dec 2003 21:08:37 +0100 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031216195200.GI17021@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195200.GI17021@lkcl.net> Message-ID: Luke Kenneth Casson Leighton writes: > > I fail to see how ACLs are a sound basis to solve the problem that > > rexec solves. ACLs, in my view, are a sound basis to solve a different > > problem (that of different identities accessing the same resources). > > substitute "identity" for "calling object" i.e. function and i > believe that there is a viable proposal. I don't think so. Suppose I have an object A protected by ACLs. Now I write a new method def doit(): A.doit() Question 1. What is the calling object? Question 2. Assuming it is "the doit function", and assuming the doit function is not listed in the ACL: Will the call be executed? If yes: What is the purpose of the ACL then? If no: I believe the proposal is not usable in practice. For example, what should be the ACL on calling open()? Regards, Martin From _ at _._ Wed Dec 10 20:31:59 2003 From: _ at _._ (Apollo) Date: Thu, 11 Dec 2003 01:31:59 GMT Subject: Python progamming certification In-Reply-To: <87fzfuszsq.fsf@pobox.com> References: <87fzfuszsq.fsf@pobox.com> Message-ID: <3FD7C8ED.3000501@_._> John J. Lee wrote: > Maxim Khesin writes: > > >>>to know it once existed because I WROTE it. > > [...] > >>I should just mention that I got hit up for an interview last week due >>to my BrainBench C++ test. So they are not entirely worthless (even > > > C++ is one area where a simple test might be useful, though. Python, > much, much less so. > > [...] > >>the Python test is worth the $45 they are charging from that >>perspective since I suspect very few potential employers will be >>looking for Python programmers on BrainBench. But how can I convince employers that I know Python I have not programmed using Python in career before? From hungjunglu at yahoo.com Fri Dec 26 18:47:41 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 26 Dec 2003 15:47:41 -0800 Subject: callable classes References: Message-ID: <8ef9bea6.0312261547.3bea1464@posting.google.com> "Duncan Smith" wrote in message news:... > I recently started to rewrite a class and decided to take a bunch of related > methods and put them in a separate callable class. (They're all what I > would call pointwise operations on pairs of instances, they raise exceptions > for identical reasons, and they all return a new instance). It seemed like > a good idea at the time, but now I'm not so sure. So my very general > questions are: > > Is this a reasonable use for a callable class? Sure. As long as the children callable objects/classes share similar features that can be factored out to a parent object/class. But one problem is that Python overloads with () operator with class constructor. > In what circumstances are callable classes particularly useful? (Maybe I > haven't racked my brains long enough.) Your case is the representative case. :) The problem isn't with your line of thought. It is with Python, which has two drawbacks: (a) it's class-based OOP, instead of prototype-based as languages like Self or Io. So, usage of classes as objects becomes somewhat cumbersome. (b) The () operator is overloaded with class constructor call. The easiest way out is not to use the () operator directly. It is less confusing if you give it a name, like: result = my_child_method.process(x1, x2) Also, it is often easier to separate instances from classes. For your problem, I would do something like: class parent(object): g = "y = y + 4" def process(self, x, y): exec self.g return self.f(x) + y def f(self, x): return x class childA(parent): g = "y = y + 7" def process(self, x, y): result = parent.process(self, x, y) return result + 1 def f(self, x): return 3*x childA = childA() # this converts childA into an object class childB(parent): def process(self, x, y): self.g = "y = y + %d" % x result = parent.process(self, x, y) return result + 2 childB = childB() # this converts childB into an object print childA.process(1, 2) # prints 13 print childB.process(1, 2) # prints 6 This example shows that you have several ways to customize the behavior of the children methods. They could be made more specific if you describe your problem more in detail. But I guess you can figure out the rest on your own. regards, Hung Jung From razor-report at daimi.au.dk Sun Dec 7 09:35:53 2003 From: razor-report at daimi.au.dk (Rasmus) Date: Sun, 7 Dec 2003 15:35:53 +0100 Subject: Best structure for (binary) trees? Message-ID: Hi. As partly novice in python I would like a piece of advise of how to implement (binary) trees the best way? Thanks in advance, Rasmus PS: Due to heavy spam reception (20.000+/week), I use a fake sender address. Please answer in the newsgroup. Thanks From alia_khouri at yahoo.com Thu Dec 25 08:41:54 2003 From: alia_khouri at yahoo.com (Alia Khouri) Date: 25 Dec 2003 05:41:54 -0800 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> <3014031e.0312242351.d2604c2@posting.google.com> Message-ID: <40a939c9.0312250541.604cac66@posting.google.com> Ahmad: > I just wanted to tell everyone here, that none of the tips really > worked. The RTLstreamer class seemed so messed up, and printing > "\u200F" before my text didn't make any difference!! I can't beleive > that after all this time, unicode and bidi support still isn't working > nicely :( It's not so much that the RTLstreamer class is 'so messed up', but that, notwithstanding the generous efforts of its author, it remained untested with RTL Arabic script. Support for bidirectional text in python will be, as is the case with all open-source software, a function of how many interested people need the functionality or want to scratch a common 'itch'. Alia From hokiegal99 at hotmail.com Sun Dec 7 22:46:52 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 7 Dec 2003 19:46:52 -0800 Subject: finding files that have extensions References: <93f5c5e9.0312071154.4e7a1311@posting.google.com> Message-ID: <93f5c5e9.0312071946.65edf4aa@posting.google.com> "James Kew" wrote: > Take a look at os.path.splitext -- testing os.path.splitext(filename)[1] > will tell you if the filename carries an extension or not. That's a great tip!!! This bit of code does it: ext = os.path.splitext(fname) if not ext[1]: do the rename... From jjl at pobox.com Mon Dec 15 08:39:29 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Dec 2003 13:39:29 +0000 Subject: ANN: lunatic-python 0.1 References: <5meqtvc1pu8t6fpbtmvqh00h7hpvh0t9a8@4ax.com> Message-ID: <874qw28ajy.fsf@pobox.com> Tim Roberts writes: > Gustavo Niemeyer wrote: > > >> Why the https? > >> > >> I expect you have a good explanation, > > > >Unbelievable... > > I'm not sure I understand your disbelief. The web site is entirely static > text. I certainly do not understand why you chose to put this on an > encrypted connection with a self-issued certificate. Because: Gustavo wrote: > This is mostly a developers site. The https server is used > just to protect passwords from being sent as plain text. John From http Thu Dec 4 02:05:20 2003 From: http (Paul Rubin) Date: 03 Dec 2003 23:05:20 -0800 Subject: Python and Zope Jobs Yahoo Group References: Message-ID: <7xllpthxlb.fsf@ruckus.brouhaha.com> "Kandidates.com" writes: > Python and Zope Jobs Yahoo Group > http://groups.yahoo.com/group/pythonzopejobs Why don't you open the message archive to non-members. Nobody wants to give you their email address for spamming purposes just to see whether the posts there are actually interesting. Also, putting your announcement on this newsgroup once was fine. Putting it up several times a day is spamming. Please slow down. From garys at ihug.com.au Thu Dec 11 03:44:20 2003 From: garys at ihug.com.au (Gary Stephenson) Date: Thu, 11 Dec 2003 19:44:20 +1100 Subject: Pyrex problem - Py_NoneStruct References: <878ylkydx9.fsf@pobox.com> Message-ID: Hi John, "John J. Lee" wrote in message news:878ylkydx9.fsf at pobox.com... > "Gary Stephenson" writes: > > > I'm getting a clean generate, compile and link from my .pyx script, but when > > I attempt to run the resultant .exe, I get: > > Hmm, what resultant .exe? Are you using py2exe or similar, or is > there a feature of Pyrex I haven't noticed? I've always ended up with > a .so / .DLL. Err, yes ... I have used Pyrex before (successfully) using distutils to produce a .DLL. In this case, however, I am effectively attempting to embed Python within another language (Xbase++), so I am compiling the pyrex generated .c file using MSVC6 into an ..obj file and linking that into my Xbase++ app. It would appear that my problems arise from incorrect switches to cl.exe. fwiw, the switches I"m using are: /c /Zl /Tc I've searched high and low for some guidance on what the correct switches might be, but alas to no avail thus far. :-( > > > "The procedure entry point Py_NoneStruct could not be located in the > > dynamic link library python23.dll" > [...] > > Had this before, but forget what the problem is. Try, try .... please... > Try posting some Pyrex code (the pyrex list is probably a better place > than here). I have attempted to post this message along with the .pyx file to the pyrex list, but it would appear there is something wrong with my subscription as I have received neither my own message not anybody else's since subscribing :-( cheers, gary The following is a somewhat cut down version of my .pyx file whichl produces the error: from scanners import xppScanner ctypedef unsigned long ULONG ctypedef void * XppParamList ctypedef long BOOL ctypedef void * ContainerHandle cdef extern from "windows.h" : pass cdef extern from "xppdef.h" : pass cdef extern from "xppcon.h" : ULONG _conGetNL( void * hNumeric, long *nlValue) void * _conParam(void * pList, unsigned long paramIndex, long *bReference) void * _conPutC( void * hDest, char *string) void * _conPut( void * hDest, void * hSrc) BOOL _retnl(XppParamList pList, long numInt) BOOL _ret(XppParamList pList) unsigned long _conRLockC( void * hString, char **ppString, unsigned long *ulSize) unsigned long _conUnlockC( void * hString) cdef public BOOL C_OX_PYINITIALIZE( XppParamList pList ) : Py_Initialize() _ret( pList ) cdef public BOOL C_OX_PYFINALIZE( XppParamList pList ) : Py_Finalize() _ret( pList ) cdef public BOOL C_OX_XPPSCANNER( XppParamList pList ) : cdef ContainerHandle ch1 cdef ULONG nRslt,nLen cdef BOOL pRef cdef object oScan,cStr ch1 = _conParam( pList, 1, &pRef ) cStr = "test.prg" oScan = xppScanner( cStr ).gen() nRslt = oScan _retnl( pList, nRslt ) cdef public BOOL C_OX_XPPSCANNER_NEXTTOKEN( XppParamList pList ) : cdef ContainerHandle ch1,ch2,ch3 cdef ULONG nLen cdef BOOL pRef ch1 = _conParam( pList, 1, &pRef ) ch2 = _conParam( pList, 2, &pRef ) ch3 = _conParam( pList, 3, &pRef ) _conGetNL( ch1, &nLen ) oScan = nLen cTyp,cVal = oScan.next() _conPutC( ch2,cTyp ) _conPutC( ch3,cVal ) _ret( pList ) From http Sat Dec 13 07:32:41 2003 From: http (Paul Rubin) Date: 13 Dec 2003 04:32:41 -0800 Subject: "Do this, and come back when you're done" References: Message-ID: <7x8ylg5252.fsf@ruckus.brouhaha.com> Kamus of Kadizhar writes: > Is there any way to rewrite each half of the function to run in the > background, so to speak, and then have a master process that waits on > the results? This would cut execution time in half more or less. Sure, use the threading module. Think about another aspect of what you're doing though. You're comparing the md5's of a local and remote copy of the same file, to see if they're the same. Are you trying to detect malicious tampering? If someone tampered with one of the files, how do you know that person can't also intercept your network connection and send you the "correct" md5, so you won't detect the tampering? Or for that matter, do you know that the remote copy of the program itself hasn't been tampered with? From richie at entrian.com Tue Dec 2 09:21:42 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 02 Dec 2003 14:21:42 +0000 Subject: Separation of content and code for web (was Re: Python for web?) In-Reply-To: <3FCC9A98.193ED480@engcorp.com> References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> Message-ID: Peter, > One thing that I find interesting, after a 15-second perusal of the > examples, is how incredibly close our own fledgling implementation is, > to the point of matching the "clone template row, delete, fill in table > with replacements" sequence, almost down to the API. That's reassuring - at least I know I'm not the only one who thinks it makes sense. > I'm looking forward to a more extensive look at it. (I was about to say > I'd be happy to contribute improvements, but we (a company) were planning > to release our own under a BSD license at some point, whereas I see yours > has the more restrictive SleepyCat license (commercial use for a fee only), > so I'm afraid I might do nothing more than pick over the best ideas from > your API rather than look into the code itself.) Note that the Sleepycat license means "closed-source redistribution for a fee only" - any redistribution with full source is free, and commercial *use* on your own server machines is free (rather annoyingly for someone who wants to make money from server-based software but remain GPL-compatible and generally Open-Source-friendly). (If this sparks a licensing rant, *please* start a new thread, whoever does so!) If it's a choice between relicensing under the BSD license or being superseded by a better implementation released by you under a BSD license, I'd be quite happy to relicense PyMeld under a BSD license. I don't have the time to improve it myself, and I don't believe it's a viable commercial product for a lot of people because of its limited performance, so I'd rather it survived and grew under a completely free license than died. Improving the performance is not hard, but I don't have the time. You might want to also look at PyMeldLite, which is currently available as part of the SpamBayes project. That's Python-licenced, and has exactly the same API and capabilities as PyMeld. The reason it's 'Lite' is that it only works with perfectly valid XHTML, whereas PyMeld will work with any old real-world HTML you care to throw at it (pretty much). I haven't done a thorough test, but PyMeldLite is almost certainly faster in a lot of cases than PyMeld, and speeding it up is probably even easier. You can get it from here: http://cvs.sourceforge.net/viewcvs.py/*checkout*/spambayes/spambayes/spambayes/PyMeldLite.py?content-type=text%2Fplain&rev=1.7 or here: http://tinyurl.com/xcwb -- Richie Hindle richie at entrian.com From sombDELETE at pobox.ru Sun Dec 7 19:01:09 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Mon, 8 Dec 2003 03:01:09 +0300 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: Bengt, don't take it personally but this what happens when you use unicode unaware software: Quote from your message: > martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: Your software also doesn't specify message encoding. The real issue is to convince developers that there are many encodings in this world. Python should offer only one way to deal with multiple encodings. Your 8-bit strings with attached coding attribute is duplicating what unicode strings offer. > >> If e.g. name had latin-1 encoding associated with it by virtue of source like > >> ... > >> # -*- coding: latin-1 -*- > >> name = 'Martin Lowis' > >> > >> then on my cp437 console window, I might be able to expect to see the umlaut > >> just by writing > >> > >> print name > > > >I see. To achieve this effect, do > > > ># -*- coding: latin-1 -*- > >name = u'Martin Lowis' > >print name > Right, but that is a workaround w.r.t the possibility I am trying to discuss. It's not a workaround it's a solution. What you propose is a lot of effort for a little gain wrt handling multiple encoding. It's already possible to handle multiple encoding. The time is better spent converting everything that still deals with 8-bit text to handle unicode. -- Serge. From remco at localhost Mon Dec 15 08:39:02 2003 From: remco at localhost (remco) Date: Mon, 15 Dec 2003 14:39:02 +0100 Subject: Using readline with a new delimiter of line ? References: Message-ID: <3fddb97c$0$217$e4fe514c@news.xs4all.nl> "Laurent" wrote: >is it possible to read a file in python line by line >by redefining a new end-of-line delimiter ? > >I would like for example to have the string "END" being the new delimiter >for each line. > i couldn't find any builtin option. But of course you could always use: listOfLines = file('','r').read().split('END') Cheers! remco From dave at pythonapocrypha.com Thu Dec 11 12:20:50 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 11 Dec 2003 10:20:50 -0700 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <071a01c3c00b$20fb28d0$891e140a@YODA> Edward wrote: > I have a lot of experience with both wxPython and Tkinter. I would urge > caution regarding any quick judgments. All cross-platform toolkits have > significant bugs and design flaws. > > My experience is that Tkinter is the "least bad" and more flexible. > wxPython (of course) inherits all the _many_ bugs in wxWindows. > It's not clear that wxWindows really actually works. Isn't that last sentence a bit overly FUD-ish? Whether or not wxWindows is better or worse than Tkinter is beside the point - many successful applications are built on top of wxWindows and wxPython, so it's quite clear that it does actually work. -Dave From opengeometry at yahoo.ca Tue Dec 16 16:37:06 2003 From: opengeometry at yahoo.ca (William Park) Date: 16 Dec 2003 21:37:06 GMT Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: Heike C. Zimmerer wrote: > William Park writes: > > > hokiegal99 wrote: > >> import os, string > >> setpath = raw_input("Enter the path: ") #This can be hard coded. > >> for root, dirs, files in os.walk(setpath, topdown=False): > >> for fname in files: > >> s = string.find(fname, '.mp3') > >> if s >=1: > >> fpath = os.path.join(root,fname) > >> os.remove(fpath) > >> print "Removed", fpath, "\n" > > > > FYI, in shell, you would go > > find . -type f -name '*.mp3' | xargs rm > > Which will fail if the file name contains any spaces or other special > characters (not too unusual for .mp3 - Files). In which case, you look up 'man find xargs' and edit the command to find ... -print0 | xargs -0 ... -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From bokr at oz.net Fri Dec 19 21:31:04 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Dec 2003 02:31:04 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 20 Dec 2003 01:43:00 GMT, Carl Banks wrote: >Paul Rubin wrote: >> >> >> Carl Banks writes: >>> Consider something like this: >>> >>> def func(param=((1,2),(3,4),(5,6),(7,8))): >>> whatever >>> >>> Do you really want to be building a big-ass nested tuple every time >>> the function is called? >> >> Come on, the compiler can easily recognize that that list is constant. > >Yes, but that doesn't account for all expensive parameters. What >about this: > > DEFAULT_LIST = ((1,2),(3,4),(5,6),(7,8)) > > def func(param=DEFAULT_LIST): > pass > >Or this: > > import external_module > > def func(param=external_modules.create_constant_object()): > pass > >Or how about this: > > def func(param={'1': 'A', '2': 'B', '3': 'C', '4': 'D'}): > pass > > >The compiler couldn't optimize any of the above cases. For the DEFAULT_LIST (tuple?) and that particular dict literal, why not? > > >>> Python evaluates default args at time of definition mostly for >>> performance reasons (and maybe so we could simulate closures before we >>> had real closures). My gut feeling is, moving the evaluation to call >>> time would be too much of a performance hit to justify it. >> >> Python takes so many other performance hits for the sake of >> convenience and/or clarity that this particular one would be miniscule >> by comparison. > > >Well, I don't have any data, but my gut feeling is this would be >somewhat more than "miniscule" performance hit. Seeing how pervasive >default arguments are, I'm guessing it would be a very significant >slowdown if default arguments had to be evaluated every call. > >But since I have no numbers, I won't say anything more about it. > Don't know if I got this right, but [18:32] /d/Python23/Lib>egrep -c 'def .*=' *py |cut -d: -f 2|sum Total = 816 [18:32] /d/Python23/Lib>egrep -c 'def ' *py |cut -d: -f 2|sum Total = 4454 would seem to suggest pervasive ~ 816/4453 or a little less than 20% Of course that says nothing about which are typically called in hot loops ;-) But I think it's a bad idea as a default way of operating anyway. You can always program call-time evaluations explicitly. Maybe som syntactic sugar could be arranged, but I think I would rather have some sugar for the opposite instead -- i.e., being able to code a block of preset locals evaluated and bound locally like current parameter defaults, but not being part of the call signature. Regards, Bengt Richter From csad7 at yahoo.com Sun Dec 21 11:04:23 2003 From: csad7 at yahoo.com (christof hoeke) Date: Sun, 21 Dec 2003 17:04:23 +0100 Subject: empty EntityResolver for SAX Message-ID: hi, (the following description is a bit convoluted, sorry about that. i hope you understand it anyway...) i thought of providing an empty EntityResolver to my parse function that if i encounter xml files with DTDs in them these will not be processed. class EmptyEntityResolver(xml.sax.handler.EntityResolver): def resolveEntity(self, publicId, systemId): return "http://localhost/empty.txt" p = xml.sax.make_parser() p.setContentHandler(handler) p.setEntityResolver(EmptyEntityResolver()) i could use p.setFeature('http://xml.org/sax/features/external-general-entities',False) of course but i thought something like the above might be better for my purpose. my problem now is that something like return None does not work. only the above with the dummy empty.txt file needs to be present. is there a simpler way of returning an empty InputSource? thanks a lot chris From jcribbs at twmi.rr.com Thu Dec 11 23:41:03 2003 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Fri, 12 Dec 2003 04:41:03 GMT Subject: What GUI toolkit looks the best? In-Reply-To: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I've been approached about writing a Windows app which will need a > really professional looking GUI. Forget TKinter, this has to actually > look good (real artists will be available to get the visual stuff > right). Assuming I write in Python, what's the best toolkit to use? Wow! What a response this question has generated. I would have to throw my hat into the PyGTK ring, for both objective and subjective reasons. I think GTK looks great on Windows and my PyGTK apps have been very stable and responsive. On a more subjective note, for me, the PyGTK API just fits my brain better than the wxPython one does. It just feels more seemless to me and things make more sense when I look at them. Like I said, pretty subjective. Maybe you could write a small sample app using both PyGTK and wxPython and see which one feels right to you. Jamey From newsgroups at jhrothjr.com Sun Dec 28 22:03:04 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Dec 2003 22:03:04 -0500 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: wrote in message news:6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com... > Hi, > I've been using constructs(?) like the below. > > def display(instance, start = None, end = None): > > if instance.__class__.__name__ == 'UPCA': > do some UPCA stuff > if instance.__class__.__name__ == 'UPCE': > do some UPCE stuff > > launched by: > > lx = UPCA(sx), where sx is a string > then: > display(lx) > > This all works well. > > What I'd like to do is display is the instance name. Is it hiding > somewhere? > > Also, if I have a string 4 chars long, representing two bytes of hex, > how can I *validate* the string as a *legal* hex string? > > isdigit works until string = '001A', for example > isalnum works, but then allows 'foob' > > Is there a 'ishexdigit'? I could parse the string, but that seems > "un-Pythonish" > > Thanks in advane....Norm Instances don't have names. They do have IDs, though, which are the memory address of the instance objects in the C Python implementation. See the built-in function id(). John Roth From paul.koelle at archit.uni-weimar.de Mon Dec 15 06:25:46 2003 From: paul.koelle at archit.uni-weimar.de (paul) Date: Mon, 15 Dec 2003 12:25:46 +0100 Subject: cPickle from 2.2 to 2.1 In-Reply-To: References: Message-ID: Tim Peters wrote: > [paul] > >>I use cPickle in a small .cgi to save data. It run's fine on python >>2.2.3 (used for development) but fails on 2.1.1 (webserver) with: >> >> File "spyblog.py", line 543, in __init__ >> self.entry = cPickle.load(open(log + self.filename, 'r+')) >>SystemError: Failed to import class _reconstructor from module >>copy_reg [ --snipp-- ] > IOW, if you want to read current pickles under older Pythons, you have to > avoid pickling anything of a type that didn't exist in the older Pythons. > For another example, you can't expect a pickle of a Unicode string to get > unpickled under Python 1.5.2 either (since Unicode strings didn't exist in > 1.5.2). Thanks for pointing that out (seems rather obvious now ;). I thought pickle is a fast and convenient method to store/restore data. Now I see the drawbacks. BTW: It was a hack to avoid the xml.dom.minidom/unicode/non ASCII charset/codec/writer mess. Seems like I have to look at that once more. greetings Paul From rmunn at pobox.com Mon Dec 8 13:52:04 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 08 Dec 2003 18:52:04 GMT Subject: Help: Uploading .zip to Python CGI References: Message-ID: Will Stuyvesant wrote: > I am uploading a .zip file to a Python CGI program, using a form on > a HTML page with > > ... > > In the Python CGI program I do: > > import cgi > fStorage = cgi.FieldStorage() > zipdata = fStorage['yourfile'].value > print "Content-type: text/plain" > print > print len(zipdata) > > Now the length of the zipdata is 100, where it should be about > 2635...and unzipping it with zipfile of course gives the "not a zip > file" error. > > The last part of the data that is received by the CGI script is: > > \xf2\xf1!0\xdbS\xa9 > > and the next one *should* be \x1a \x1a is ASCII for Ctrl-Z, which is used in Windows as an EOF (End Of File) marker. > It seems that the .zip data is being truncated, but I don't know where > in my tool chain. Somewhere in your tool chain, something is opening a file in text mode instead of in binary mode. The fact that your CGI script works on Unix but fails on Windows is further proof that the Ctrl-Z is being treated as EOF on Windows, since Unix doesn't give that character any special meaning. -- Robin Munn rmunn at pobox.com From dman at dman13.dyndns.org Mon Dec 15 16:38:34 2003 From: dman at dman13.dyndns.org (Derrick 'dman' Hudson) Date: Mon, 15 Dec 2003 21:38:34 GMT Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com> Message-ID: On 15 Dec 2003 13:28:01 -0800, hokiegal99 wrote: > How can I make this script run w/o seeing a cmd popup window on the > screen? The script works well, but each hour (when the task scheduler > runs it) a brief cmd window appears and then goes away. It's only on > the screen for a second or two, but it's noticable. Use a better OS? <0.5 wink> Run it with pythonw.exe instead of python.exe. -- One OS to rule them all, one OS to find them, One OS to bring them all and in the darkness bind them, In the Land of Redmond, where the Shadows lie. www: http://dman13.dyndns.org/~dman/ jabber: dman at dman13.dyndns.org From fredrik at pythonware.com Tue Dec 9 02:46:18 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 08:46:18 +0100 Subject: Python supported web hosting? References: Message-ID: Jeff Wagner wrote: > Does anyone know of a good web hosting company who > supports Python? When I finally get my numerology program > written, I would like to put it on my web site for everyone > to be able to use but my present web host only supports > Perl CGI scripts. if you google for "Python hosting" and use the "I feel lucky" option, you'll end up here: http://www.python.org/cgi-bin/moinmoin/PythonHosting From aahz at pythoncraft.com Fri Dec 26 13:08:31 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Dec 2003 13:08:31 -0500 Subject: ANN: Python Language Reference References: Message-ID: In article , Stephen Ferg wrote: > >An attempt to produce a complete, alphabetized reference of all of >Python's language features. The purpose is support developers, who >need a quick way to look up information about a language feature. > >The table of contents was extracted from: > * the index of the language reference > * the index of the library reference > * the global module index > >http://www.ferg.org/pyref/index.html Looks good! I've added it to my bookmark list. Note that there's at least some missing stuff: __new__() isn't there. You might want to add descrintro to your set of resources. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From bhan at andrew.cmu.edu Mon Dec 22 02:08:21 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Mon, 22 Dec 2003 02:08:21 -0500 (EST) Subject: test if a file is locked? In-Reply-To: References: Message-ID: On Mon, 22 Dec 2003, Carl Banks wrote: > Fortepianissimo wrote: > > > > > > I can lock a file using the following snippet: > > > > --- > > import fcntl > > > > f=open('flock.txt','w') > > fcntl.lockf(f.fileno(),fcntl.LOCK_EX) > > --- > > > > If some other script tries to open 'flock.txt', it'll wait until the > > file is unlocked/closed. > > > > My question is, I'd like to tell a script to quit *immediately* if it > > cannot open the file, or, if it knows the file is locked. > > > > The reason I need this is I want to serialize parallel processes using > > a lock file. Any suggestion is welcome! > > > Try this: > > fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB) Ok looks like I'm still missing something: so how do you get 'f' without using open() or file()? Either of these will put the script on hold... Thanks! From sebastien.giraud at eds.com Fri Dec 19 08:55:26 2003 From: sebastien.giraud at eds.com (Giraud, Sebastien) Date: Fri, 19 Dec 2003 13:55:26 -0000 Subject: Windows always scroll up and it souldn't Message-ID: HI, I was wondering how to make a chat window work fine : the one where the text appear. I have one big problem : it always scroll up when new text is added. I work with PyQt 2.3 for windows... If someone have an answer to my issue... Regards. S?bastien GIRAUD EDS - France, p?le TMA-ERP 8, rue de l'H?tel de Ville 92522 Neuilly-sur-Seine Tel : 01.55.61.20.51 Portable : 06.84.21.36.06 Mail : > From jepler at unpythonic.net Thu Dec 25 15:20:57 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 25 Dec 2003 14:20:57 -0600 Subject: How does "delegation" work as per the FAQ? In-Reply-To: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> References: <10gmuvc8pqt5opt7o4l6qp1683kf7sl2f3@4ax.com> Message-ID: <20031225202057.GA28941@unpythonic.net> In Python, there's little difference between f = o.m f(3) and o.m(3) either way, the attribute 'm' is looked up on o in exactly the same way. So the delegation pattern works no matter whether 'o.m' is a method or is data. Jeff From danb_83 at yahoo.com Fri Dec 26 01:05:21 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 25 Dec 2003 22:05:21 -0800 Subject: indendation question References: Message-ID: km wrote in message news:... > Hi all, > > What is the standard and recommended way of indendation one should get to use > in python programming? is it a tab or 2 spaces or 4 spaces? i am confused. > kindly enlighten It doesn't matter how much indentation you use, as long as you're consistent. But it is recommended to never use tabs, and *strongly* recommended to never mix tabs and spaces. I usually use 3 spaces. Most of the regulars on this newsgroup use 4. From s.m.gutstein at worldnet.att.net Mon Dec 29 14:13:25 2003 From: s.m.gutstein at worldnet.att.net (Steven Gutstein) Date: Mon, 29 Dec 2003 19:13:25 GMT Subject: Installing PyOpenGL - can't find libnumarray module Message-ID: This is probably a fairly newbie type problem, but I'm trying to use PyOpenGL, and don't seem to have installed it correctly. I'm running Python 2.3 on a Windows NT machine. Whenever I go into IDLE and type from OpenGL.GL import * I get a flagrant crash which shuts down IDLE. The error message I get (as well as I could copy it) is as follows: Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\scintilla\formatter.py", line 222, in OnStyleNeeded notify = self.scintilla.SCIUnpackNotifyMessage(extra) File "C:\Python23\lib\site-packages\Pythonwin\pywin\scintilla\control.py" , line 57, in SCIUnpackNotifyMessage margin = margin) ImportError: No module named libnumarray win32ui: Exception in OnNotify() handler The main problem seems to be the lack of a libnumarray module. However, I have already installed numarray, and have verified that it's in my sys.path: >>> sys.path ['', 'c:\\dislin\\python', 'C:\\WINDOWS\\System32\\python23.zip', 'C:\\Python23\\lib\\site-packages\\Pythonwin', 'C:\\Python23\\lib\\site-packages\\win32', 'C:\\Python23\\lib\\site-packages\\win32\\lib', 'C:\\Python23\\lib\\site-packages', 'C:\\Python23\\DLLs', 'C:\\Python23\\lib', 'C:\\Python23\\lib\\plat-win', 'C:\\Python23\\lib\\lib-tk', 'C:\\Python23', 'C:\\Python23\\Deitel_Examples', 'C:\\Python23\\lib\\site-packages\\Numeric', 'C:\\Python23\\lib\\site-packages\\PIL', 'C:\\Python23\\lib\\site-packages\\gist', 'C:\\Python23\\lib\\site-packages\\numarray', 'C:\\Python23\\lib\\site-packages\\PythonPrograms'] It's the next to last entry. Inside my numarray directory there is a file libnumarray.pyd. I reinstalled numarray & checked the version for Python2.2. All I see in each version is libnumarray.pyd. Is there anything obvious that I'm missing or should try ? Thanks, Steven Gutstein From fpetermaas at netscape.net Tue Dec 9 05:00:07 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Tue, 09 Dec 2003 11:00:07 +0100 Subject: popen In-Reply-To: <36153c56.0312082323.67249ea@posting.google.com> References: <36153c56.0312082323.67249ea@posting.google.com> Message-ID: Faith schrieb: > hi all, > I am trying to run a batch file from my python program, in the end of > the batch file I call a command called creterelease but for some > reason its not being executed.. I know there is nothing wrong with the > bacthfile cause it worked fine when I run it from the command line .. Have you supplied the full pathname? As far as I know path search is done by the shell, not by popen(). Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From andrew-pythonlist at puzzling.org Thu Dec 11 05:43:26 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 11 Dec 2003 21:43:26 +1100 Subject: ANN: Twisted 1.1.1 In-Reply-To: References: <8765gowgp7.fsf@mobile.foo> Message-ID: <20031211104326.GA23474@frobozz> On Wed, Dec 10, 2003 at 11:11:40PM +0100, Just wrote: > > This ties nicely into the xsdb + stackless discussion: > > - threads + blocking sockets is attractive since the code can be > written in a natural style, yet cause overhead and > synchronization headaches. > > - async sockets are attractive because they avoid threads and > therefore avoid overhead and synchronization issues. Yet it > is often a bit harder to code, since you need to turn your > code inside out, using callbacks. > > But there is a "perfect" solution: co-routines. With co-routines you can > both write the code in a "natural" style, but still using an even-driven > core. This is a very pleasant model to work with, so I totally > understand that some people (eg. Aaron) choose to use Stackless to make > this possible. co-routines miss one of the features of the threading model, though, which is preemptive concurrency. I prefer the async way of working too, but I can see that co-routines don't provide the best of both worlds... -Andrew. From aleax at aleax.it Thu Dec 25 12:10:09 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Dec 2003 17:10:09 GMT Subject: replace line #1 with "newline\n" in text file References: <3fe955b8.0@news1.mweb.co.za> <3FE95743.AB5B23F8@alcyone.com> Message-ID: Erik Max Francis wrote: > bmgz wrote: > >> I am trying to replace the first line of a config file.. with a new >> string >> been googlizing and reading the python manual.. but can't find what I >> need.. >> it's all rubbish about bits and bytes etc.. > > You'll have to read in the file, write out a temporary one, and then > move the new one over the old one. Yes, that's basically what fileinput (which I suggested in my other msg in this thread) does for you behind the scenes. Of course, such complication is typically only worth it for potentially big files -- for a small file, one might prefer a "rewrite-in-place" approach, e.g.: f = file('thefile.txt', 'r+') lines = f.readlines() lines[0] = "the new line goes here\n" f.seek(0) f.writelines(lines) f.close() This should be fine unless the file is huge OR you're unlucky enough that the machine crashes right while you're rewriting the file...;-) Alex From sombDELETE at pobox.ru Tue Dec 23 15:45:45 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Tue, 23 Dec 2003 23:45:45 +0300 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> <8765g7jp6j.fsf@pobox.com> Message-ID: "John J. Lee" wrote in message news:8765g7jp6j.fsf at pobox.com... > Fran?ois Pinard writes: > [...] > > [1] I mean, nearly French, as the necessary diacritics may not be > > used in Python identifiers, which is a common and constant source of > > displeasure to those of us who especially like working in French. Oh, > > Python does not differ on this aspect than most other programming > > languages. However, as Python is so satisfying in many other areas, we > > had some vague hope that he might become better in this particular one. > > Especially given that, for a tiny moment, it once worked correctly for > > French -- but sadly, this was the consequence of a Python bug which has > > been corrected since. > > I don't feel qualified, or morally righteous enough to have a > hard opinion on whether this would be a good thing, as an English > monoglot, but I don't see what the problem is with adding this > feature. It seems only fair and symmetrical to allow unicode > identifiers. Yes, it'd confuse the hell out of people like me to have > to read a Python program written in Korean characters. But it'd > confuse me just as much if it were written in Korean but > transliterated into Roman characters in plain old ASCII. There is generic problem for non-latin alphabets: keyboard is too small to accommodate two alphabets so you have to switch frequently between languages if you're going to type python code with non-latin identifiers. Try it, it's pain. I wouldn't use this feature personally. There's an advanced keyboard switcher for rus/eng input "Punto Switcher" that knows about rare combinations of letters and is able to automagically switch keyboard. But I'm sceptical it will work for code as good as for pure text. I may try it when I have time. Anyway it's a hack. > > Has this been a problem Java, in practice? > > Or is the problem simply that it's considered that there's not good > enough unicode support in editors and other tools yet? Again, I'm > surprised if that's the case with all this Java code floating around. > > Has it been PEPed? Or is GvR's opinion on it obvious enough that > nobody has bothered? GvR comment: http://mail.python.org/pipermail/python-dev/2002-July/026553.html quote: "Allowing non-ASCII identifiers may eventually happen, but there are lots of reasons why it's a bad idea " -- Serge. From Dick.Zantow at lexisnexis.com Thu Dec 11 15:51:53 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Thu, 11 Dec 2003 15:51:53 -0500 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > "rzed" writes: > [snip] >> whether they [underscores] make text easier to read than camelcase stuff is a >> matter of opinion and is based on what people are used to. > > i_really_don't_think_it_is_a_matter_of_opinion. i_think_it_is_a > matter_of_human_cognition, and_i'm_willing_to_bet_that_cognitive > psychology_experiments_would_prove_me_right, although_i_have_no_such > experiments_to_cite_at_the_moment. > > IHaveBeenUsingCamelCaseEveryDayForAboutTenYearsNow, > andIStillFindItMuchMoreDifficultToReadThanTheAlternatives. > ItNoLongerMakesMeWantToHurlTheWayThatItUsedTo,ButEasyToReadItIsNot. > > just compare the preceding two paragraphs for readability. that > should be all the proof one needs. I can see we won't agree about this. I find it much more distracting to have interspersed underscores. So, while I agree that's all the proof we need, I can't agree with you on what is proved. > >> i went from one form to the other and had no trouble adjusting; it >> took very little time for me to come to prefer camelcase. > > a chaque son gout, but if you are using camelCase in a > case-insensitive language, i believe that you are still making a > serious mistake. I couldn't agree more, there! But I was talking about switching to a case-sensitive language. In case-insensitive coding, I do believe it *could* be useful to adopt case conventions for some purposes, but it's far too easy for programmers with conflicting views on case to much with each other's code, and the result is a mess. It'll be interesting to see which way Python 3K goes, don't you think? -- rzed From tjreedy at udel.edu Mon Dec 8 12:32:38 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Dec 2003 12:32:38 -0500 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: "Rene Pijlman" wrote in message news:fmt8tvcqgmduhj5e6c46fukbtihkvrjtg8 at 4ax.com... > David McNab: > >a framework which allows mountable linux filesystems to be > >implemented in pure python. > > Serious question: why? If I wanted to learn about or experiment with linux filesystems, I might do better to start with this than track down the actual Linux C sources. TJR From duncan at NOSPAMrcp.co.uk Tue Dec 9 08:56:48 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 9 Dec 2003 13:56:48 +0000 (UTC) Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: Robin Becker wrote in news:LIGj15A6Vc1$EwNO at jessikat.fsnet.co.uk: > > C:\tmp>\python23\python ttt.py > list () = 1.72 > list [] = 3.27 > comprehension = 0.81 > copy = 3.94 > cCopy.copy = 1.59 > lambda z: z[:] = 1.14 > lambda z: list(z) = 4.73 > lambda z: [] = 0.95 > f=lambda z: [] = 0.95 > > like /F though I am extremely puzzled about the list result. I just had a look at listobject.c, in particular the code for list_fill. static int list_fill(PyListObject *result, PyObject *v) { PyObject *it; /* iter(v) */ int n; /* guess for result list size */ int i; n = result->ob_size; /* Special-case list(a_list), for speed. */ if (PyList_Check(v)) { if (v == (PyObject *)result ) return 0; /* source is destination, we're done */ return list_ass_slice(result, 0, n, v); } /* Empty previous contents */ if (n != 0) { if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0) return -1; } /* Get iterator. There may be some low-level efficiency to be gained * by caching the tp_iternext slot instead of using PyIter_Next() * later, but premature optimization is the root etc. */ ... and so on } Timing 'python \python23\lib\timeit.py "list([])"' gave times around 4.5uSec per loop, whereas the same with "list(())" gives about 2.3uSec per loop. Putting #ifdef 0/#endif around the 'special case for speed' block makes the first case go from 4.5uS to 2.4uS, and the second case also speeds up marginally for good measure. So it looks suspiciously like a premature optimisation 'for speed' should say 'for reduced speed'. Next I tried: python \python23\lib\timeit.py -s"r=range(10000)" "list(r)" and python \python23\lib\timeit.py -s"r=tuple(range(10000))" "list(r)" For this length of list the optimisation is a clear winner. It looks to me as though the breakeven is around 100 elements in the list. With fewer than 100 elements the optimisation slows things down, with more it speeds them up. I put the tests in a batch file: ------ test.bat -------- @echo off @echo Length: 0 python \python23\lib\timeit.py -s"r=[]" "list(r)" python \python23\lib\timeit.py -s"r=()" "list(r)" @echo Length: 1 python \python23\lib\timeit.py -s"r=range(1)" "list(r)" python \python23\lib\timeit.py -s"r=tuple(range(1))" "list(r)" @echo Length: 10 python \python23\lib\timeit.py -s"r=range(10)" "list(r)" python \python23\lib\timeit.py -s"r=tuple(range(10))" "list(r)" @echo Length: 100 python \python23\lib\timeit.py -s"r=range(100)" "list(r)" python \python23\lib\timeit.py -s"r=tuple(range(100))" "list(r)" @echo Length: 1000 python \python23\lib\timeit.py -s"r=range(1000)" "list(r)" python \python23\lib\timeit.py -s"r=tuple(range(1000))" "list(r)" @echo Length: 10000 python \python23\lib\timeit.py -s"r=range(10000)" "list(r)" python \python23\lib\timeit.py -s"r=tuple(range(10000))" "list(r)" ------------------------ With the original code I get: C:\Pythonsrc\python\dist\src\PCbuild>test Length: 0 100000 loops, best of 3: 4.38 usec per loop 100000 loops, best of 3: 2.32 usec per loop Length: 1 100000 loops, best of 3: 5.26 usec per loop 100000 loops, best of 3: 2.4 usec per loop Length: 10 100000 loops, best of 3: 5.39 usec per loop 100000 loops, best of 3: 2.84 usec per loop Length: 100 100000 loops, best of 3: 7.44 usec per loop 100000 loops, best of 3: 7.26 usec per loop Length: 1000 10000 loops, best of 3: 28.5 usec per loop 10000 loops, best of 3: 50.4 usec per loop Length: 10000 1000 loops, best of 3: 258 usec per loop 1000 loops, best of 3: 505 usec per loop With the optimisation code completely removed I get: C:\Pythonsrc\python\dist\src\PCbuild>test Length: 0 100000 loops, best of 3: 2.21 usec per loop 100000 loops, best of 3: 2.24 usec per loop Length: 1 100000 loops, best of 3: 2.34 usec per loop 100000 loops, best of 3: 2.36 usec per loop Length: 10 100000 loops, best of 3: 2.84 usec per loop 100000 loops, best of 3: 2.85 usec per loop Length: 100 100000 loops, best of 3: 7.56 usec per loop 100000 loops, best of 3: 7.13 usec per loop Length: 1000 10000 loops, best of 3: 53.2 usec per loop 10000 loops, best of 3: 50.4 usec per loop Length: 10000 1000 loops, best of 3: 549 usec per loop 1000 loops, best of 3: 534 usec per loop With the optimisation tweaked to ignore 0 length lists entirely and only 'optimise' for lists with more than 100 elements: C:\Pythonsrc\python\dist\src\PCbuild>test Length: 0 1000000 loops, best of 3: 1.39 usec per loop 100000 loops, best of 3: 2.31 usec per loop Length: 1 100000 loops, best of 3: 2.28 usec per loop 100000 loops, best of 3: 2.33 usec per loop Length: 10 100000 loops, best of 3: 2.85 usec per loop 100000 loops, best of 3: 2.84 usec per loop Length: 100 100000 loops, best of 3: 7.43 usec per loop 100000 loops, best of 3: 7.14 usec per loop Length: 1000 10000 loops, best of 3: 28.4 usec per loop 10000 loops, best of 3: 50.2 usec per loop Length: 10000 1000 loops, best of 3: 256 usec per loop 1000 loops, best of 3: 532 usec per loop The relevant part of list_fill now looks like this: /* Special-case list(a_list), for speed. */ if (PyList_Check(v)) { int vsize = ((PyListObject*)v)->ob_size; if (v == (PyObject *)result || vsize==0) return 0; /* nothing to copy */ if (vsize > 100) return list_ass_slice(result, 0, n, v); } -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From newsgroups at jhrothjr.com Sat Dec 27 17:26:16 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 27 Dec 2003 17:26:16 -0500 Subject: callable classes References: Message-ID: "Duncan Smith" wrote in message news:bshtlg$m1r$1 at news6.svr.pol.co.uk... > I recently started to rewrite a class and decided to take a bunch of related > methods and put them in a separate callable class. (They're all what I > would call pointwise operations on pairs of instances, they raise exceptions > for identical reasons, and they all return a new instance). It seemed like > a good idea at the time, but now I'm not so sure. So my very general > questions are: > > Is this a reasonable use for a callable class? > > In what circumstances are callable classes particularly useful? (Maybe I > haven't racked my brains long enough.) Function Objects (which is what the GoF patterns book calls these things) are useful whenever you need a function that requires long term persistant parameter storage. You can initialize one with the parameters, and then use it many times without the various callers having to remember the parameters and pass them to it each time. Another use is controlling visibility. In this use, it's somewhat similar to a proxy, except that you don't have to remember the name of the method to call; you just call the object. John Roth > > Cheers. TIA. > > Duncan > From piir at earthlink.net Fri Dec 26 14:31:57 2003 From: piir at earthlink.net (Todd Gardner) Date: 26 Dec 2003 11:31:57 -0800 Subject: hex array to array of 16 bit numbers? References: <9b849915.0312250206.61d89841@posting.google.com> Message-ID: <9b849915.0312261131.1344f5d4@posting.google.com> That's all I needed to make it work. Thank you for pointing me to the correct module. Todd From pinard at iro.umontreal.ca Tue Dec 23 09:46:35 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 23 Dec 2003 09:46:35 -0500 Subject: Naming conventions for iterator methods? In-Reply-To: References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> Message-ID: <20031223144635.GA3113@titan.progiciels-bpi.ca> [John J Lee] > I think I'll go with .foos(), for the same reason you choose .all_foos() > -- it'll make people read the docs if they need to know whether it's a > sequence, iterator, or object supporting the iterator protocol. I surely thought about using a suffix `s'. I do not know how frequent the problem is in English, but when I write in-house Python, I use French identifiers[1], and many words already have an `s' suffix in the singular form, the spelling does not change when pluralised. > [Fran?ois Pinard] > > I took the habit of naming such methods and functions with names > > starting with `all_', so I can write: > > for name in all_names(): > > do something > I don't like that, because often my iterator-returning methods take > arguments to restrict the iterees: shop.iter_cheeses(variety="smelly"). In my humble opinion, for cheese in shop.all_cheeses(variety="smelly"): do something would still be quite legible, and not shocking at all. In French, `all_' would become `tous_' or `toutes_', of course. > I just realised some of these methods of mine don't actually return > iterators, but merely objects supporting the iterator protocol. It may be a worth idea systematically returning iterables instead of iterators. Yet, I think an iterator shall formally provide itself through its `__iter__' method. In practice, I noticed that most of my `all_' functions or methods are based on generators. So clean! :-) These are very useful. ------------------------------------------------------------------------ [1] I mean, nearly French, as the necessary diacritics may not be used in Python identifiers, which is a common and constant source of displeasure to those of us who especially like working in French. Oh, Python does not differ on this aspect than most other programming languages. However, as Python is so satisfying in many other areas, we had some vague hope that he might become better in this particular one. Especially given that, for a tiny moment, it once worked correctly for French -- but sadly, this was the consequence of a Python bug which has been corrected since. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From deets_noospaam at web.de Tue Dec 9 12:14:59 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 18:14:59 +0100 Subject: regex confusion References: <3FD5FB97.CB8118FB@engcorp.com> Message-ID: >> This is a bogus regex - a '*' means "zero or more occurences" for the >> expression to the left. '?' means "zero or one occurence" for the exp to >> the left. > > Not true. See http://www.python.org/doc/current/lib/re-syntax.html : > > *?, +?, ?? > The "*", "+", and "?" qualifiers are all greedy; they match as much text > as possible. .... Adding "?" after the qualifier makes it perform the > match in non-greedy or minimal fashion; as few characters as possible will > be matched. .... Hmm. But when thats true, what does ".??" then mean - the first ? is not greedy, so it is nothing matched at all. The same is true for ".*?", and ".+?" is then equal to "." So what makes this useful? The regex in question definitely didn't work with it. Diez From bwglitch at hotpop.com Sun Dec 14 23:17:37 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Sun, 14 Dec 2003 23:17:37 -0500 Subject: Strip HTML tags? In-Reply-To: <7b454334.0312141157.8383dd5@posting.google.com> References: <7b454334.0312131911.70647953@posting.google.com> <7b454334.0312141157.8383dd5@posting.google.com> Message-ID: Fazer wrote: > BW Glitch wrote in message news:... > >>Fazer wrote: >> >> >>>Hello, >>> >>>I was wondering what would be the easiest way to strip away HTML tags from a string? >>> >>>Or how would I remove everything between < and > also the < , > as well using regex? >> >>You could use the SGMLparser for that also. Check the Python Cookbook at >>ASPN ( http://aspn.activestate.com/ASPN/Python/Cookbook/ ) for a recipe >>that uses it ( >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52281 ). >> > > > Thanks! The recipe works out fine! The problem is that I saved the > class in a file and I want it to be included in my other script. How > can that be done? My other script is in the same directory as the > class and doing import doesn't work. You should import -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "Come on, fight back! How far will you carry this silly chivalry? 'Cause this dark damsel is not impressed!" -- Blackarachnia to Silverbolt, "Bad Spark" From jsbenson at bensonsystems.com Sun Dec 7 14:49:07 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sun, 7 Dec 2003 11:49:07 -0800 Subject: how to display clock?, plus musings on the Nerd factor in Python Message-ID: <04f001c3bcfb$2ee9bff0$210110ac@jsbwxp3> Hi, here's some code I use to update a clock and some other stuff. You can probably use the Tkinter mainloop() instead of the twisted reactor and after(milliseconddelay, callback, args, ...) instead of the twisted callLater routine if the twisted framework isn't being used. You don't have to wrap the after()/callLater() stuff in a class like I did, but it facilitates setup of various independent periodic events. Attention veteran pythonistas: I'm a newcomer to python, so criticism of the following code will be welcomed and assiduously studied: ... from twisted.internet import reactor, tksupport ... class Pulsar: def __init__(self, reactor, requiredparamslist=[], kwdparamsdict={}, pulseinterval=1.0, maxpulses=None, callbeforefirstdelay=True): # begin create attributes self.reactor = reactor # from twisted.internet import reactor self.requiredparamslist = requiredparamslist self.kwdparamsdict = kwdparamsdict self.pulseinterval = float(pulseinterval) if maxpulses == None: self.maxpulses = None else: self.maxpulses = int(maxpulses) self.pulses = 0 # end create attributes # start and/or schedule repetition if self.maxpulses == None or self.pulses < self.maxpulses: self.reactor.callLater(0, self.beforefirst) if (self.maxpulses == None) or (self.pulses < self.maxpulses): if callbeforefirstdelay: self.IDelayedCall = self.reactor.callLater(0, self.functionwrapper) else: self.IDelayedCall = self.reactor.callLater(self.pulseinterval, self.functionwrapper) else: # looks like there was just 1 repetition self.afterlast() else: # no repetitions! self.afterlast() def afterlast(self): pass def beforefirst(self): pass def cancel(self): self.IDelayedCall.cancel() self.maxpulses = self.pulses # paranoia, in case the cancel suffered from a race condition self.cancelled() def cancelled(self): pass def functionwrapper(self): # assume that if we have been called/scheduled, we need to run the function: self.pulses += 1 apply(self.function, self.requiredparamslist, self.kwdparamsdict) if (self.maxpulses == None) or (self.pulses < self.maxpulses): self.IDelayedCall = self.reactor.callLater(self.pulseinterval, self.functionwrapper) else: # that's all, folks: no more repetitions self.afterlast() def function(self): raise NotImplementedError # must be overridden class Heartbeat(Pulsar): def afterlast(self): log("Heartbeat: that's all, folks!") reactor.stop() def beforefirst(self): log("XYZ Emulator entering service at %s" % time.asctime()) ... def cancelled(self): log("Heartbeat: I was cancelled!", fei.ERROR) self.afterlast() def function(self): fei.timenow.set(time.asctime()) log("Heartbeat %d " % self.pulses) ... heartbeat = Heartbeat(reactor, pulseinterval=1) reactor.listenTCP(5600, FalconFactory()) reactor.run() ... From aahz at pythoncraft.com Tue Dec 23 09:55:50 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Dec 2003 09:55:50 -0500 Subject: Tkinter and OS X 10.3? References: Message-ID: In article , Ron Stephens wrote: >aahz at pythoncraft.com (Aahz) wrote in message news:... >> >> Anyone used Tkinter on 10.3 yet? > >I have been using Tkinter on Mac OS X 10.3 and it works fine. I havev >not really stressed it however, just running IDLE, and some other >programs that use Tkinter GUI's. No heavy lifting, I'm afraid. Still, >come on in, the water feels fine ;-))) Thanks! That's all I wanted to know. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From theller at python.net Fri Dec 12 08:36:55 2003 From: theller at python.net (Thomas Heller) Date: Fri, 12 Dec 2003 14:36:55 +0100 Subject: java.awt.Robot equivalent? References: Message-ID: <4qw66tu0.fsf@python.net> "Fredrik Lundh" writes: > Christopher Koppler wrote: > >> Is this capability available in any of the GUI toolkits (searching >> Tkinter docs brought up nothing)? Is there a C library that I could >> wrap? Or maybe I just need to use the Windows extensions. But if so, >> how - I don't have the slightest idea how that would work. >> >> Anyone have any pointers? > > win32api's PostMessage might be useful. random google link: > > http://mail.python.org/pipermail/python-win32/2002-December/000635.html Other random resources: Simon Brunning has written a 3-part details blog entry on 'automating the win32 gui'. And there's a library named 'autoit' which can be driven by com. Thomas From tov at eecs.harvREMOVEard.edu Sat Dec 20 22:57:26 2003 From: tov at eecs.harvREMOVEard.edu (Jesse Tov) Date: 21 Dec 2003 03:57:26 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <877k0rgdff.fsf@thalassa.informatimago.com> Message-ID: Pascal Bourguignon : > Even with sed I find difficult to do that. If you want to remove blank lines, then sed '/^$/d' will do. If, on the other hand, you actually want to compress pairs of newlines into single newlines (as I think the specification may have said), something a bit more complicated is required. I think that sed 'N;P;/\n$/d;D' will do it. If you want to use Perl or Ruby, these are equivalent to the first sed solution: ruby -ne 'print unless /^$/' perl -ne 'print unless /^$/' In Ruby you might also use: ruby -pe 'next if /^$/' The equivalent doesn't work in Perl, probably because -p puts the implicit print statement in a "continue" block, which gets executed before the loop is restarted by "next". If you're doing this on a huge file and care about speed, sed will be slightly faster than Perl and Perl will blow Ruby away. Because I was curious, I tried writing it in C to see if I could beat sed. My first attempt was slightly slower (!), but my second attempt ran much faster than sed; unfortunately, it also took 30 minutes and 34 lines. Jesse From max at theslimmers.net Fri Dec 19 17:51:40 2003 From: max at theslimmers.net (max) Date: 19 Dec 2003 14:51:40 -0800 Subject: Problem mapping VB com code to Python Message-ID: <4f55e45a.0312191451.73b8f84b@posting.google.com> I am trying to use a sdk to access quickbooks, the sdk provided a COM interface and I think it installed the com server files/dlls. A VB code example is provided, but I can't figure out how to map "Dim sessionManager As New QBFC2_1Lib.QBSessionManager" into a corresponding Python statement, when I try obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get traceback Shown below. I have been able to run makepy and it generates a lovely file. I can find a Type Library, but need a little help mapping this to be able to access the com object and call its methods. I have included a snipit of the sample VB code and the traceback from my attempt to create a client com object ? Any help much appreciated, max =======Traceback ============= >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) ========= Sample VB code ========== Option Explicit Public Sub Main() On Error GoTo ErrHandler 'Establish a communication channel with QuickBooks 'Create the session manager object, and initiate a conversation with QuickBooks Dim sessionManager As New QBFC2_1Lib.QBSessionManager sessionManager.OpenConnection " ", "QBFC Developer's Guide" sessionManager.BeginSession "", omDontCare 'Build a set of requests - in this case, containing only one request 'Create the request set (the message set request object) Dim requestSet As QBFC2_1Lib.IMsgSetRequest 'Create a qbXML version 2.1 message Set requestSet = sessionManager.CreateMsgSetRequest(2, 1) 'Add a request to the request set. Dim customerAdd As QBFC2_1Lib.ICustomerAdd 'AppendCustomerAddRq is called only once here, even though two values are being set. Set customerAdd = requestSet.AppendCustomerAddRq customerAdd.Name.SetValue "Joe" customerAdd.CustomerTypeRef.FullName.SetValue "East Coast" 'Indicate that all requests should be processed, even if one has an error requestSet.Attributes.OnError = roeContinue 'Send the request set to QuickBooks Dim responseSet As QBFC2_1Lib.IMsgSetResponse Set responseSet = sessionManager.DoRequests(requestSet) From allenabethea at aol.com Tue Dec 30 13:32:27 2003 From: allenabethea at aol.com (Allenabethea) Date: 30 Dec 2003 18:32:27 GMT Subject: Programming language from python References: <3FF191C4.3020602@users.sourceforge.net> Message-ID: <20031230133227.01690.00000837@mb-m18.aol.com> > >I hear that the port of Sqiwrnsyivstblz++ for the .NET platform (named >"Sqiwrnsyivstblz++#") is even better. > I'm in the process of upgrading my PC jr to 640K and then installing windows 3.1. are there any 16-bit dos or windows binary packages of Sqiwrnsyivstblz++ which will run on dos 5.0 and windows 3.1? I'd rather have binaries but if I have to compile, I need a source version that will compile with Mix PowerC 2.0 allen. From skip at pobox.com Fri Dec 5 09:57:56 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Dec 2003 08:57:56 -0600 Subject: How to tell the difference between string and list In-Reply-To: <1070635589.841.8.camel@marigold> References: <1070635589.841.8.camel@marigold> Message-ID: <16336.40180.980551.605191@montanaro.dyndns.org> Jan> I need to recognize 'var' and ['var'], usually I would use: ... Try if isinstance(a, str): pass elif isinstance(a, list): pass Skip From andymac at bullseye.apana.org.au Fri Dec 5 17:43:02 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 6 Dec 2003 09:43:02 +1100 (EST) Subject: Threading - Why Not Lock Objects Rather than lock the interpreter In-Reply-To: References: <8089854e.0312050632.72cbfb44@posting.google.com> Message-ID: <20031206093409.C70794@bullseye.apana.org.au> On Sat, 5 Dec 2003, Christopher A. Craig wrote: > michael at foord.net (Fuzzyman) writes: > > > Looking at threading code it seems that the Global Interpreter Lock is > > a bit of a 'brute force' way of preventing two threads attempting to > > access sensitive objects simultaneously.... > > > > Why not have a new type of object with a 'lock' facility... if an > > object is locked then any thread trying to access the object other > > than the one obtaining the lock is blocked until the lock is > > released..... rather than blocking *all* threads until one thread has > > finished with the object..... > > > > It could be implemented as a new attribute of existing objects... or > > new types of objects..... > > It would slow down the interpreter drastically. The important thing > here is that for the above to be true, you'ld need to define > "sensitive objects" to be "objects with a reference count" (i.e. all > of them). Because of that if you did this you'ld be doing about as > much locking and unlocking as you would code execution. For example, > calling the following function would require at least 2 lock/unlock > pairs (there may be more, I'm not thinking too hard about it): > > def donothing(): pass As an example of what can happen, I played around with building a pre 2.3alpha CVS Python with OpenWatcom on OS/2. Building the Python core as a DLL resulted in a Pystone rating 25% less than a static linked Python.exe. This was traced to the OpenWatcom malloc() implementation always using thread locks when linked to code in a DLL, even when extra threads are never created (ie only the primary thread is running). Enabling PyMalloc fixed that. While Python does many malloc()s and free()s, it does many, many more object accesses. So the performance degradation from an object locking strategy can be savage. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From http Fri Dec 12 17:23:34 2003 From: http (Paul Rubin) Date: 12 Dec 2003 14:23:34 -0800 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> <3FD9D4E9.FE199F61@engcorp.com> Message-ID: <7xfzfphdzt.fsf@ruckus.brouhaha.com> Peter Hansen writes: > As the author, John might seem biased, but I'll weigh in with my own > praise for the product. His comment "if you want to stay sane" is > really on-the-mark here... Cookies _are_ insane, but ClientCookie at > least provides them a nice padded room in which to reside... Cookies aren't insane in concept, but their implementation leaves some things to be desired. From jjl at pobox.com Sun Dec 14 19:29:09 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Dec 2003 00:29:09 +0000 Subject: focusNextPrevChild to move through child widgets. References: Message-ID: <87brqahqju.fsf@pobox.com> Andy Rayner writes: > Hello, using pyqt [...] 1. Then put that in the subject line, if you're posting here. 2. PyKDE list would be a better choice than here. John From sombDELETE at pobox.ru Sun Dec 21 06:15:05 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sun, 21 Dec 2003 14:15:05 +0300 Subject: Unicode from Web to MySQL References: Message-ID: > . What's driving me crazy is knowing the encoding > but still not getting the data all the way through the chain to MySQL. That's because you're trying to create SQL statements manually. >>>2) Convert to unicode before UTF-8 >>Not sure what that means. > data.decode(None,'strict') > or > unicode(data,'unicode','strict') See Francis' excellent post why both of these calls do not make sence at all. >>>3) replace quotation marks within the SQL statement: >>>data2.replace(u'"',u'\\"') >>It's not a unicode problem, is it? > Occasionally instead of getting the encoding error I get a SQL syntax error, > and figured somewhere it was misinterpreting something like the end > delimiter. > No proof though, just a guess, so I tried the replaces. Uh, I see. If you're creating SQL statement yourself, you have to take care of escaping. I guess after data2.encode('utf-8') you've got illegal (in SQL) characters and you have to escape them. Another quick scan of mysql-python docs reveals that .execute method can be called as c.execute(''' INSERT INTO junk ( junklet) VALUES ( '%s') ''', args=(data2,) ) where data2 is a unicode string. Then the python wrapper will take care of unicode convertions and escaping. Don't forget that you need to .connect with unicode='utf-8' parameter. -- Serge. From mhammond at skippinet.com.au Mon Dec 22 18:29:42 2003 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 23 Dec 2003 10:29:42 +1100 Subject: Problem mapping VB com code to Python In-Reply-To: <4f55e45a.0312211048.4fc090a@posting.google.com> References: <4f55e45a.0312191451.73b8f84b@posting.google.com> <4f55e45a.0312211048.4fc090a@posting.google.com> Message-ID: max wrote: > No luck, I have tried all possible case combinations and permutations > of what I see in the com brouser. The only place I have found > references to the com module qbFC2_1Lib is in the "Registered Type > Libraries". > > Is there another way to access the com module then client.Dispatch()? > > What is the mapping of the VB statememnt > " Dim sessionManager As New QBFC2_1Lib.QBSessionManager" > does this imply something other than late binding. This is VB using early binding, and using vtable interfaces rather than IDispatch. I'm really not sure why this is failing for you though - if the problem was that the object did not support IDispatch, I would expect an "unsupported interface" exception. It may just be that you have to find the correct progID for use in this context. Can you find VB code that uses CreateObject() on the object? Mark. From fuehner at iisb.fraunhofer.de Mon Dec 8 08:27:30 2003 From: fuehner at iisb.fraunhofer.de (Tim Fuehner) Date: Mon, 08 Dec 2003 14:27:30 +0100 Subject: static program including python interpreter + dynamic python extensions Message-ID: Dear Newsgroup, I have a problem that is somewhat related to Alexandre Gillet's ones: "build a static python executable". I would like to make a C[++] program scriptable. Therefor, I have included a python interpreter into the program. Additionally I have wraped all the program's interfaces that I need, using SWIG. Finally, I have created a shared library, which includes this interface and all functions that are to be available from within python scripts. And it works: one can write a script, which can access the program's routines and data, the main program correctly loads them, using its python interpreter. However, the program has to be linked dynamically. Once I try to change the main program's linkage to static, loading any module, that is not a plain python file (but a shared library), fails, saying: Fatal Python error: Interpreter not initialized (version mismatch?) Since I need the program to be linked statically, I would appreciate any hint on how to fix this problem. I'm using gcc 3.2 under linux (2.4.19) and python 2.3.2 (also checked with 2.2). Thanks -tim From eddie at holyrood.ed.ac.uk Tue Dec 2 07:10:49 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 2 Dec 2003 12:10:49 +0000 (UTC) Subject: Can Python be run off of a CD-ROM? References: Message-ID: "BJ MacNevin" writes: >Hi all, >I teach middle school and am currently trying to bring some computer science >to the students. Our district has a wonderfully linked network throughout >all our schools... done via MS Windows Network. In order to protect the >network, our district's IT department does not want things installed on the >system (or at least makes it VERY difficult to get it done). SO, I am using >MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it >off of them. >BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I >can do the same thing... or something similar? Is there a way to install >Python on a CD-ROM, too, if we don't need it to be accessed from a command >prompt? You *could* kill two birds with on CD by running a real OS (BSD or Linux) from CD with Python built in. Just a point to consider, don't get too worked up about it (it's a bit slow mind you). Anyway, to answer the main question. You can create a file system with all the Python files on it and run from there but I think the main problem is search paths and the like. I believe you ideally need to get the relevant information into the registry but if you're not able to I think this is problematic. So I was wondering whether there was a howto on running Python from Windows without it being in the registry (and for the OP how do you get it in the registry without an install process). I have similar problems running from a USB memory key but at least there I can write files to the same directory where the binaries are (though it's not ideal). Eddie From daniels at dsl-only.net Wed Dec 3 11:46:39 2003 From: daniels at dsl-only.net (sdd) Date: Wed, 03 Dec 2003 08:46:39 -0800 Subject: Stuck newbie In-Reply-To: References: <20619edc.0312020958.4c1700cb@posting.google.com> Message-ID: <3fce207d$1@nntp0.pdx.net> Diez B. Roggisch wrote: >... Lotsa good stuff ... Then > > print records[-1] > The __repr__ method is automagically called when print is used on an object. Well, it tries to call the __str__ method, which defaults to the __repr__ method if no __str__ is defined. pedantically yours, -Scott David Daniels Scott.Daniels at Acm.Org From miki.tebeka at zoran.com Sun Dec 28 08:12:29 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 28 Dec 2003 05:12:29 -0800 Subject: Using python to check the status of a program References: Message-ID: <4f0a9fdb.0312280512.39a495d4@posting.google.com> Hello Jetman, > > I would like to use a Python script to periodically check to see if a > > program is still running and if it isn't I want to start it up. Could > > someone point me on the right path? Thanks in advance. > If we're talking about Windows, then this would work using the > Cygwin utils for ps or one could try Pythonwin. Mark has ported > many Windows APIs, so it would be a little more involved, but > straight-fwd. HTH....Jet There are always the pstools from sysinternals (http://www.sysinternals.com/ntw2k/freeware/pstools.shtml) HTH. Miki From news at grauer-online.de Wed Dec 3 06:36:28 2003 From: news at grauer-online.de (Uwe Grauer) Date: Wed, 03 Dec 2003 12:36:28 +0100 Subject: Building a GUI agnostic database application In-Reply-To: <3fcd9d2a@mail.netspeed.com.au> References: <3fcd9d2a@mail.netspeed.com.au> Message-ID: Take at look at PAF http://www.dctools.org Uwe Rasjid Wilcox wrote: > I am wanting to write a database application using Python. > > I want it to be GUI agnostic. The GUI will probably be Python/wxPython, but > I would also like the option of a Webbased (PHP?) gui, and possibly GUI's > in Java or C++, Visual Basic etc. > > The Python 'backend' may run on the same machine as the client (thick > client), or on the same machine as the database (thin client). > > My main requirements are: > 1. Reasonably light-weight > 2. Secure authentication between the GUI and the backend. > 3. Ideally runs wherever Python runs, and at least on Linux, Mac and > Windows. > > http://www.markcarter.me.uk/computing/python/python.html has a list of > possible candidates. > > These include: > Corba, OSE, SOAP, Spread, Twisted, XML-RPC and Yami > > It looks to me like XML-RPC run over SSL is probably the simplest solution, > but I'd be interested in other peoples views. > > Thanks, > > Rasjid. > From theller at python.net Fri Dec 5 14:54:37 2003 From: theller at python.net (Thomas Heller) Date: Fri, 05 Dec 2003 20:54:37 +0100 Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: "Brad Clements" writes: > "Rene Olsthoorn" wrote in message > news:3fcf581e$0$200$e4fe514c at news.xs4all.nl... >> Dear readers, >> >> py2exe has a problem including libxml2. Not at building time, but at >> runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has >> the problem? (and can you drop me your setup.py scipt, please). >> > > Perhaps you hit the same problem I did when using libxml2 and libxslt in a > service created by p2exe. > > Here are notes from my project diary (these notes are meant for my client to > reconcile my bill vs. what I did) > ----- > The service builds, I can install it, but get an error when I run it: > > The instance's SvcRun() method failed > File "win32serviceutil.pyo", line 663, in SvcRun > File "UMXWIN32SVC.pyo", line 41, in SvcDoRun > File "Rose\WebServer\UMXMServer.pyo", line 53, in ? > File "Rose\WebServer\umx_handler.pyo", line 16, in ? > File "Rose\WebServer\HTTPHandler.pyo", line 95, in ? > File "Rose\WebServer\XMLProcessor.pyo", line 34, in ? > > exceptions.ImportError: dynamic module does not define init > function (initlibxslt) > > This says that the service cannot import the libxslt module for some reason. > > I built a test script that py2exe runs in console mode, it also fails in the > same way. > > I think libxml is using some kind of dynamic import mechanism, we need to > work around. > > Aha, figured it out. example problem with libxml2. > > libxml2.py is a module that imports libxml2mod.pyd which imports libxml2.dll > > But, py2exe creates a default path like this: > > c:\\temp\\rose, c:\\temp\\rose\\library.zip > > This means that python tries to import from the directory first, before > importing from library.zip. So, python imports libxml2.dll, not libxml2.py > > My workaround is to reverse the order of the imports in the startup script: > > zipfile = sys.path[-1] > sys.path.insert(0,zipfile) Which version of py2exe are you using, and what is this libxml2? IIRC, in the latest version py2exe doesn't put the executable's directory on the path anymore, but file names like libxml2.py, libxml2.pyd, and libxml2.dll all at the same time have the potential to confuse it! Thomas From yan at NsOeSiPnAeMr.com Sat Dec 6 17:15:42 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 06 Dec 2003 17:15:42 -0500 Subject: how to determine if files are on same or different file systems Message-ID: Thanks to everyone on this list. I now have a functioning piece of python code!! :-)) Now I'm trying to clean it up. I have the same (or similar) lines repeated several times: shutil.copy2(newArrivalsDir+'/'+movie,archivesDir) thumb = string.replace(movie,'.avi','.jpg') shutil.copy2(newArrivalsDir+'/tn/'+thumb,archivesDir+'/tn/') or os.rename(otherFavDir+'/'+movie,dir+'/'+movie) thumb = string.replace(movie,'.avi','.jpg') os.rename(otherFavDir+'/tn/'+thumb,dir+'/tn'+thumb) what varies is the name of the function (shutil.copy2 or os.rename depending on if I am renaming or copying) and the names of the source and dest directories. This particular snippet is repeated about a half-dozen times. It would be nice if I could write a function that would determine if the source and destination are on the same file system or not, and thus use rename or copy appropriately, or if there is already such a built-in function. TIA, -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From http Mon Dec 15 19:06:01 2003 From: http (Paul Rubin) Date: 15 Dec 2003 16:06:01 -0800 Subject: Preview of a Stackless Zope Application References: Message-ID: <7xr7z5aaom.fsf@ruckus.brouhaha.com> Christian Tismer writes: > Let me know your thoughts... > > http://www.centera.de/tismer/stackless/zope_demo The link http://www.centera.de/tismer/stackless/zope_demo/download_pickle/zope_demo.pickle sometimes gets a runtime error: Zope has encountered an error while publishing this resource. Error Type: RuntimeError Error Value: You cannot __reduce__ the tasklet which is current. Also I think you should make the demo go from 1 to 5 instead of 10, so there's not so much button pushing. Finally, as a non-Zope and non-Stackless user, I find the source code incomprehensible. It would be much simpler in a conventional web framework, especially if you can put a generator into a session variable. Generator pickling would help with that, of course. From ramen at lackingtalent.com Fri Dec 26 20:41:18 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 27 Dec 2003 01:41:18 -0000 Subject: dynamic typing questions References: <2m6hb1-u24.ln1@beastie.ix.netcom.com> Message-ID: In article , Dennis Lee Bieber wrote: > Dave Benjamin fed this fish to the penguins on Wednesday 24 December > 2003 00:26 am: >> >> Lake Havasu City, Arizona. ;) >> > Next to lots of beach front property, I take it Yes, sir, we'd like the lake installed over here, please... -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From duncan at NOSPAMrcp.co.uk Mon Dec 15 08:47:13 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 15 Dec 2003 13:47:13 +0000 (UTC) Subject: Using readline with a new delimiter of line ? References: Message-ID: "Laurent" wrote in news:brkd27$6es$1 at news- reader4.wanadoo.fr: > Hello, > > is it possible to read a file in python line by line > by redefining a new end-of-line delimiter ? > > I would like for example to have the string "END" being the new delimiter > for each line. > If your file is short enough that it will fit comfortably into memory, just do: inputFile = file('name', 'rb') lines = inputFile.read().split('END') then you can iterate over the list stored in 'lines'. If the file is too large for that, you'll need to implement your own scheme to read chunks, split them up on your delimiter and return a line at a time. The easiest way to do that is to use a generator. Something like: def oddFile(filename, delimiter, buffersize=10000): inputFile = file(filename, 'rb') lines = [''] for data in iter(lambda: inputFile.read(buffersize), ''): lines = (lines[-1] + data).split(delimiter) for line in lines[:-1]: yield line yield lines[-1] Then you can do: for l in oddFile('somefile', 'END'): print repr(l) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tjreedy at udel.edu Sat Dec 27 16:45:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Dec 2003 16:45:48 -0500 Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: "Bjorn Pettersen" wrote in message news:Xns945E70BA8545Dbjornpettersen at 216.196.97.136... > The case I've seen come up repeatedly is a little simple, only involving > deletions of the list: > > x = range(30) > for i in x: > if 5 <= i <= 10: # try to remove 5,6,7,8,9,10 > x.remove(i) > > the above removes 6,8,10 instead. For those who don't know, in-place removal must be done in reverse. x = range(15) for i in range(14,-1,-1): if 5 <= i <= 10: # try to remove 5,6,7,8,9,10 x.remove(i) >>> x [0, 1, 2, 3, 4, 11, 12, 13, 14] tjr From deets_noospaam at web.de Tue Dec 2 08:45:35 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 02 Dec 2003 14:45:35 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com> Message-ID: Joerg Schuster wrote: > Peter Hansen writes: > >> produce a longer overall match. In other words, the "|" operator is >> never greedy. > > O.k. Thanks for pointing this out. Maybe I should have formulated my > question differently: Is there a trick (be it dirty or not) to make > "|" greedy in python? I don't think so - as regexps are finite state automata, their capabilities are limited to what these machines can do. So they can't backtrack to a part of the disjunction that was a shorter match if the longer match suddenly will fail. Consider this example: rex: a|abc string: abd If the state-machine was greedy, it would follow the second path and fail. The only thing you can do to avoid is is to split your disjunctions and search separately, and afterwards takt the longest part. That could be done using a small grammar, that allows you to detect the disjunctions and create separate rexes for it. Diez From jason at tishler.net Tue Dec 2 07:45:00 2003 From: jason at tishler.net (Jason Tishler) Date: Tue, 2 Dec 2003 07:45:00 -0500 Subject: HELP: W2K Python + Cygwin shell script In-Reply-To: <3fca4139$0$1154$39db0f71@news.song.fi> References: <3fca4139$0$1154$39db0f71@news.song.fi> Message-ID: <20031202124500.GB1660@tishler.net> Pekka, On Sun, Nov 30, 2003 at 09:12:12PM +0200, Pekka Niiranen wrote: > Before I start the trial & error -cycle, has anybody tried to start > Bash -shell script in Cygwin environment from Python running in W2K? Something like the following should meet your needs: Python ... [MSC 32 bit (Intel)] on win32 >>> import os >>> os.system('bash ~/bin/foo.sh') foo 0 Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From gerrit at nl.linux.org Tue Dec 9 16:07:06 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 9 Dec 2003 22:07:06 +0100 Subject: "How Python is Developed": an introductory essay In-Reply-To: References: Message-ID: <20031209210706.GA5372@nl.linux.org> Brett C. wrote: > At http://www.python.org/dev/dev_intro.html you will find an essay > entitled, "Guido, Some Guys, and a Mailing List: How Python is > Developed". The essay covers the development process of Python without > going into extreme nitty-gritty details. The purpose of this essay is > to provide an easy introduction to how Python is developed culminated in > a single document. I think there is a minor markup nit: in the HTML version, the string `Python-checkins`_ is included, but it should probably be a link...? BTW, interesting essay. Gerrit. -- 59. If any man, without the knowledge of the owner of a garden, fell a tree in a garden he shall pay half a mina in money. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From amy-g-art at cox.net Sat Dec 27 13:05:17 2003 From: amy-g-art at cox.net (Amy G) Date: Sat, 27 Dec 2003 10:05:17 -0800 Subject: Adding newusers to Unix system from mysql data (Better Approach) References: <99dce321.0312270514.53ebf23d@posting.google.com> Message-ID: Thank you very much... it was indeed f1.close() that needed fixing. Program works flawlessly. And thanks for the shortcut, that is a good one. "David M. Wilson" wrote in message news:99dce321.0312270514.53ebf23d at posting.google.com... > "Amy G" wrote... > > > My problem is this... It writes the data file without problem. But, the > > os.system... does not necessarily work to add a new user. By 'not > > necessarily' I mean that it works some of the time, but not all of the time. > > If I run the program and it does not work, I can simple type 'adduser -f > > ' at the command line and it works no problem. Any ideas what > > could be causing this. > > Have you tested adduser seperately? I can't see any problem with your > code, suggesting it may be adduser. > > > > for line in c: > > userid, password, name = line > > You can do inline tuple unpack: > > for userid, password, name in c: > > > > aList.append("%s::20::::%s::sh:%s" %(userid, name, password)) > > > > f1=open('/home/sean/bin/users.test', 'w') > > for line in range(len(aList)): > > f1.write(str(aList[line]) + "\n") > > Just in case you hadn't noticed the shortcut here: > > for userid, password, name in c: > f1.write("%s::20::::%s::sh:%s\n" %(userid, name, password)) > > > > f1.close > > Ahah! Where are the parenthesis? :) Your file is probably not getting > flushed to disk: > > f1.close() > > > David. From stani_ at hotmail.com Wed Dec 3 11:11:58 2003 From: stani_ at hotmail.com (SM) Date: 3 Dec 2003 08:11:58 -0800 Subject: Pychecker under Windows References: <153fa67.0311252016.2e02b575@posting.google.com> Message-ID: <99230dbb.0312030811.1c2bceb1@posting.google.com> kylotan at hotmail.com (Kylotan) wrote in message news:<153fa67.0311252016.2e02b575 at posting.google.com>... > Is there a practical way to use Pychecker in Windows? It doesn't work > under IDLE. (In fact, it seems to end up breaking everything, and > every subsequent statement and expression I execute gets ignored.) > Running it from the Python interpreter in DOS means everything scrolls > off the screen. Ideally I'd like to redirect it to a file, or be able > to use it in IDLE. PyChecker is integrated in SPE, an python IDE built on wxWindows. Maybe you coud try that. http://spe.pycs.net Good luck, Stani From glenfant at NOSPAM.bigfoot.com Wed Dec 17 18:09:49 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Thu, 18 Dec 2003 00:09:49 +0100 Subject: Save the pythons. References: Message-ID: "f29" a ?crit dans le message de news:aeaacf65.0312171345.4267f213 at posting.google.com... > I don't believe that noone has yet spotted that python is becoming > java. Each new version is fully equipped with more garbage than > before. Classes are great, but once there are 1000 of them, inheriting > from each other, I cannot avoid comparing this unpleasant situation to > java. > Python power is in it's syntax, not addons. Let's not copy perl's > experience and one java is already far too much for earth. > > f29 Where's the problem ? $ rm /usr/local/lib/python4.5/[type your useless packages here] -- Gilles From raims at dot.com Fri Dec 12 10:46:21 2003 From: raims at dot.com (Lawrence Oluyede) Date: Fri, 12 Dec 2003 16:46:21 +0100 Subject: SWT and Python (was: Re: What GUI toolkit looks the best?) References: <20031211190954.GA54939@hishome.net> <05f701c3c026$5eb9c8f0$7401a8c0@voidmk9> Message-ID: <87iskmox82.fsf@mobile.foo> Michael Hudson writes: > Is SWT the framework that was developed for Eclipse? Yes, it is. -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com From no_more_spam at no_use_for.me Tue Dec 30 08:05:22 2003 From: no_more_spam at no_use_for.me (Sven Brandt) Date: Tue, 30 Dec 2003 14:05:22 +0100 Subject: Newbie: sort list of dictionaries In-Reply-To: <7xy8su7a1k.fsf@ruckus.brouhaha.com> References: <7xy8su7a1k.fsf@ruckus.brouhaha.com> Message-ID: Hi Paul, thanks a lot, esp. for the good explanation. That's excactly what i needed. Regards Sven Paul Rubin schrieb: > The list sort method lets you pass an optional comparison function, > that takes two items and returns -1, 0, or 1, depending on what order > the items are supposed to appear in. The comparison function takes > exactly two args (the items to be compared). You can't pass a third > arg to specify the field name. You could do something ugly like use a > global variable, but the preferred way given a field name is to > construct a brand new comparison function just for that name: > > def compare_by (fieldname): > def compare_two_dicts (a, b): > return cmp(a[fieldname], b[fieldname]) > return compare_two_dicts > > What's that? Two nested function definitions. The outer function, > compare_by, creates a new function called compare_two_dicts, which > compares specifically based on the field that you passed to the outer > function. compare_by then returns the new function, that's right, > functions are values in Python! You can then can pass the new > function to the sort method: From bhoel at web.de Sun Dec 28 05:47:00 2003 From: bhoel at web.de (Berthold Hoellmann) Date: Sun, 28 Dec 2003 11:47:00 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 Message-ID: Hello, When I use ./configure --with-thread --with-fpectl --with-signal-module \ --with-pymalloc --enable-shared --with-cxx=g++ make test on 2.3.3 I get ... test_queue test_quopri test_random test_re make: *** [test] Speicherzugriffsfehler (Speicherauszug erstellt) gdb ./python core.29964 GNU gdb 5.3.93 Copyright 2003 Free Software Foundation, Inc. ... Reading symbols from /home/devel/compile/Python-2.3.3/build/lib.linux-i686-2.3/pyexpat.so...done. Loaded symbols for /home/devel/compile/Python-2.3.3/build/lib.linux-i686-2.3/pyexpat.so #0 0x400f126c in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6840) at Modules/_sre.c:750 750 { (gdb) bt #0 0x400f126c in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6840) at Modules/_sre.c:750 #1 0x400f2084 in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6839) at Modules/_sre.c:1257 #2 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6838) at Modules/_sre.c:1271 #3 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6837) at Modules/_sre.c:1271 #4 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6836) at Modules/_sre.c:1271 #5 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6835) at Modules/_sre.c:1271 #6 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6834) at Modules/_sre.c:1271 #7 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6833) at Modules/_sre.c:1271 #8 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=6832) at Modules/_sre.c:1271 ... #6838 0x400f20ef in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=2) at Modules/_sre.c:1271 #6839 0x400f157c in sre_match (state=0xbfffcaf0, pattern=0x41126a0c, level=1) at Modules/_sre.c:1161 ---Type to continue, or q to quit--- #6840 0x400f8a36 in sre_search (state=0xbfffcaf0, pattern=0x411269ee) at Modules/_sre.c:1411 #6841 0x400f63bf in pattern_search (self=0x411269c0, args=0x40e785ac, kw=0x0) at Modules/_sre.c:1869 #6842 0x40068e74 in PyCFunction_Call (func=0x410610cc, arg=0x40e785ac, kw=0x0) at Objects/methodobject.c:93 #6843 0x400a29e6 in call_function (pp_stack=0xbfffcf6c, oparg=6840) at Python/ceval.c:3439 #6844 0x400a4115 in eval_frame (f=0x84f2ddc) at Python/ceval.c:2116 #6845 0x400a181f in PyEval_EvalCodeEx (co=0x40429c60, globals=0x0, locals=0x0, args=0x84f2ddc, argcount=2, kws=0x84d3468, kwcount=0, defs=0x40436c18, defcount=1, closure=0x0) at Python/ceval.c:2663 #6846 0x400540d5 in function_call (func=0x4043ba74, arg=0x40f54c6c, kw=0x41134e84) at Objects/funcobject.c:504 #6847 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40f54c6c, kw=0x41134e84) at Objects/abstract.c:1755 #6848 0x400a2cad in ext_do_call (func=0x4043ba74, pp_stack=0xbfffd13c, flags=1089817708, na=0, nk=0) at Python/ceval.c:3713 #6849 0x400a3fbb in eval_frame (f=0x84fa644) at Python/ceval.c:2151 #6850 0x400a181f in PyEval_EvalCodeEx (co=0x40461e20, globals=0x0, locals=0x0, args=0x84fa644, argcount=5, kws=0x8423550, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #6851 0x400a76b5 in fast_function (func=0x41126a0c, pp_stack=0xbfffd2ec, n=5, na=5, nk=20) at Python/ceval.c:3529 #6852 0x400a2aa7 in call_function (pp_stack=0xbfffd2ec, oparg=6840) at Python/ceval.c:3458 #6853 0x400a4115 in eval_frame (f=0x84233ec) at Python/ceval.c:2116 #6854 0x400a773e in fast_function (func=0x41126a0c, pp_stack=0xbfffd41c, n=1, na=1, nk=138556396) at Python/ceval.c:3518 #6855 0x400a2aa7 in call_function (pp_stack=0xbfffd41c, oparg=6840) ---Type to continue, or q to quit--- at Python/ceval.c:3458 #6856 0x400a4115 in eval_frame (f=0x84f328c) at Python/ceval.c:2116 #6857 0x400a181f in PyEval_EvalCodeEx (co=0x40461c20, globals=0x0, locals=0x0, args=0x84f328c, argcount=2, kws=0x0, kwcount=0, defs=0x404a7a58, defcount=1, closure=0x0) at Python/ceval.c:2663 #6858 0x4005401b in function_call (func=0x404a695c, arg=0x40f5462c, kw=0x0) at Objects/funcobject.c:504 #6859 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40f5462c, kw=0x0) at Objects/abstract.c:1755 #6860 0x400448a4 in instancemethod_call (func=0x1ab8, arg=0x40f5462c, kw=0x0) at Objects/classobject.c:2433 #6861 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e78fac, kw=0x0) at Objects/abstract.c:1755 #6862 0x40082bc8 in slot_tp_call (self=0x40e78fac, args=0x40e78fac, kwds=0x0) at Objects/typeobject.c:4473 #6863 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e78fac, kw=0x0) at Objects/abstract.c:1755 #6864 0x400a7806 in do_call (func=0x4113c36c, pp_stack=0x40e78fac, na=-1, nk=6840) at Python/ceval.c:3644 #6865 0x400a29ac in call_function (pp_stack=0xbfffd8cc, oparg=6840) at Python/ceval.c:3460 #6866 0x400a4115 in eval_frame (f=0x84237fc) at Python/ceval.c:2116 #6867 0x400a181f in PyEval_EvalCodeEx (co=0x404a41e0, globals=0x0, locals=0x0, args=0x84237fc, argcount=2, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #6868 0x4005401b in function_call (func=0x404a6d14, arg=0x40f543ac, kw=0x0) at Objects/funcobject.c:504 #6869 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40f543ac, kw=0x0) at Objects/abstract.c:1755 #6870 0x400448a4 in instancemethod_call (func=0x1ab8, arg=0x40f543ac, kw=0x0) ---Type to continue, or q to quit--- at Objects/classobject.c:2433 #6871 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e78f8c, kw=0x0) at Objects/abstract.c:1755 #6872 0x40082bc8 in slot_tp_call (self=0x40e78f8c, args=0x40e78f8c, kwds=0x0) at Objects/typeobject.c:4473 #6873 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e78f8c, kw=0x0) at Objects/abstract.c:1755 #6874 0x400a7806 in do_call (func=0x4113ca8c, pp_stack=0x40e78f8c, na=-1, nk=6840) at Python/ceval.c:3644 #6875 0x400a29ac in call_function (pp_stack=0xbfffdd7c, oparg=6840) at Python/ceval.c:3460 #6876 0x400a4115 in eval_frame (f=0x8364c9c) at Python/ceval.c:2116 #6877 0x400a181f in PyEval_EvalCodeEx (co=0x404a41e0, globals=0x0, locals=0x0, args=0x8364c9c, argcount=2, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #6878 0x4005401b in function_call (func=0x404a6d14, arg=0x40f5460c, kw=0x0) at Objects/funcobject.c:504 #6879 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40f5460c, kw=0x0) at Objects/abstract.c:1755 #6880 0x400448a4 in instancemethod_call (func=0x1ab8, arg=0x40f5460c, kw=0x0) at Objects/classobject.c:2433 #6881 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e7854c, kw=0x0) at Objects/abstract.c:1755 #6882 0x40082bc8 in slot_tp_call (self=0x40e7854c, args=0x40e7854c, kwds=0x0) at Objects/typeobject.c:4473 #6883 0x4003a0aa in PyObject_Call (func=0x41126a0c, arg=0x40e7854c, kw=0x0) at Objects/abstract.c:1755 #6884 0x400a7806 in do_call (func=0x410e6f8c, pp_stack=0x40e7854c, na=-1, nk=6840) at Python/ceval.c:3644 #6885 0x400a29ac in call_function (pp_stack=0xbfffe22c, oparg=6840) ---Type to continue, or q to quit--- at Python/ceval.c:3460 #6886 0x400a4115 in eval_frame (f=0x829a7a4) at Python/ceval.c:2116 #6887 0x400a773e in fast_function (func=0x41126a0c, pp_stack=0xbfffe35c, n=2, na=2, nk=136947620) at Python/ceval.c:3518 #6888 0x400a2aa7 in call_function (pp_stack=0xbfffe35c, oparg=6840) at Python/ceval.c:3458 #6889 0x400a4115 in eval_frame (f=0x41b3a014) at Python/ceval.c:2116 #6890 0x400a181f in PyEval_EvalCodeEx (co=0x40461420, globals=0x0, locals=0x0, args=0x41b3a014, argcount=2, kws=0x84376fc, kwcount=0, defs=0x4049e938, defcount=1, closure=0x0) at Python/ceval.c:2663 #6891 0x400a76b5 in fast_function (func=0x41126a0c, pp_stack=0xbfffe50c, n=2, na=2, nk=8) at Python/ceval.c:3529 #6892 0x400a2aa7 in call_function (pp_stack=0xbfffe50c, oparg=6840) at Python/ceval.c:3458 #6893 0x400a4115 in eval_frame (f=0x8437594) at Python/ceval.c:2116 #6894 0x400a181f in PyEval_EvalCodeEx (co=0x40461460, globals=0x0, locals=0x0, args=0x8437594, argcount=1, kws=0x814b440, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #6895 0x400a76b5 in fast_function (func=0x41126a0c, pp_stack=0xbfffe6bc, n=1, na=1, nk=4) at Python/ceval.c:3529 #6896 0x400a2aa7 in call_function (pp_stack=0xbfffe6bc, oparg=6840) at Python/ceval.c:3458 #6897 0x400a4115 in eval_frame (f=0x814b2ec) at Python/ceval.c:2116 #6898 0x400a773e in fast_function (func=0x41126a0c, pp_stack=0xbfffe7ec, n=0, na=0, nk=135574252) at Python/ceval.c:3518 #6899 0x400a2aa7 in call_function (pp_stack=0xbfffe7ec, oparg=6840) at Python/ceval.c:3458 #6900 0x400a4115 in eval_frame (f=0x831ca34) at Python/ceval.c:2116 #6901 0x400a181f in PyEval_EvalCodeEx (co=0x4044e5a0, globals=0x0, locals=0x0, args=0x831ca34, argcount=5, kws=0x80d6870, kwcount=0, defs=0x40459938, ---Type to continue, or q to quit--- defcount=1, closure=0x0) at Python/ceval.c:2663 #6902 0x400a76b5 in fast_function (func=0x41126a0c, pp_stack=0xbfffe99c, n=5, na=5, nk=20) at Python/ceval.c:3529 #6903 0x400a2aa7 in call_function (pp_stack=0xbfffe99c, oparg=6840) at Python/ceval.c:3458 #6904 0x400a4115 in eval_frame (f=0x80d6654) at Python/ceval.c:2116 #6905 0x400a181f in PyEval_EvalCodeEx (co=0x4044e520, globals=0x0, locals=0x0, args=0x80d6654, argcount=0, kws=0x80baac4, kwcount=0, defs=0x4045e428, defcount=11, closure=0x0) at Python/ceval.c:2663 #6906 0x400a76b5 in fast_function (func=0x41126a0c, pp_stack=0xbfffeb4c, n=0, na=0, nk=0) at Python/ceval.c:3529 #6907 0x400a2aa7 in call_function (pp_stack=0xbfffeb4c, oparg=6840) at Python/ceval.c:3458 #6908 0x400a4115 in eval_frame (f=0x80ba974) at Python/ceval.c:2116 #6909 0x400a181f in PyEval_EvalCodeEx (co=0x4044e8a0, globals=0x0, locals=0x403fe79c, args=0x80ba974, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #6910 0x400a1152 in PyEval_EvalCode (co=0x4044e8a0, globals=0x403fe79c, locals=0x403fe79c) at Python/ceval.c:537 #6911 0x400dcc2d in run_err_node (n=0x403fe79c, filename=0xbfffefad "./Lib/test/regrtest.py", globals=0x403fe79c, locals=0x403fe79c, flags=0xbfffecf8) at Python/pythonrun.c:1265 #6912 0x400db668 in PyRun_SimpleFileExFlags (fp=0x8049a00, filename=0xbfffefad "./Lib/test/regrtest.py", closeit=1, flags=0xbfffecf8) at Python/pythonrun.c:862 #6913 0x400daf9e in PyRun_AnyFileExFlags (fp=0x8049a00, filename=0xbfffefad "./Lib/test/regrtest.py", closeit=1, flags=0xbfffecf8) at Python/pythonrun.c:659 #6914 0x400e3994 in Py_Main (argc=2, argv=0xbfffed74) at Modules/main.c:415 #6915 0x080486f3 in main (argc=5, argv=0xbfffed74) at Modules/ccpython.cc:10 Current language: auto; currently c (gdb) Some kind of "infinite" recursion? Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From peter at engcorp.com Tue Dec 9 16:18:24 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Dec 2003 16:18:24 -0500 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> Message-ID: <3FD63C20.45135F8@engcorp.com> Rene Pijlman wrote: > The modules are Cheetah templates (http://www.cheetahtemplate.org/) in > different skins of a website. I've made one package per skin, and my > website generator basically does: > > from skin import template > > where skin is only known at runtime (it's passed as a parameter or hidden > field to my mod_python application). > > The alternative would be: > > if skin == 'basic': > from basic import homepage > elif skin == 'modern': > from modern import homepage > > ... but this is unmaintainable and unpythonic. Unmaintainable as-is, perhaps, but pythonicism has nothing to do with this. What is probably cleaner *and* more maintainable is to have an extra level of indirection, with some kind of configuration file that in effect maps between the skin names and the Python package which implements it. I'd personally do this with a quick bit of XML, but I've been drinking too much Koolaid(tm) so ignore me. The problem I see with the above approach is that you are tying some strings that are used in your HTML pages directly to the names of Python modules. Unless you are doing this in an entirely automated fashion (e.g. generating the list of available skins via a directory scan) then you are increasing the coupling in your system inappropriately, and *that* is certain to be the least maintainable approach of all, IMHO. -Peter From jdhunter at ace.bsd.uchicago.edu Tue Dec 9 12:23:30 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 Dec 2003 11:23:30 -0600 Subject: regex confusion In-Reply-To: (Peter Otten's message of "Tue, 09 Dec 2003 17:51:01 +0100") References: Message-ID: >>>>> "Peter" == Peter Otten <__peter__ at web.de> writes: Peter> This may be off-topic, but the easiest if not fastest way Peter> to find multiple occurences of a string in a text is: Right, I actually am using regex matching and not literal char matching, but in trying to debug why my regex wasn't working, I simplified it to the simplest case I could, which was a string literal. Thanks for the DOTALL pointer above. JDH From fperez528 at yahoo.com Wed Dec 10 22:19:52 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 10 Dec 2003 20:19:52 -0700 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: Allenabethea wrote: > Jython is 100% java coded python. > Python objects work with javacompilers and Virtual machines. > > I am a hobby programmer so the technical reasons are probably beyond me... > Why is python incompatible with .net? Why can't python be coded in C#? > > I see the the MONO project on linux/unix is advancing. .Net seems to be a > juggernaut especially if programmers will be able to use their favorite(most > productive) language to program in. (every language but python) > > I am a new python tinkerer. I love the language. But what is its future but > as a legacy tool? > > allen Some who I suspect know a thing or two about python and .NET seem to disagree: http://primates.ximian.com/~miguel/activity-log.php Cheers, f From piir at earthlink.net Thu Dec 18 02:02:40 2003 From: piir at earthlink.net (Todd Gardner) Date: 17 Dec 2003 23:02:40 -0800 Subject: Calling dlls with Calldll/WinDll or Ctypes or... Message-ID: <9b849915.0312172302.7999d44a@posting.google.com> Hello all, Pardon my ignorance here. I would like to talk to someone that has had success in calling ddls in Windows NT/2000/XP. I am wondering where to dload any of these packages? Google searches keep turning up articles similar to this. Any pointers would be greatly appreciated! Todd From torsten.rueger at hiit.fi Fri Dec 19 04:11:57 2003 From: torsten.rueger at hiit.fi (Torsten Rueger) Date: Fri, 19 Dec 2003 11:11:57 +0200 Subject: SocketServer broadcast In-Reply-To: <3FE2BC10.210AEF11@mortauxspams.bz> References: <3FE2BC10.210AEF11@mortauxspams.bz> Message-ID: <656BF244-3203-11D8-B2B6-000A959C1BB0@hiit.fi> On Dec 19, 2003, at 10:51 AM, Olivier Hoarau wrote: > I have build a client/server application with the socket module. The > server mades UDP broadcasting and the client only reads UDP broadcast > messages. All work fine. Are you saying you have working server client/server code that works, but doesn't use the SocketServer ? If so, could you post it ? I've been trying to do the same thing, though I'd be fine with it not using the Socketserver, but no success. Sorry. Torsten From tjreedy at udel.edu Tue Dec 23 11:32:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Dec 2003 11:32:48 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Francis Avila" wrote in message news:vug18vkmjpiice at corp.supernews.com... The word 'name' is used in multiple senses in Python, which seems to sometimes get confused. > But a name is part of an object. Modules, classes, and functions have a __name__ attribute for the purpose of forming a string represention. Other builtins do not. This is the secondary use of 'name'. Otherwise, 'names', in the primary sense as code token, are *not* parts of an object. > Namespaces arise from objects possessing names. Since objects only 'possess' token names by virtue of being associated with them in namespaces, this does not seem a useful viewpoint. > This is why I can't see how names can be objects in Python: Token names are grammatical code units, like expressions and statements (which are also not objects *in* Python). We use them to direct computation with objects. The interpreter may implement token names (and namespaces) in any way consistent with the defined semantics of the expression and statement they occur in. CPython, in particular, sometimes converts them to Python strings and sometimes to C ints. >they are incapable of existing independent of an object. They exist in code prior to the creation of ojects due to running of the code. John Roth" wrote in message > Technically, since names are simply keys in dictionaries, This is only true of attribute names, the third use of 'name'. Definition names start as code token names and become values of a __name__ attribute, not a key. Code token names otherwise become whatever the interpreter does with them, which might or might not be to make them a Python dictionary key. Terry J. Reedy From duncan at NOSPAMrcp.co.uk Thu Dec 4 11:51:29 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 4 Dec 2003 16:51:29 +0000 (UTC) Subject: Why 'string' functions i.e. rstrip, upper, lower are 'not found'......... References: <2c82369d.0312040836.7374c789@posting.google.com> Message-ID: John_Dutcher at urmc.rochester.edu (John F Dutcher) wrote in news:2c82369d.0312040836.7374c789 at posting.google.com: > There must be a 'fundamental' reason why 'string' functions are > reported as 'not found' even though the 'import string' statement > is present. If the script has user-defined functions at its beginning > and I remove them...doing all code inline, the 'not found' error goes > away. Is there some 'placement of user functions' issue that explains > why the 'import string' doesn't make the various string functions > visible when I use various 'def userfunc's in the script ?? > Thanks much, > John D. > You need to be more specific. What is the *exact* error message you are seeing? Cut and paste it, don't paraphrase. If possible, cut the code down the the minimum that shows the problem and post it here. Cutting the code down also help you isolate the error yourself. If you can't cut the code down enough to post, then at least post the code around the area where the problem occurs. The only thing that immediately springs to mind would be that if you created a global variable, or a function, that was itself called 'string', that would overwrite the variable created by the import statement (think of both 'import' and 'def' as being statements that do a variable assignment as a side effect). BTW, you probably want to get to the bottom of this problem to help your understanding, but after you've done that you may find it simpler just to use the methods that strings have as that way you rarely need to import the string module. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From blk at srasys.co.in Thu Dec 11 04:22:55 2003 From: blk at srasys.co.in (bala) Date: Thu, 11 Dec 2003 14:52:55 +0530 Subject: I wan to know how to USE AAIE under pyAA module in python Message-ID: <005e01c3bfc8$5bf652e0$440210ac@Bala> Hi, I want to know how to use the AAIE under pyAA module in python... If u give the Tutorial Link and sample of how to use the AAIE...I will very thankfull to you.... Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From vze4rx4y at verizon.net Mon Dec 1 05:11:16 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 01 Dec 2003 10:11:16 GMT Subject: Fast attribute/list item extraction References: Message-ID: <8tEyb.18589$UG2.14269@nwrdny03.gnilink.net> [Peter Otten] > > extract[1] > > extract["key"] [Robert Brewer] > I'm having a hard time seeing the use cases, given that I find > most of them more readable if done with list comprehensions > or good ol' for loops. Peter's post focused on implementation instead of the context. For Py2.4, the list.sort() will have an optional key argument that encapsulates the decorate/sort/undercorate pattern. For example, here is the new fastest way to have a case insensitive sort leaving the original case intact: >>> words = 'The quick BROWN fox JumPed OVER the LAzy dog'.split() >>> words.sort(key=str.lower) >>> words ['BROWN', 'dog', 'fox', 'JumPed', 'LAzy', 'OVER', 'quick', 'The', 'the'] Though case insensitivity is straight-forward, the two most common cases need to be coded with lambda: records.sort(key=lambda r: r.someattr) # sort on an attribute records.sort(key=lamdda r: r[2]) # sort on a field number Not only is the lambda unattractive, it is slow. This situation is not unique to sort(), it comes up with other functionals like map() and filter(). A new itertool called groupby() also faces the same situation. So, the idea was born to add a fast extract function maker to the operator module: from operator import extract records.sort(key=extract('someattr')) records.sort(key=extract(2)) The same form is usable in other contexts as well: students.sort(key=extract('age')) for age, agegroup in groupby(students, extract('age')): print 'Students of age ', age for student in agegroup: print ' ', student.name The lastest incarnation of the extract() idea is have two separate extra functions (one using getitem and the other using getattr) rather than one overloaded function. Raymond From reply.in.the.newsgroup at my.address.is.invalid Mon Dec 8 08:04:39 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 Dec 2003 14:04:39 +0100 Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: David McNab: >a framework which allows mountable linux filesystems to be >implemented in pure python. Serious question: why? -- Ren? Pijlman From adsl5lcq at tpg.com.au Sun Dec 14 00:37:09 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Sun, 14 Dec 2003 16:37:09 +1100 Subject: continue and break frustration Message-ID: Hello All. I've been coding in python for a reasonable amount of time now (coding in total for approx. 20 years) and am writing a performance intensive program in python. The problem I'm having is I want to use break and continue to get out from more than one level of loop. If I set a variable and then check it my program will take too much of a performance hit. Are there any alternatives people can think of? Thanks, Glen From exarkun at intarweb.us Tue Dec 23 13:27:08 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 23 Dec 2003 13:27:08 -0500 Subject: twisted request In-Reply-To: <9a6d7d9d.0312230829.29b014fa@posting.google.com> References: <9a6d7d9d.0312230829.29b014fa@posting.google.com> Message-ID: <20031223182708.GB25399@intarweb.us> On Tue, Dec 23, 2003 at 08:29:39AM -0800, Aaron Watters wrote: > I have a "chat" protocol module called "Hollerith" which > is appropriate for use with threads or stackless, but is not > ready for "event loop" style programming. Can someone show > me how to implement it (and use it) using Twisted? > > http://cvs.sourceforge.net/viewcvs.py/*checkout*/xsdb/xsdb/xsdb/Hollerith.py?content-type=text%2Fplain&rev=1.1 > > Of course the twisted version should never block, please. > > Thanks in advance, -- Aaron Watters > Twisted includes a netstring implementation and an int32 string implementation, both of which are conceptually very similar to the underlying function of Hollerith. Adapting either should be a simple task. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From michele.simionato at poste.it Mon Dec 8 11:58:12 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 8 Dec 2003 08:58:12 -0800 Subject: New inited instance of class? References: Message-ID: <95aa1afa.0312080858.69cc9a42@posting.google.com> "Francis Avila" wrote in message news:... > That strikes me as a very *bad* idea, because it's no longer obvious that > the classes themselves are new-style, and the OP might develop a bad habit > of using this to avoid typing '(object)' all the time. (Or he might show us > all for fools, if ':' becomes shorthand for '(object):'.) I don't disagree. > Aside from that, metaclasses are a more advanced and less-commonly-used > feature of classes, and therefore probably more vulnerable to change. I > know it should work, but am uneasy that it might manifest some unexpected > behavior (or bug). Maybe you are worrying a bit too much here, since the __metaclass__=type idiom is quite safe in practice. Of course, it can give surprises, such as the following: __metaclass__=type class E: pass raise E() # not the error you would expect Nevertheless, you should derive exceptions from Exception, so this does not happen in real live. The other caution is with certain usages of special methods, but they are relatively rare. On the other hand, custom metaclasses different from type can give more than one surprise, so I would not suggest their use to the causal programmer. BTW, also the experienced programmer can live without metaclasses for 99% of tasks. But they may come handy in special situations. Michele From loic at yermat.net1.nerim.net Tue Dec 30 05:16:42 2003 From: loic at yermat.net1.nerim.net (Yermat) Date: Tue, 30 Dec 2003 11:16:42 +0100 Subject: When to put my modules References: <3ff0e744_1@dns.sd54.bc.ca> Message-ID: Hi, "Bob van der Poel" a ?crit dans le message de news:3ff0e744_1 at dns.sd54.bc.ca > I'm working on a moderately sized application and I'm planning on > having a fair number of modules. The only question in my mind is: > where do I put the modules ... and how do I let python know about > them? see http://www.python.org/doc/current/tut/node8.html especially the 6.1.1 > I could put them with the rest of the python lib, but I'm not really > presumtious to do that. Not that good... > I can keep them all in the current directory, but that forces the user > to chd to a certain location all the time. > > Best, I think, is to put them in a program specific location. My > program needs some other data files, etc. so I'm thinking that I can > just put the python stuff in /usr/local/lib/MYPROGRAM/modules. Not that good too. You may want to re-use your module later in another program... > Okay, but what about when I'm just working on them? In this case I'd > like them to be in my current working dir. > > Is there a magic line I need to add to the top of the main module to > set the path up? > > Apologies if this is covered in a document...but I can't see to find > anything. Maybe this is a faq? What I'm doing is something like this : All my module are in a directory such as /home/loic/MyPython/. I set the PYTHONPATH to that directory. I've got for example a module rtf in /home/loic/MyPython/rtf/, another one Heredis in /home/loic/MyPython/Heredis and my program is in /home/loic/MyPython/Heredis2Gedcom for example. In that way, I don't mix my module with standard one. Every program can access all non program specific module. For other tips, look at sys.path too. Hope it help ! Yermat From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 30 06:14:34 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Dec 2003 12:14:34 +0100 Subject: Programming language from python In-Reply-To: <8fk2vvg18hgvocrmm09b86epekpdnuc02t@4ax.com> References: <8fk2vvg18hgvocrmm09b86epekpdnuc02t@4ax.com> Message-ID: <3ff15e50$0$318$e4fe514c@news.xs4all.nl> Rene Pijlman wrote: > The lander defense system of the Martians is also quite good. Ah! I already suspected that the 'it has landed in a hole' excuse about why the Beagle2's contact is lost, was a lie. What truly happened is that it has been obliterated by a gamma ray. :-) --Irmen From mcfletch at rogers.com Mon Dec 8 16:18:32 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 08 Dec 2003 16:18:32 -0500 Subject: Understanding and working with __metaclass__ In-Reply-To: <99dce321.0312081149.2a32575d@posting.google.com> References: <99dce321.0312081149.2a32575d@posting.google.com> Message-ID: <3FD4EAA8.4060808@rogers.com> http://members.rogers.com/mcfletch/programming/metaclasses.pdf Is intended to answer exactly this question. HTH, Mike David M. Wilson wrote: >Hi there, > >I've been sitting on the __metaclass__ feature for about 2 weeks now, >and haven't really got that far with it. It looks like a very powerful >tool, and I think I have even already identified places in my code >where I could use it quite effectively, but I can't quite tell what it >is /meant/ to be used for, or indeed what it is popularly used for. > >Is there a page, posting, or other place I can turn to to get a >developer's run-down on the practical uses of __metaclass__? The >Python documentation states very clearly what it does, but I fear that >journeying off on my own with it will lead to some terrible habit >formation, and I already have enough of those to deal with. :) (:set >ts=3 ;) > >Thanks for your time, > > >David. > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From piir at earthlink.net Mon Dec 8 19:49:17 2003 From: piir at earthlink.net (Todd Gardner) Date: 8 Dec 2003 16:49:17 -0800 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: <9b849915.0312081649.71df2880@posting.google.com> "Colin J. Williams" wrote in message news:... > Todd, > > If you are using wxPython, you might consider wxPyPlot: > http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html > > Colin W. > Thanks Colin! wxpyplot is awesome! My criteria are rather loose at this point because I do not have any clue what is available. I currently use a language called LabVIEW to plot. I guess that is what I am after for functionality. wypyplot does not do everything LV does but it comes close. Now I have a specific question. Given that I am rather ignorant in using wxpyplot where should I look to get started? Thanks, Todd > Todd Gardner wrote: > > Peter Hansen wrote in message news:<3FD3E423.B53D23DE at engcorp.com>... > > > >>Todd Gardner wrote: > >> > >>>I would like to graph two columns of x,y numbers? I would greatly > >>>appreciate any pointers or suggestions. > >> > >>Yes, include more detail about what you want to do. Specifically, > >>what platform, do you care if it's wxPython, or Tkinter, or something > >>else, etc. There are about a zillion possible answers to your > >>question as it stands, and "python graphing" or something on Google > >>would likely get you a lot of mileage right now. Maybe after you > >>do a little research there you can come back with a more detailed > >>question? > >> > >>-Peter > > > > > > There are LOTS of plotting choices on google. I guess I would like to > > narrow them down by tapping into some expertise. > > > > I would like to do 2D and possibly 3D plotting with python. I am > > tending toward wxpython because of it's ease of use. > > > > Any suggestions? Thanks in advance. Todd From jjl at pobox.com Thu Dec 11 18:33:28 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 23:33:28 +0000 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> Message-ID: <87vfon0w1j.fsf@pobox.com> hungjunglu at yahoo.com (Hung Jung Lu) writes: [...] > I got looking into PBP because Python starts to look evil when you use > descriptors, metaclasses, etc. And that's not just Python: the > fundamentals of most well-known languages are getting more and more > complicated. The current programming world reminds me of the situation > of the time when RISC came up against CISC. I mean, it's OK for a lot > of additional features to be built on top of the fundamentals, but > nowadays the fundamentals themselves are getting too complicated. Is In principle, I agree, though I can't say it's ever actually bothered me in practice with Python. > it time to take a break and say: "there is gotta be a simpler way!"? [...] JavaScript (no, don't run away!) is actually quite similar to Python and is prototype-based. JavaScript (ECMAScript, now) has a global object (that happens to be window in web browsers) that functions rather like the global namespace in other languages. John From noemail at noemail4u.com Mon Dec 22 08:26:33 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 22 Dec 2003 13:26:33 GMT Subject: dynamic typing question References: <27377dcdd307865f045cc7064818d389@news.teranews.com> Message-ID: On Mon, 22 Dec 2003 13:23:55 GMT, Dang Griffith wrote: > Finally, the standard Python distribution includes PyUnit for >developing unit tests, following the same principles as JUnit, et al. The module is called unittest, though, not PyUnit. --dang From imbosol at aerojockey.invalid Mon Dec 22 03:03:38 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 22 Dec 2003 08:03:38 GMT Subject: test if a file is locked? References: Message-ID: Benjamin Han wrote: > > > On Mon, 22 Dec 2003, Carl Banks wrote: >> Fortepianissimo wrote: >> > >> > >> > I can lock a file using the following snippet: >> > >> > --- >> > import fcntl >> > >> > f=open('flock.txt','w') >> > fcntl.lockf(f.fileno(),fcntl.LOCK_EX) >> > --- >> > >> > If some other script tries to open 'flock.txt', it'll wait until the >> > file is unlocked/closed. >> > >> > My question is, I'd like to tell a script to quit *immediately* if it >> > cannot open the file, or, if it knows the file is locked. >> > >> > The reason I need this is I want to serialize parallel processes using >> > a lock file. Any suggestion is welcome! >> >> >> Try this: >> >> fcntl.lockf(f.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB) > > Ok looks like I'm still missing something: so how do you get 'f' without > using open() or file()? Either of these will put the script on hold... > > Thanks! Have you tried it? (Hint: it's not "open" that waits until the file is unlocked.) -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From somebody at nowhere.com Wed Dec 10 14:40:59 2003 From: somebody at nowhere.com (Sean Richards) Date: Thu, 11 Dec 2003 08:40:59 +1300 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> Message-ID: <87k754xxys.fsf@hugin.valhalla.net> Dang Griffith writes: > On Wed, 10 Dec 2003 11:19:21 +0100, Irmen de Jong > wrote: > >>Sean Richards wrote: >> >> >>> Tab completion for keywords and methods etc (you can get this in the >>> standard python shell as well of course) >> >>You can? How? >> >>--Irmen > > Press tab after typing part of the keyword/method. > > This assumes you're *not* using Win32. The documentation says that > IPython requires the GNU readline function, which I guess isn't > available with Win32. Neither is color highlighting. > > --dang Actually you can get all this on win32 if you use the cvs version of IPython and Gary Bishop's Python readline module. There is a URL and instructions on how to set it up here. http://www.scipy.net/pipermail/ipython-dev/2003-December/000094.html The Python readline module needs ctypes so get that as well. Works with Python 22 and 23 and gives you readline functionality and colour highlighting when using IPython under win32. Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From aahz at pythoncraft.com Sat Dec 20 08:37:25 2003 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2003 08:37:25 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: In article , John Roth wrote: > >The people who have switched don't post here. I'm very active >on the XP mailing list, and I see lots more references to Ruby than >to Python. Maybe the fact that such industry heavy hitters as Robert >Martin, David Thomas, and any number of others have switched >shouldn't count. In fact, the head of this thread should really be a >wakeup call: the *only* reason that Python was chosen instead >of Ruby is the lack of *current* market penetration. AFAIK, those are all people who were never heavy Python users. We're still getting plenty of people switching to Python instead of Ruby, largely because there are more killer applications written in Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From mike at mhuffman.com Sun Dec 7 01:05:23 2003 From: mike at mhuffman.com (Mike Huffman) Date: 6 Dec 2003 22:05:23 -0800 Subject: Installing Python 232 onto CD-ROM References: Message-ID: <3ae9c53d.0312062205.37f66321@posting.google.com> > heck the sys.path list and no \lib\site-packages subdirectory. (Running > from the removable, this subdirectory does appear. And the subdirectory > is on both the CD-ROM and removable cartridge.) Add a .pth file with > the subdirectory string. Still no good. > Are you by any chance trying to run the CD-ROM on a Windows 98 system? Python is case-sensitive with regard to loading modules. However, Windows 98 does not seem to retain Windows 2K/XP case for 8.3 file names. For example, os.pyc in Windows 2K/XP becomes OS.PYC on Windows 98, and you typically get a message like " 'import site' failed; use -v for traceback " Try setting the environment variable PYTHONCASEOK to some non-zero value. The command set PYTHONCASEOK=1 worked for me. Mike Huffman From boydrobh at yahoo.com Tue Dec 30 11:34:48 2003 From: boydrobh at yahoo.com (Rob Boyd) Date: Tue, 30 Dec 2003 08:34:48 -0800 (PST) Subject: FIXED - Re: build problems on Solaris 9 In-Reply-To: <20031230152830.82136.qmail@web42004.mail.yahoo.com> Message-ID: <20031230163448.65824.qmail@web42001.mail.yahoo.com> Never mind... Fixed my problem by using crle (learned something new). 'make' still couldn't import curses, but I don't expect to be using that. Rob --- Rob Boyd wrote: > Hi, > > I am having problems building Python 2.3.3 on > Solaris > 9, on a SunFire SPARC. I am using gcc 3.3.2, and > apparently don't have binutils (but have ld, as, ar, > and the like). I have set LD_RUN_PATH appropriately. > > During 'make', I get many warnings such as: > "WARNING: renaming "regex" since importing it > failed: > ld.so.1: ./python: fatal: libgcc_s.so.1: open > failed: > No such file or directory". I can still subsequently > install Python, but it is broken. > > Despite the warning, libgcc_s.so.1 is in > /usr/local/lib. Plus, I did not get these errors > when > building Python 2.3.2, and it does not fail to find > libstdc++.so.5 (which fails if LD_RUN_PATH is not > set). > > Any help is greatly appreciated. Sorry if this is in > a > FAQ or prior posts, but my searches, and the Solaris > section in the README have not helped resolve this. > > Rob Boyd > __________________________________ Do you Yahoo!? Find out what made the Top Yahoo! Searches of 2003 http://search.yahoo.com/top2003 From mir4uu at yahoo.com Tue Dec 9 12:32:22 2003 From: mir4uu at yahoo.com (mir nazim) Date: 9 Dec 2003 09:32:22 -0800 Subject: online examination system Message-ID: <425cc8d1.0312090932.697fd6c6@posting.google.com> hi there, One of my client needs a computer based examination system. It should have following capabilities. 1. It should support Multiple choice questions. 2. It should be adaptive, that is, difficulty should vary with each question. kind of those used in MCSD/MCSE/SCJP etc examinations. 3. should be web based. 4. MySQL support. (better be Database independent) 5. OS independent. Now please let me know if there is one available for ZOPE platform. blesses-n-luck From skip at pobox.com Mon Dec 15 10:33:44 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Dec 2003 09:33:44 -0600 Subject: How to integrate python, vtk and C++ object ? In-Reply-To: References: Message-ID: <16349.54360.934093.432933@montanaro.dyndns.org> YY> I need to integrate python, vtk and my own C++ object. Is it YY> possible to do it by using python/C API ? Or there is a more YY> efficient way to do it. Where can I find the examples taking about YY> that ? Thanks in advance !!! There is a VTK binding for Python which comes with the VTK source. There is a pretty fabulous visualization tool called MayaVi which is written in Python and uses that binding. You should be able to get some good ideas from one or both sources. As for mixing in your own C++ objects, I'm sure it can be done, but am not sure how. Check out Boost.Python and SWIG and candidate tools for incorporating your classes into Python. Skip From jsbenson at bensonsystems.com Tue Dec 16 17:25:59 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 16 Dec 2003 14:25:59 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python) Message-ID: <011101c3c423$94c035f0$d709500a@jsbwxp3> I used FORTH on the Commodore VIC-20 and -64. Sound chip access and light pen input made for a lot of fun. However, the parameter stack is always in your face; if you didn't push or pop it, it didn't go to a callee or get returned from same. Because of this, I suggest that Pythonistas fans accustomed to easily passing objects, lists and dictionaries to a called function may feel rather hobbled when attempting to use FORTH. If you want to keep high-level coding style and go for the small footprint, my guess is that Lua (or something like it) would be much more friendly. From spiffy at worldnet.att.net Tue Dec 9 19:27:07 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Wed, 10 Dec 2003 00:27:07 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> <2fsBb.423999$0v4.20388116@bgtnsc04-news.ops.worldnet.att.net> <3fd66012$0$113$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: "Fedor" wrote in message news:3fd66012$0$113$3a628fcd at reader2.nntp.hccnet.nl... > > "Spiffy" wrote in message > news:2fsBb.423999$0v4.20388116 at bgtnsc04-news.ops.worldnet.att.net... > > > > "Diez B. Roggisch" wrote in message > > news:br5hu8$em2$01$1 at news.t-online.com... > > > > Here is the code used to call it from Python: > > > > import os > > > > filename = "C:\Python22\Canyon.mid" > > > > os.system("C:\Python22\playb.exe%s"%filename) > > > > ...this causes a dos box to appear which promptly hangs and does > > nothing, > > > > at which time Python stops responding. Vartiations on this will cause > > the > > > > dos box to appear with the message "Bad command or file name". > > > > > > > > > > Looks like there is a space missing - > > > > > > os.system("C:\Python22\playb.exe %s"%filename) > > > ^ > > > > > > Diez > > > > > There is no space missing. That is the name of the file on my comp. > > > > > > The ^ points right after exe. (use fixed fonts to see). The command you are > executing is: > > C:\Python22\playb.exeC:\Python22\Canyon.mid > > There needs to be a space between exe and the second C: > > Hope it helps. > > I have tried your suggestion and put a space after the .exe...the result is the same as before...a dos box appears and does nothing and python crashes (stops responding). From deets_noospaam at web.de Tue Dec 9 11:16:54 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 17:16:54 +0100 Subject: regex confusion References: Message-ID: John Hunter wrote: > > In trying to sdebug why a certain regex wasn't working like I expected > it to, I came across this strange (to me) behavior. The file I am > trying to match definitely contains many instances of the letter 'a', > so I would expect the regex > > rgxPrev = re.compile('.*?a.*?') This is a bogus regex - a '*' means "zero or more occurences" for the expression to the left. '?' means "zero or one occurence" for the exp to the left. I'm not exactly sure why this is not working, but its definitely redundant. Eliminiating the redundancy gives you this: rgxPrev = re.compile('.*a.*') Works perfect. Regards, Diez From ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ Thu Dec 11 10:27:02 2003 From: ZZZ-ialbert-ZZZ at mailblocks-ZZZ.com-ZZZ (Istvan Albert) Date: Thu, 11 Dec 2003 10:27:02 -0500 Subject: Preview of a Stackless Zope Application In-Reply-To: References: Message-ID: Christian Tismer wrote: > Let me know your thoughts... > > http://www.centera.de/tismer/stackless/zope_demo Seems to work only of I allow the site to set a cookie and thus retrieve a session. But if so doing the same thing the old fashioned way is also very simple. Istvan. From MidasOneTwo at hotmail.nospam.com Sat Dec 27 19:23:14 2003 From: MidasOneTwo at hotmail.nospam.com (Midas) Date: Sun, 28 Dec 2003 00:23:14 GMT Subject: ObjectA calling ObjectB References: <3fedd9cc.46564976@news.iprimus.ca> <87smj656xu.fsf@mobile.foo> <3fedf97e.54680044@news.iprimus.ca> <3fee1d7d.350511859@news.blueyonder.co.uk> Message-ID: <3fee224a.65125244@news.iprimus.ca> Thanks for assisting. What I'm trying to do is as follows: Part 1) Create 10 new assorted objects Part 2) Link up the objects, somehow, so they can communicate with each other directly, like parts of an electrical circuit. Part 3) Call the first object, which calls another, etc. like an electrical circuit. To change the circuit, I would only change part 2 and perhaps part 3. For example, ObjectX could have an input, for a string, and two outputs. If the input is "TurnOnS", it calls ObjectY.Input3 If the input is "TurnOnT", it calls ObjectZ.Input7 ObjectX would call either, ObjectY.Input3 or ObjectZ.Input7, because it was connected that way in part 2. I could then later change part 2 so ObjectX called either ObjectE.Input2 or ObjectF.Input9 In other words, I could "re-wire" the circuit without changing anything in the objects. From newsgroups at jhrothjr.com Sat Dec 20 16:23:53 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 16:23:53 -0500 Subject: dynamic typing questions References: Message-ID: "Robert Brewer" wrote in message news:mailman.378.1071946544.9307.python-list at python.org... Unit tests are wonderful, _IF_ you pre-conceive all the corner cases. This is, of course, impossible in any sufficiently powerful system to be worthwhile. Unit test are the greatest thing since sliced bread. No argument from me. But Mr. Roth's hyperbole regarding the usefulness of debuggers is out of place. IF you only use code you write, and IF you fully understand your problem domain and range, then you MIGHT not need a debugger. The rest of us mortals use them when they're needed. [John Roth] Which means, I suppose, that the immortals use print statements. [grin] Seriously, I don't use one often enough to remember how to use it. I only used them seriously for a few years after I got to work on a system that had one (IBM MVS 20 Beta TSO, if you have to know.) When I started in '65, we had one system where we were lucky to get one turnaround a week. That wasn't usual, most of the systems had one turnaround per day. Planning beats flailing around in the debugger any day. John Roth [/jr] Robert Brewer MIS Amor Ministries fumanchu at amor.org From echols at uclink.berkeley.edu Sat Dec 6 20:07:32 2003 From: echols at uclink.berkeley.edu (Nat Echols) Date: Sat, 6 Dec 2003 17:07:32 -0800 Subject: segfault in extension module In-Reply-To: References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: > *That's* very odd. > > Can we see a little more? Yup: Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 1074141248 (LWP 5500)] 0x420744b0 in _int_free () from /lib/tls/libc.so.6 (gdb) bt #0 0x420744b0 in _int_free () from /lib/tls/libc.so.6 #1 0x420734d6 in free () from /lib/tls/libc.so.6 #2 0x08055a1f in _PyObject_Del () #3 0x080593c5 in PyString_AsEncodedString () #4 0x0807db19 in _PyEval_SliceIndex () #5 0x080c41c9 in PyFunction_SetClosure () #6 0x080cdf49 in PyDict_New () #7 0x080ce35e in PyDict_SetItem () #8 0x080d1799 in _PyModule_Clear () #9 0x0808e81a in PyImport_Cleanup () #10 0x08096114 in Py_Finalize () #11 0x080539bf in Py_Main () #12 0x08053469 in main () #13 0x42015574 in __libc_start_main () from /lib/tls/libc.so.6 Now, if I run it interactively instead (still within gdb), I get this backtrace when it segfaults after I try to exit Python: Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 1074141248 (LWP 5502)] 0x420744b0 in _int_free () from /lib/tls/libc.so.6 (gdb) bt #0 0x420744b0 in _int_free () from /lib/tls/libc.so.6 #1 0x420734d6 in free () from /lib/tls/libc.so.6 #2 0x08055a1f in _PyObject_Del () #3 0x080593c5 in PyString_AsEncodedString () #4 0x080ce4d9 in PyDict_DelItem () #5 0x0805f1f2 in PyString_Fini () #6 0x08096153 in Py_Finalize () #7 0x080539bf in Py_Main () #8 0x08053469 in main () #9 0x42015574 in __libc_start_main () from /lib/tls/libc.so.6 From fedor at mailandnews.com Tue Dec 9 18:51:52 2003 From: fedor at mailandnews.com (Fedor) Date: Wed, 10 Dec 2003 00:51:52 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> <2fsBb.423999$0v4.20388116@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <3fd66012$0$113$3a628fcd@reader2.nntp.hccnet.nl> "Spiffy" wrote in message news:2fsBb.423999$0v4.20388116 at bgtnsc04-news.ops.worldnet.att.net... > > "Diez B. Roggisch" wrote in message > news:br5hu8$em2$01$1 at news.t-online.com... > > > Here is the code used to call it from Python: > > > import os > > > filename = "C:\Python22\Canyon.mid" > > > os.system("C:\Python22\playb.exe%s"%filename) > > > ...this causes a dos box to appear which promptly hangs and does > nothing, > > > at which time Python stops responding. Vartiations on this will cause > the > > > dos box to appear with the message "Bad command or file name". > > > > > > > Looks like there is a space missing - > > > > os.system("C:\Python22\playb.exe %s"%filename) > > ^ > > > > Diez > > > There is no space missing. That is the name of the file on my comp. > > The ^ points right after exe. (use fixed fonts to see). The command you are executing is: C:\Python22\playb.exeC:\Python22\Canyon.mid There needs to be a space between exe and the second C: Hope it helps. From bokr at oz.net Sat Dec 13 19:06:27 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 00:06:27 GMT Subject: case-sensitivity References: Message-ID: On Sat, 13 Dec 2003 20:31:46 GMT, Dennis Lee Bieber wrote: >Douglas Alan fed this fish to the penguins on Saturday 13 December 2003 >01:03 am: > >> >> In the ol' days it was actually a semi-plausible argument that you >> shouldn't make your identifies too long because you'd be too likely to >> make a mistake when typing them. >> > There was also the minor factor that, while the HOL might allow longer >(say 32 character) identifiers, if the HOL produced assembly output >rather than final binary, those identifiers were truncated to fit an >assembly pass that might only allow eight characters -- so any >identifier that was identical in the first eight characters was >considered the same by the assembler. > IIRC the old Pascal (as defined by Jensen/Wirth manual) also ignored characters beyond 8 in identifiers, though I think it allowed them. Regards, Bengt Richter From somebody at nowhere.com Wed Dec 10 03:55:59 2003 From: somebody at nowhere.com (Sean Richards) Date: Wed, 10 Dec 2003 21:55:59 +1300 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: Message-ID: <87ekvdgig0.fsf@hugin.valhalla.net> seberino at spawar.navy.mil (Christian Seberino) writes: > I know IPython is another interpreter for Python and was wondering > what people liked about it and if I should switch to it. Some things i like are ..... Typing ? after a function name gives you the function definition and docstrings for the function. i.e arange? returns Type: builtin_function_or_method Base Class: String Form: Namespace: Interactive Docstring: arange(start, stop=None, step=1, typecode=None) Just like range() except it returns an array whose type can be specified by the keyword argument typecode. Normal shell commands like cd & ls are available Tab completion for keywords and methods etc (you can get this in the standard python shell as well of course) Heaps more features but those are the killers for me (YMMV) > If it is so good then why is it not part of the standard Python > tarball? No idea. It's no big deal for me to download it separately and install it. You could ask the same question about many other Python packages, if they were all included the distribution would start getting a bit big I think. Anyway give IPython a try I think you will like it. Sean -- "Hver sin smak", sa vintapperen, han drakk mens de andre sloss. From edreamleo at charter.net Tue Dec 2 10:09:24 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 2 Dec 2003 09:09:24 -0600 Subject: PyChecker lives! Version 0.8.13 released. References: Message-ID: > As always, I'd like to hear your suggestions for common mistakes and bugs than can/should be found by PyChecker. Hi Neal. Thanks for these questions, and thanks for pychecker! More nifty checks would always be welcome, but for me, some fairly small and easy changes to pychecker might make a big difference. I would suggest putting more of your attention on giving the user more control over pychecker. In particular: 1. Make it really clear and obvious in the documentation that it is possible to drive pychecker using options.py. Put some screenshots in the docs, etc. 2. Bring options.py up-to-date: support all options (or maybe document things better). For example, I've never been able to get the suppressions dictionary in .pycheckrc to work, despite numerous experiments. I miss not being able to get this to work every time I run pychecker. 3. Add an option to options.py so one can specify a source file to run. Better yet, allow a list of files to check. As it is now, I have to browse to the file. 4. Think about ways to make pychecker scriptable. This is a biggie. If it is already, then _tell us about it_ (!!) 5. Think about ways to make pychecker less monolithic and more useful for unit testing. In effect, I'd like unit tests to be able to run a specific set of tests on specific files with specific options without having to mess with options.py or .pycheckrc. This would be so cool. I don't believe any of these items would take a lot of technical work, but they would make pychecker hugely more useful to me. Thanks for listening. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From BJ at replyhere.now Wed Dec 3 08:59:38 2003 From: BJ at replyhere.now (BJ MacNevin) Date: Wed, 03 Dec 2003 13:59:38 GMT Subject: Can Python be run off of a CD-ROM? References: Message-ID: WOW! Lots of responses. Thanks everyone! I need to play around with it more. My first attempt of just dragging the C:\python23 directory and copying the .dll's into it did work by and large... no IDLE which is a bummer (but understandable). So I will try some of the other options shared here. Thanks again for all the great and helpful feedback! BJ MacNevin "BJ MacNevin" wrote in message news:BhVyb.389117$Tr4.1144562 at attbi_s03... > Hi all, > > I teach middle school and am currently trying to bring some computer science > to the students. Our district has a wonderfully linked network throughout > all our schools... done via MS Windows Network. In order to protect the > network, our district's IT department does not want things installed on the > system (or at least makes it VERY difficult to get it done). SO, I am using > MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it > off of them. > > BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I > can do the same thing... or something similar? Is there a way to install > Python on a CD-ROM, too, if we don't need it to be accessed from a command > prompt? > > Thanks, > BJ MacNevin > > -- > _______________________________ > I didn't say it was your fault... > I said I was going to blame you. > > From ac007 at bluewin.ch Thu Dec 4 20:51:29 2003 From: ac007 at bluewin.ch (Alexandre) Date: Fri, 5 Dec 2003 02:51:29 +0100 Subject: xml.dom.minidom -> nextElement ? References: <3fcfdfdf$1_2@news.bluewin.ch> Message-ID: <3fcfe4a3_2@news.bluewin.ch> little correction, next time ill test before sending :) *************************************** def nextElement(current): next = current.nextSibling if next == None: return next elif next.nodeType == next.ELEMENT_NODE: return next else: return nextElement(next) *************************************** From edreamleo at charter.net Fri Dec 5 12:01:24 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 5 Dec 2003 11:01:24 -0600 Subject: ANN: Leo 4.1 beta 5: An outlining editor References: Message-ID: > Parsing ambiguity: Is that e-dream-leo or ed-ream-leo ? ;-) Sometimes ambiguity is nice. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From bokr at oz.net Sun Dec 7 21:38:58 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Dec 2003 02:38:58 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On Mon, 8 Dec 2003 03:01:09 +0300, "Serge Orlov" wrote: >Bengt, > >don't take it personally but this what happens when you use unicode >unaware software: >Quote from your message: >> martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: > >Your software also doesn't specify message encoding. > >The real issue is to convince developers that there are many encodings in >this world. Python should offer only one way to deal with multiple encodings. >Your 8-bit strings with attached coding attribute is duplicating what unicode >strings offer. In one sense yes (being able to represent all the same character sequences one way or another) but other senses no. Part of the concern was matters that could well be totally hidden behind a unicode interface (internal representation/optimization issues). Normalizing to one methodology usually saves time and space, but if there are use cases where the normalization is a useless 1:1 transformation, then not. But then it becomes a matter of how much overhead there is in deciding which situation applies. It may or may not be worth it. Anyway, that's one path of discussion. Another is how to deal with the fact that you wouldn't want to convert all current str data into unicode (e.g. data that is really pure bytestrings and has no character interpretation). If we were starting from scratch, it would be a lot easier to disentangle bytestrings and charstrings. That's really the problem that led to most of my ramblings. My tacking on .coding attributes is really a kludge to create a hybrid charstring/bytestring. I don't like kludges, but otherwise I don't currently see a way short of major breakage, and Martin predicts I'll run into major problems any way I might want to try going. His opionion is nothing to sneeze at ;-) > >> >> If e.g. name had latin-1 encoding associated with it by virtue of source like >> >> ... >> >> # -*- coding: latin-1 -*- >> >> name = 'Martin Lowis' >> >> >> >> then on my cp437 console window, I might be able to expect to see the umlaut >> >> just by writing >> >> >> >> print name >> > >> >I see. To achieve this effect, do >> > >> ># -*- coding: latin-1 -*- >> >name = u'Martin Lowis' >> >print name >> Right, but that is a workaround w.r.t the possibility I am trying to discuss. > >It's not a workaround it's a solution. What you propose is a lot of effort for It's one solution to a particular problem. That solution was proposed as a way to get an end effect. I wasn't asking for help on how to get the end effect. I think I can do that ;-) I was discussing another problem, namely that a bare quoted string is not sufficient to cause the proper encoding conversions for output even though the encoding could be determined unambigously from the source file encoding. >a little gain wrt handling multiple encoding. It's already possible to handle I don't consider being able to eliminate unnecessary source text cruft little gain. >multiple encoding. The time is better spent converting everything that still >deals with 8-bit text to handle unicode. It was always possible to handle multiple encodings, if you wanted to go to the trouble of writing your own solution. If you are happy with the u'...' prefix as the final answer to handling multiple character sets, and consider python evolution finished there with that issue, that's fine. But the problem is also disentangling text uses from byte uses of str, and migrating towards transparent use of unicode oer the quivalent. This gets into language design issues that are more interesting than just how to make a multi-char-set app work using python as it is currently. I doubt if wholesale conversion to unicode is a good idea. E.g., you wouldn't want to read a latin-1 log file of hundreds of megabytes and get automatic conversion to 16-bit unicode for no reason, I wouldn't think. You could have a unicode interface that hid internal bytestrings-with-various-encodings-attached. And then you are getting into that part of what I was discussing. The other part is how to disentangle charstrings from bytestrings without rewriting the world. Hence proposing, for discussion, a kludge that might let str act as both. But you didn't see me mention the PEP word anywhere yet, did you ;-) Martin says the problem is hard. I believe him. I still like to bat ideas around with intelligent people (of which there are a fair number posting to this group), even at the risk of striking out some of the time. Sometimes something worthwhile emerges that perhaps no one participating would have thought of without the interchange to trigger a key thought. I'll be off line for a few days (pre-apologizing in case I appear to be ignoring anyone ;-) Regards, Bengt Richter From exarkun at intarweb.us Thu Dec 11 09:26:07 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 11 Dec 2003 09:26:07 -0500 Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha In-Reply-To: References: <9a6d7d9d.0312110538.568014ef@posting.google.com> Message-ID: <20031211142607.GA20313@intarweb.us> On Thu, Dec 11, 2003 at 02:03:35PM +0000, Duncan Booth wrote: > aaron at reportlab.com (Aaron Watters) wrote in > news:9a6d7d9d.0312110538.568014ef at posting.google.com: > > > regarding the use of stackless in > > http://xsdb.sourceforge.net > > "Fredrik Lundh" wrote in message > > news:... > >> Aaron Watters wrote: > >> > 5) use an event loop and use a generator for the relevant code; > >> when you discover that you need to pause, yield to the framework. > > > > Please tell me I'm missing something, but I don't think > > this will really help. The problem is that I need to "yield" > > or "suspend" or "send something across a channel" from about > > 45 places in the code some of which are arbitrarily deep into > > multiple recursions. The generator thing will only allow > > me to go one level deep into a single call -- no? By contrast > > the stackless.channel mechanism is a far more general construct, > > allowing me to "yield" at any point without restructuring the > > code at all. Stackless rules. > > The generator solution may not be appropriate for your task, but it isn't > entirely accurate to say that you can only go one level deep. You can (sort > of) yield from arbitrarily deep function nesting, or even from recursive > functions. The catch though is that you do have to write the code in a > slightly contorted manner in order to yield from below the first function. > > The rule to follow is simply: any function which wants to yield, or which > calls a function that wants to yield has to be a generator and has to be > called from a 'for' loop which itself yields. > > e.g. A generator that walks a tree recursively: > > def inorder(t): > if t: > for x in inorder(t.left): > yield x > yield t.label > for x in inorder(t.right): > yield x > This works, but it is even easier. All you need is top-level code to handle it: def unroll(f, *a, **kw): gstack = [iter(f(*a, **kw))] while gstack: try: e = gstack[-1].next() except StopIteration: gstack.pop() else: if isinstance(e, types.GeneratorType): gstack.append(e) else: yield e def inorder(t): if t: yield inorder(t.left) yield t.label yield inorder(t.right) unroll(inorder, t) A bit more frameworky code, but it's all isolated in one place, which is much nicer than having to spread it all over the place. Jp From claird at lairds.com Fri Dec 12 10:53:18 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 12 Dec 2003 15:53:18 -0000 Subject: Python code to replace shell scripts References: Message-ID: In article , Dennis Lee Bieber wrote: . . . > (o)REXX would be a bit more transparent (though I don't think IBM >makes it free to all -- you can get an "evaluation" copy for Linux). In . . . There *are* open-source REXXs (even a mod_rexx!) which are alternatives to IBM's. Normally, at this point, I'd provide references to a couple; a combination of catastrophes seems to be afflicting my REXX-related notes, though, and I have none at hand that satisfy me. I'll cross-post to c.l.r for the benefit of those who want to pursue this. -- Cameron Laird Business: http://www.Phaseit.net From js at cis.uni-muenchen.de Wed Dec 3 07:37:31 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 03 Dec 2003 13:37:31 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com> Message-ID: "Diez B. Roggisch" writes: > The only thing you can do to avoid is is to split your disjunctions and > search separately, and afterwards takt the longest part. That could be done > using a small grammar, that allows you to detect the disjunctions and > create separate rexes for it. > > Diez Thanks for the tip. From tim.one at comcast.net Mon Dec 1 17:28:51 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 1 Dec 2003 17:28:51 -0500 Subject: sys._getframe() not behaving as expected In-Reply-To: <16331.44285.6257.338657@montanaro.dyndns.org> Message-ID: [Skip Montanaro] > sys._getframe() is acting peculiar. At least it doesn't seem to be > doing what I expect based upon a couple readings of its doc. Given > this module (call it 'gl'): > > import sys > > def printframes(): > print "frame[-2]:", id(sys._getframe(-2)) > print "frame[-1]:", id(sys._getframe(-1)) > print "frame[0]:", id(sys._getframe(0)) > print "frame[-2] globals:", id(sys._getframe(-2).f_globals) > print "frame[-1] globals:", id(sys._getframe(-1).f_globals) > print "frame[0] globals:", id(sys._getframe(0).f_globals) > print "my globals:", id(globals()) > ... An argument < 0 is treated like 0. You want to pass 2 and 1, not -2 and -1. From aahz at pythoncraft.com Tue Dec 30 23:33:38 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2003 23:33:38 -0500 Subject: Tkinter and OS X 10.3? References: <7ba1cb43.0312301205.30156acf@posting.google.com> Message-ID: In article <7ba1cb43.0312301205.30156acf at posting.google.com>, Brian Parkinson wrote: >I have tried to get Tkinter working on my Mac (OS X 10.3). I installed >MacPython 2.3 and the TclTkAquaBI-8.4.2.0.dmg. > >When I type: > >import Tkinter >r = Tkinter.Tk() > >I get a window all right, but clicking on the window causes the >following error: > >SetFrontProcess failed,-606 > >the window can't properly get focus. BTW, did you remember to use ``pythonw`` instead of ``python``? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From anton at vredegoor.doge.nl Thu Dec 4 11:45:16 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 04 Dec 2003 17:45:16 +0100 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: <3fcf6605$0$7671$3a628fcd@reader1.nntp.hccnet.nl> michael at foord.net (Fuzzyman) wrote: >Pythons internal 'pointers' system is certainly causing me a few >headaches..... When I want to copy the contents of a variable I find >it impossible to know whether I've copied the contents *or* just >created a new pointer to the original value.... > >For example I wanted to initialize a list of empty lists.... > >a=[ [], [], [], [], [] ] > >I thought there has to be a *really* easy way of doing it - after a >bit of hacking I discovered that : >a = [[]]*10 appeared to work > >however - using it in my program called bizarre crashes.... >I eventually discovered that (as a silly example) : >a = [[]]*10 >b=-1 >while b < 10: > b += 1 > a[b] = b >print a > >Produced : >[ [9], [9], [9]...... > >Which isn't at all what I intended............... >What is the correct, quick way of doing this (without using a loop and >appending...) ? Here it produced an IndexError. After changing "b < 10" into "b < 9" the code produced: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I see some other posters already gave you the answer. I'll do something different and give you the question :-) n = 4 agents = [[]]*n print agents agents[0].append('Smith') print agents neos = map(list,[[]]*n) print neos neos[0].append('Neo') print neos output is: [[], [], [], []] [['Smith'], ['Smith'], ['Smith'], ['Smith']] [[], [], [], []] [['Neo'], [], [], []] The question is: Why is "Smith" copied to all elements in the matrix? (or is that another movie :-) Anton From lupan at zamek.gda.pl Tue Dec 23 05:36:58 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Tue, 23 Dec 2003 11:36:58 +0100 Subject: linux wine py2exe ?? References: Message-ID: <87fzfb4y7p.fsf@psi.lupan.zamek.gda.pl> duikboot writes: > Hi > > > A friend of mine runs windows, and asked me to write a little script. He has no Python installed though, and istalling it, is no option. > So I really wanted to make an executable for windows. I recently done similar thing but using `McMillan installer`_ and `Inno Setup`_. The program was wxPython app with a C extension. I tried py2exe half year ago and have some problem with running it under wine, but do not remember what it was. .. _McMillan installer: http://www.mcmillan-inc.com/install1.html .. _Inno Setup: http://www.jrsoftware.org/isinfo.php -- =*= Lukasz Pankowski =*= From js at cis.uni-muenchen.de Mon Dec 8 09:21:08 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 08 Dec 2003 15:21:08 +0100 Subject: Quantify over all functions of a module References: Message-ID: Thanks. From usenet at soraia.com Sun Dec 7 12:38:58 2003 From: usenet at soraia.com (Joe Francia) Date: Sun, 07 Dec 2003 17:38:58 GMT Subject: Lists and Tuples In-Reply-To: References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: > as expected, you spent that thread attacking everyone who dis- > agreed with you, misrepresented other people's arguments, referred > to implementation artifacts and design mistakes as "proof", and used > the same muddled thinking as you've shown in this thread. So you're saying he's a news commentator for Fox News? ;>) From duncan at NOSPAMrcp.co.uk Wed Dec 3 05:12:02 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 3 Dec 2003 10:12:02 +0000 (UTC) Subject: PyMeld and PyMeldLite (was Re: Separation of content and code for web) References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> <3FCCBF61.9587D06@engcorp.com> Message-ID: Richie Hindle wrote in news:mailman.53.1070384810.16879.python-list at python.org: > Yes. `element.class = something` is an example that one PyMeld user ran > into. You need to say `setattr(element, 'class', something)`, which is > messy. For HTML generation could you also take advantage of the fact that attributes are case insensitive and do `element.Class = something`? -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From r at gnar.de Fri Dec 26 10:04:22 2003 From: r at gnar.de (Ragnar Heil) Date: 26 Dec 2003 07:04:22 -0800 Subject: Plone and Windows 2003? Message-ID: <8a70509.0312260704.4a29014b@posting.google.com> Hi, I would love to know if I can run the Plone (CMS) 1.0.5 Windows installer on win 2003. At the moment I can`t start the server. Error messages in stupid.log: "file e:\program files\plone\zope\zserver\medusa\asyncore.py line 306, ... error 10013 permission denied. also the e:\program files\plone\zope\import\examples.zexp can`t be found at this place used environment: Python 2.1.3 & Zope 2.6.1 regards Ragnar From karin.lagesen at labmed.uio.no Mon Dec 15 05:03:18 2003 From: karin.lagesen at labmed.uio.no (Karin Lagesen) Date: Mon, 15 Dec 2003 10:03:18 +0000 (UTC) Subject: dislin package Message-ID: I have a lot of data that I am going to plot and put on a web server. Since there is a lot of it, I was planning to script it all using python. I have looked around and it seems to me that dislin is good for doing the plots. However, I cannot seem to find the file/package/?? that I need to do the following statement: from dislin import * which the dislin python manual describes. Does anybody have any tips on where I can get what I need to do this? I have already installed dislin itself. Karin -- Karin Lagesen, karin.lagesen at labmed.uio.no From reply.in.the.newsgroup at my.address.is.invalid Mon Dec 8 13:15:55 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 Dec 2003 19:15:55 +0100 Subject: Class problem References: <3fd4b254$1@nntphost.cis.strath.ac.uk> <3fd4bcb5$1@nntphost.cis.strath.ac.uk> Message-ID: <2of9tvkkfjdj4s035flqv9igjcl6vpfjjn@4ax.com> Daniel Pryde: >the code's on my home hard drive Never leave home without it :-) >import ImagePyramid >pyramid = ImagePyramid(parameters) Yes, that should be: import ImagePyramid pyramid = ImagePyramid.ImagePyramid(parameters) This is explained in section 6 "Modules" of the tutorial on http://www.python.org/doc/current/tut/node8.html -- Ren? Pijlman From js at cis.uni-muenchen.de Tue Dec 2 09:18:04 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 02 Dec 2003 15:18:04 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com> <3FCC6C18.7090209@Linux.ie> Message-ID: "Fredrik Lundh" writes: > Joerg Schuster wrote: > > > I should have read your mail more carefully. You wrote about sorting > > the *re*, not about sorting the regex. Sorry. > > what's the difference? One could suspect that re.search() first matches with a greedy "|", then stores all the matches of all parts of the disjunction in the re-object and then returns the first one. J?rg From sebb at linuxcult.com Wed Dec 17 19:33:41 2003 From: sebb at linuxcult.com (sebb) Date: 17 Dec 2003 16:33:41 -0800 Subject: Learning python 2nd takes time to arrive. Message-ID: <56f42e53.0312171633.344de672@posting.google.com> Learning python second edition was first supposed to arrive at the beginning of November. But the date have been relayed many times to finally be in December. Now, we are the 17th of December and he is still not there. I wanted to have that book just in time to read it in my Christmas vacation, but I'm not sure anymore that I'll get it for this time. If someone at O'Reilly or the author of the book or anyone that know more than me on that can give me a hint of when the book will finally arrive, it would be great. I also want to know how many time it usually take for Amazon to have a book after O'Reilly published it. It's because I always buy my books with Amazon. Thanks Note : English is not my mother tongue (I'm learning it) so be kind. From paska at kios.sk Mon Dec 8 06:06:20 2003 From: paska at kios.sk (Stano Paska) Date: Mon, 08 Dec 2003 12:06:20 +0100 Subject: sorting slovak utf Message-ID: <3FD45B2C.1080107@kios.sk> Hi, I have one problem. In file aaa.txt I have slovak letters in utf-8. zcaron scaron aacute ocircumflex tcaron yacute ccaron eacute lcaron iacute dcaron uacute adiaeresis oacute lacute ncaron racute with this script (output is redirected to file bbb.txt): import fileinput riadky = [] a = fileinput.input("aaa.txt") for i in a: riadky.append(i.strip()) a.close() riadky.sort() for i in riadky: print i I have this result: aacute adiaeresis eacute iacute oacute ocircumflex uacute yacute ccaron dcaron lacute lcaron ncaron racute scaron tcaron zcaron and corrent result would be: aacute adiaeresis ccaron dcaron eacute iacute lacute lcaron ncaron oacute ocircumflex racute scaron tcaron uacute yacute zcaron I have set utf-8 in sitecustomize.py I tried: import locale locale.setlocale(locale.LC_CTYPE, 'sk_SK.utf-8') and locale.setlocale(locale.LC_CTYPE, ('sk_SK', 'utf-8')) but i got "unsupported locale" error What I must do to get correct sorting result? Stano. P.S. lower, upper works correct From kirk at strauser.com Wed Dec 31 13:45:05 2003 From: kirk at strauser.com (Kirk Strauser) Date: Wed, 31 Dec 2003 18:45:05 GMT Subject: Maybe a stupid idea References: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: <87wu8cx1xh.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2003-12-31T17:49:55Z, sebb at linuxcult.com (sebb) writes: > I thought about that because it's not very easy to program a cycle. Your example doesn't really define a cycle. What is it? A loop from start-val to end-val to start-val? >>> def cycle(a,b): ... return range(a,b)+range(b,a,-1) ... >>> cycle(0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] > Here is a simple example : > > b=0 > > while b < 50: > b+=1 > print "*" * b > > while b > 0: > b-= 1 > print "*" * b for length in cycle(0,50): print "*" * length There you go, and it didn't even take a new language structure. :) - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/8xj95sRg+Y0CpvERAmRzAJ49ZjF7tBXPrMQ8VnpeB0tvMHb5gQCeJ7cO +r9MHpgTAA9nZmdrTGBDGOo= =Apc/ -----END PGP SIGNATURE----- From jdhunter at ace.bsd.uchicago.edu Tue Dec 9 10:43:24 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 Dec 2003 09:43:24 -0600 Subject: regex confusion Message-ID: In trying to sdebug why a certain regex wasn't working like I expected it to, I came across this strange (to me) behavior. The file I am trying to match definitely contains many instances of the letter 'a', so I would expect the regex rgxPrev = re.compile('.*?a.*?') to match it the string contents of the file. But it doesn't. Here is a complete example import re, urllib rgxPrev = re.compile('.*?a.*?') url = 'http://nitace.bsd.uchicago.edu:8080/files/share/showdown_example2.html' s = urllib.urlopen(url).read() m = rgxPrev.match(s) print m print s.find('a') m is None (no match) and the s.find('a') reports an 'a' at index 48. I read the regex to mean non-greedy match of anything up to an a, followed by non-greedy match of anything following an a, which this file should match. Or am I insane? John Hunter hunter:~/python/projects/poker/data/pokerroom> uname -a Linux hunter.paradise.lost 2.4.20-8smp #1 SMP Thu Mar 13 17:45:54 EST 2003 i686 i686 i386 GNU/Linux hunter:~/python/projects/poker/data/pokerroom> python Python 2.3.2 (#1, Oct 13 2003, 11:33:15) [GCC 3.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. Welcome to rlcompleter2 0.95 for nice experiences hit multiple times From peter at engcorp.com Wed Dec 3 15:16:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Dec 2003 15:16:46 -0500 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> Message-ID: <3FCE44AE.C415D6FA@engcorp.com> "Mike C. Fletcher" wrote: > > Fredrik Lundh wrote: > > >Enrique wrote: > >>Usually major versions of python were courteus with the previous versions... > > > >0xED has never been a valid 7-bit ASCII character. > > > Sure, but Python used to accept 8-bit characters in the platform's > default encoding as part of string characters... > > Most likely Enrique has a \xED somewhere in a string literal in his code > that is intended to be an i-accent-ague. That would have worked fine in > all versions of Python before 2.3, but started failing in 2.3 due to the > decision that all string literals would be converted to unicode and back > and that the default encoding for such conversions would be ASCII > (whereas previously it would most closely have been approximated by > "platform's local 256-char encoding"). [snip] > Which doesn't actually mention the breakage of code that results. True, > theoretically the code was never valid, but *lots* of people used 8-bit > encodings quite happily with earlier versions and do find their code > breaking in 2.3 because of this. Wait a sec... are you telling me that my code, which has strings containing binary data (which I believe has *always* been permitted), and which from time to time might, say, produce an error traceback containing the content from one such string and write it to a log file, then continue processing safely, will now fail with an ugly crash because I haven't changed it to specify a default encoding? (!!!) I've been watching this "value XX with high bit set was never a valid 7-bit ASCII" discussion with only one eye for quite some time now, somewhat curious why so many people were having troubles. I assume it was merely that they were using *names* that contained non-ASCII characters, in their source code. Are you saying that this change is actually breaking code that happens to have these perfectly valid binary strings stored in string constants? I'm very unimpressed with this decision if that's the case. -Peter From mcfletch at rogers.com Sun Dec 14 09:39:09 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 14 Dec 2003 09:39:09 -0500 Subject: Is there a lib which support .jpeg file with "RGBA" mode? In-Reply-To: References: Message-ID: <3FDC760D.4000500@rogers.com> google12 wrote: >Oh, sorry. I made a mistake... > >My question is -- when I run the code described below, the transparence of >the orginal image will be removed. How can I keep the transparence? > > im = Image.open(test.png) > fp = open('test.jpg','wb') > im.save(fp,'JPEG') > > I believe the thrust of Fredrik's post was: you can't. JPEG does *not* store alpha channels. It's just not part of the format, so if you need to store in JPEG format, you will not be storing the alpha channel in the file. If what you're asking is whether you can store the alpha data to a separate file (as is done with programs such as 3DStudio Max), yes, that can be done too: >>> import Image >>> i = Image.open( r'p:\OpenGLContext\tests\wrls\simple_texturergba.png' ) >>> alpha = i.getdata( 3 ) >>> i2 = Image.new( 'L', i.size, ) >>> i2.putdata( alpha ) >>> i2.save( r'p:\OpenGLContext\tests\wrls\simple_texturea.jpg', 'jpeg' ) HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From op73418 at mail.telepac.pt Wed Dec 3 07:02:37 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 03 Dec 2003 12:02:37 +0000 Subject: Adding method to object References: Message-ID: <72krsvcpeur8hhu74s4bhlsq3bf60fu055@4ax.com> On Wed, 03 Dec 2003 10:44:12 +0100, "Thomas Guettler" wrote: >Hi! > >How can I add a method to an object. >This code does not work: > >class Foo: > def __init__(self): > self.counter=0 > >f=Foo() > >def incr(self): > self.counter+=1 > >f.incr=incr > >f.incr() > >===> python extend.py >Traceback (most recent call last): > File "extend.py", line 12, in ? > f.incr() >TypeError: incr() takes exactly 1 argument (0 given) You have to call it like f.incr(f) If you want to leave out the f as arg (call it like an instance method) then >>> import new >>> help(new.instancemethod) Help on class instancemethod in module __builtin__: class instancemethod(object) | instancemethod(function, instance, class) | | Create an instance method object. | ... And new.instancemethod(incr, f, f.__class__) Should do the trick. With my best regards, G. Rodrigues From bignose-hates-spam at and-benfinney-does-too.id.au Mon Dec 29 00:10:59 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 29 Dec 2003 16:00:59 +1050 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: On Sun, 28 Dec 2003 18:15:49 -0800, engsolnom at ipns.com wrote: > What I'd like to do is display is the instance name. Is it hiding > somewhere? What does "the instance name" mean when several names are bound to the same instance? -- \ "The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing." -- Steven Wright | _o__) | Ben Finney From max at alcyone.com Sun Dec 21 20:37:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 21 Dec 2003 17:37:29 -0800 Subject: memory overhead using from-import? References: <20031221102848.4f901801.wtrenker@shaw.ca> Message-ID: <3FE64AD9.5FA6967E@alcyone.com> William Trenker wrote: > Ah. So using the "ps" command (on Linux) to inspect the process's > virtual memory size may not show me if memory for dereferenced objects > is being freed for re-use within python's execution environment? That's correct. This is really true of any application. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ He who laughs has not yet heard the bad news. -- Bertolt Brecht From claird at lairds.com Sat Dec 20 10:48:35 2003 From: claird at lairds.com (Cameron Laird) Date: Sat, 20 Dec 2003 15:48:35 -0000 Subject: any one used googles api? References: Message-ID: In article , Bill Sneddon wrote: >Has anyone used googles API who would be will to share >a simple example. I have been wanting to play around with >SOAP for a while and this looks like a place to start. > >I am going to mess with it in ASP when our IT guys set it up >for me. > > >I like Python but have not done anything with SOAP yet. > >http://www.google.com/apis/ > Intel once published an introduction to SOAP using Google at but I haven't been able to get that site to return content lately. -- Cameron Laird Business: http://www.Phaseit.net From mwh at python.net Mon Dec 15 04:59:42 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Dec 2003 09:59:42 GMT Subject: Idle won't start References: Message-ID: kmneilso at yahoo.com (Kerry Neilson) writes: > For the past couple of months, Idle won't start when I invoke it. I > am at a complete loss for why this is. When this happens, they python > command line still starts, and python works fine otherwise. > Most interesting to me is that a reboot won't fix the problem. But if > I just try it again sometime later it will work. Anyone have any > ideas? I'm running python 2.3 on windows 2000 professional. Do you have any firewall type software? Some Windows firewalls apparently believe trying to open a socket to 127.0.0.1 is a dastardly attempt to compromise your privacy... Cheers, mwh -- If i don't understand lisp, it would be wise to not bray about how lisp is stupid or otherwise criticize, because my stupidity would be archived and open for all in the know to see. -- Xah, comp.lang.lisp From doveclaw at users.sourceforge.net Sat Dec 20 20:14:06 2003 From: doveclaw at users.sourceforge.net (Doveclaw) Date: Sat, 20 Dec 2003 20:14:06 -0500 Subject: [Fwd: RE: Is anyone using Python for .NET?] Message-ID: <1071969246.6102.5.camel@localhost.localdomain> -----Forwarded Message----- From: Mark Hammond To: 'James Tanis' Subject: RE: Is anyone using Python for .NET? Date: Sun, 21 Dec 2003 11:25:40 +1100 > Just wondering, because this discussion peaked my > interest.. but why do > you disagree.. I understand your opinion that the market right now for > this product are "average" programmer's who happily except > being dumbed > down.. but why (if you do) do you disagree with his statement > about .NET > support being advantageous to *nix. I wasn't clear. I believe it will be advantageous to *nix, but not necessarily in terms of directly reusing code originally written "for Windows". It is just that the biggest market now in Windows is for these large insurance companies writing "business logic" etc, and that I doubt any of *that* code will end up running on Linux. > I don't believe he's saying that. What I think he's saying is that > Microsoft developed it to basically make there Operating System's that > much more tasty, and advantageous.. because when developing with .NET > they will not be hindered with incompatible legacy > applications. Whether > this is true or not I do not know, I haven't yet looked into .NET as a > solution. Right - if he was simply stating "MS continue to innovate in order to continue selling OSs", I agree. Let's not forget programs like Office though too - .NET could help these products at the *expense* of their OS division, assuming things ever got good enough to run a .NET forms based app on *nix. If programs are written to .NET, the OS no longer matters. In theory of course :) Mark. -- Doveclaw http://horizon2.sourceforge.net From lbray_103 at yahoo.com Mon Dec 22 13:02:05 2003 From: lbray_103 at yahoo.com (MComp) Date: 22 Dec 2003 10:02:05 -0800 Subject: Remembering Message-ID: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Hey guys, I'm another new to programming guy. I have one quick question. How do you make a program not forget everything you input, once it shuts down? Thanks in advance. From gherron at islandtraining.com Fri Dec 5 18:25:21 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 5 Dec 2003 15:25:21 -0800 Subject: Newbie question: Any way to improve this code? In-Reply-To: References: Message-ID: <200312051525.21891.gherron@islandtraining.com> On Friday 05 December 2003 02:00 pm, Gustavo Campanelli wrote: > I'm begining to work in a program that cicles through a list of phrases > (basically, a changing signature file). I started yesterday, and I only > have abput 8 full hours of real Python experience. > > So far I produced a code that succesfully reads an process the file, > separating the phrases. Is there any way to optimize this code, so that > I don't have to use the if for the first list member? > > Now for the data. > The file is firmas.txt, it contains the following three example phrases > > Frase 1 > Frase 2 > Frase 3 > > Note that this phrases are separated by newline characters. Upon reading > the full file (it won't be long) I get this: > > 'Frase 1\nFrase 2\nFrase 3\n' > > so, as you can see, the newlines are there. > > My code is this (I know I should close the file, but so far the runtime > is so small it doesn't really matter, that'll change) > > import string > f = open("firmas.txt",'r') # open the file > texto = f.read () > ... bunch of lines deleted ... Instead of this and all the rest of the code, you can just frases = f.readlines() Then 'frases' will be a list of strings, each string containing one line from the file. If you want to see what you've got try print frases You'll see that each string contains the newline the ended the line in the file. To get rid of them and any other beginning or ending white space (if you want) do: for i in range(len(frases)): frase[i] = frase[i].strip() If your file might contain empty lines, you can get rid of them with either a standard loop final = [] for phrase in frases: if phrase: final.append(phrase.strip()) Or, if you're adventurous for a beginner, try list comprehensions. final = [phrase.strip() for phrase in frases if phrase] And finally, all this could be done in one line frases = [phrase.strip() for phrase in f.readlines() if phrase] Gary Herron From lkcl at lkcl.net Tue Dec 16 09:12:07 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 16 Dec 2003 14:12:07 +0000 Subject: rexec.py unuseable In-Reply-To: <1071581854.3fdf0a9eba3ea@mcherm.com> References: <1071581854.3fdf0a9eba3ea@mcherm.com> Message-ID: <20031216141207.GA17021@lkcl.net> On Tue, Dec 16, 2003 at 05:37:34AM -0800, Michael Chermside wrote: > Luke writes: > > i think the only really sensible way forward is to begin from a > > sound basis... > > I agree completely. > > > proposal: how about building ACLs into the python codebase? > > Actually, I rather prefer the approach that has been mentioned before > of trying to use capabilities. capabilities, acls, schmapabilities, same thiiing :) a la "cambridge capability system" [a historic architecture that provided hardware-assisted restrictions on function calls!] > See, for instance, the threads on > Capabilities found here: > http://mail.python.org/pipermail/python-dev/2003-March/thread.html#33854 > Of course, that's not trivial to add either, since some way would > need to be provided for disabling Python's powerful introspection. > > the algorithm for evaluating an acl has been worked out already, > > and implemented originally by matthew chapman of the samba team, > > so code under the GPL already exists [in an NT-like environment which > > is over-the-top]. > > Unfortunately, code under the GPL is of no use at all for Python which > is released with a more flexible (but GPL compatible) liscense. And > I'm not quite sure what you mean by an "NT-like environment" being > "over-the-top". the algorithm is there, for people to examine. i wasn't recommending that people go for complete code reuse of what is in samba (even if licenses were compatible) because the code in samba is a _complete_ reimplementation of the NT acl system _including_ recreating the internals of ACLs and their on-the-wire representation. however, there is a less low-level library which uses ACLs as "blobs", and it is the implementation of the check security access function [name i forget] which is actually a _re_implementation of the exact NT equivalent function that i recommend people to examine. > > an empty acl also means that there is no performance penalty for having > > acl code in the python codebase. > > Sorry, but I simply don't believe this. Really. Think about it a bit, > and if you still think you're right, I'll provide some reasons, but > I suspect you'll realize that it's simply not true. tiny, then. in function calling: if len(acl) == 0 or check_allowed_access(callee_function, acl, EXECUTE_CAPABILITY): proceed... and in file write, again: if len(acl) == 0 or check_allowed_access(callee_function, acl, WRITE_CAPABILITY): proceed... yes, the len(acl) == 0 checks will stack up, but not terribly significantly IMO. if an acl _does_ exist, even if it's one that grants permission to all functions/modules the ability to perform _all_ operations, _then_ you get a performance hit as the check_allowed_access() function needs to "do work". > I *DO* think though, that some amount of slow-down *IS* acceptable > (pie or no pie ) if it provided powerful new capabilities like > *reliable* restricted execution environments. ack! btw yes you're right, it's better off called "capabilities" but the name CCLs - capability control lists - is a bit of a mouthful :) btw, as a first implementation, doing "recursive" capability permissions could be avoided, by simply "copying" permissions down the object tree. as can be imagined, this is rather wasteful of both time and resources, which is why someone at microsoft came up with the concept of "apply-to-sub-object" capabilities. but remember: if all your ACLs (sorry, CCLs) are 0-length, it's not a waste of either time _or_ resources. l. From Laurent.Olivry at wanadoo.fr Mon Dec 15 08:45:53 2003 From: Laurent.Olivry at wanadoo.fr (Laurent) Date: Mon, 15 Dec 2003 14:45:53 +0100 Subject: Using readline with a new delimiter of line ? References: <3fddb97c$0$217$e4fe514c@news.xs4all.nl> Message-ID: thanks for this Laurent "remco" a ?crit dans le message de news: 3fddb97c$0$217$e4fe514c at news.xs4all.nl... > "Laurent" wrote: > > >is it possible to read a file in python line by line > >by redefining a new end-of-line delimiter ? > > > >I would like for example to have the string "END" being the new delimiter > >for each line. > > > > i couldn't find any builtin option. But of course you could always use: > > > listOfLines = file('','r').read().split('END') > > Cheers! > remco From abhjrpe at comcast.net Fri Dec 26 06:43:39 2003 From: abhjrpe at comcast.net (Aubrey Hutchison) Date: Fri, 26 Dec 2003 06:43:39 -0500 Subject: Question about functions Message-ID: Question about functions: 1)--- module "A" contains the following X = 999666 #easy to notice value Y = 111222 #easy to notice value Product = 69696969 #easy to notice value def DoSomething(): global Product,X,Y Product = X*Y return 0 module imported from A import * 2)--- toplevel code def Mult(): global Product,X,Y DoSomething(): return 0 """start of top level code """ ... ... Product =Mult() ... print Product ( Result ----> print out is 69696...) Per "Python Nutshell" this appears to be the correct result. How do you or can you modify the imported variables without using classes objects? Aubrey From pascal.parent at free.fr Mon Dec 1 11:45:04 2003 From: pascal.parent at free.fr (Pascal) Date: 1 Dec 2003 08:45:04 -0800 Subject: Extract double in binary file References: Message-ID: First thanks for trying! May be these values will tell you somethings: 1 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x81 -1 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x81 2 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x82 -2 0x0 0x0 0x0 0x0 0x0 0x0 0x80 0x82 3 0x0 0x0 0x0 0x0 0x0 0x0 0x40 0x82 -3 0x0 0x0 0x0 0x0 0x0 0x0 0xc0 0x82 1.1 0xcd 0xcc 0xcc 0xcc 0xcc 0xcc 0xc 0x81 1.2 0x9a 0x99 0x99 0x99 0x99 0x99 0x19 0x81 1.3 0x66 0x66 0x66 0x66 0x66 0x66 0x26 0x81 1.4 0x33 0x33 0x33 0x33 0x33 0x33 0x33 0x81 1.01 0x48 0xe1 0x7a 0x14 0xae 0x47 0x1 0x81 0.01 0xd7 0xa3 0x70 0x3d 0xa 0xd7 0x23 0x7a 1.02 0x8f 0xc2 0xf5 0x28 0x5c 0x8f 0x2 0x81 0.02 0xd7 0xa3 0x70 0x3d 0xa 0xd7 0x23 0x7b From torsten.rueger at hiit.fi Fri Dec 19 08:31:26 2003 From: torsten.rueger at hiit.fi (Torsten Rueger) Date: Fri, 19 Dec 2003 15:31:26 +0200 Subject: SocketServer broadcast In-Reply-To: <3FE2D68C.D7A493E1@mortauxspams.bz> References: <3FE2BC10.210AEF11@mortauxspams.bz> <3FE2D68C.D7A493E1@mortauxspams.bz> Message-ID: On Dec 19, 2003, at 12:44 PM, Olivier Hoarau wrote: > > Of course Thanks a bunch! I don't have client or servers really, just peers. So I need to have both client + server in the same process. When I do that, the client bind fails. But when I bind to '' (empty string) then it works. Maybe that helps you too (?) Anyway, it works for me now, thanks a lot Torsten From jacek.generowicz at cern.ch Wed Dec 10 11:54:50 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 17:54:50 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: "Terry Reedy" writes: > You presented an example function as taking a type (including new classes) > as parameter. If your type domain is boundedly finite It's unboundedly finite :-) > and preknowable*, you could precompute the function for *all* inputs > and replace the call with a dict lookup (or bound method for map). > > (*) If 'preknowable', could either create classes with factory function that > adds them to cache or give metaclass that does same. Hmmm ... all the non-builtin types in my domain are actually dynamically created, and are themselves instances of a metaclass, which could be instructed to add information about the new classes, to the caches, as the classes are being created. However, there are a number of problems I foresee (which I don't think are particularly interesting to discuss here). Still, it could be put to good use in some of the cases. I'll bear it in mind, thanks. But first, I think that I'll try inlining the exception handler in those cases where it can be done. Cheers, From fnord at u.washington.edu Mon Dec 22 19:08:39 2003 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 22 Dec 2003 16:08:39 -0800 Subject: Remembering References: <37c4fd7c.0312221002.1f4fe6d0@posting.google.com> Message-ID: I wrote a simple persistent dictionary class that may be of use to you. I find it quite handy. http://magicpeacefarm.com/lonnie/py/diskt.py Basically, it uses pickle to store the contents of the dictionary in a directory on the filesystem instead of in memory. Consider this example: Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from diskt import diskt >>> stuff = diskt() >>> stuff['foo'] = 'bar' ... exit Python and restart ... Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from diskt import diskt >>> stuff = diskt() >>> print stuff['foo'] bar (much lighter-weight than things like the ZODB :P) From gerson.kurz at t-online.de Thu Dec 4 13:50:28 2003 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Thu, 04 Dec 2003 18:50:28 GMT Subject: ANN: pcalc 3.0 - a Python powered MFC calculator Message-ID: <3fcf809b.12120234@news.t-online.de> pcalc.net is a freeform calculator written in C++/MFC with a Python parser powering it. (There is also an optional native C++ parser, just as a toy thrown in). If nothing else, it shows you how to integrate MFC + Python. But you can also use it as a fine calculator ;) Download: http://p-nand-q.com/python/pcalc-3.0.exe The installer includes the complete C++ and Python source. License: This is freeware, open source, whatever. Enjoy! Homepage http://p-nand-q.com/download/pcalc.html From beliavsky at aol.com Mon Dec 15 16:18:21 2003 From: beliavsky at aol.com (beliavsky at aol.com) Date: 15 Dec 2003 13:18:21 -0800 Subject: Python in a spreadsheet Message-ID: <3064b51d.0312151318.277c8c06@posting.google.com> Is it possible to call a Python function from Calc (the Open Office spreadsheet) or Microsoft Excel? Are their web sites or books describing how to do this? I would prefer not to write any more VBA :). From tjreedy at udel.edu Sun Dec 21 11:47:42 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Dec 2003 11:47:42 -0500 Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: "Carl Banks" wrote in message news:KKPEb.22919$031.11381 at fe3.columbus.rr.com... > >> DEFAULT_LIST = ((1,2),(3,4),(5,6),(7,8)) > >> def func(param=DEFAULT_LIST): > >> pass > >>The compiler couldn't optimize any of the above cases. > > > > For the DEFAULT_LIST (tuple?) and that particular dict literal, why not? > Well, the value of DEFAULT_LIST is not known a compile time To further illustrate the problem with the wished-for change, consider: DL = (1,2) def f(x=DL): print x [lots of code] DL = (3,4) f() What should this print? Currently, (1,2). To get, (3,4) instead, one can default x to None and dynamically reset x in the body to the calltime value of DL. If default expressions were evaluated at runtime, the choice of fixing the default at definition, regardless of subsequent code, would, as near as I can think of at the moment, be excluded. Terry J. Reedy From aleax at aleax.it Sat Dec 27 18:21:45 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Dec 2003 23:21:45 GMT Subject: lists with zero-valued elements References: <3c228754.0312271335.4acfe0fb@posting.google.com> Message-ID: Nick Forest wrote: > Any body knows a trivial way to enumerate a list with n zero-valued > elements? 'enumerate'...? As in, enumerate(n*[0]) ... ? Alex From pierluigi.fabbris at email.it Fri Dec 12 15:48:09 2003 From: pierluigi.fabbris at email.it (Pierluigi Fabbris) Date: 12 Dec 2003 12:48:09 -0800 Subject: Curses and Events and Other Message-ID: I'm a python programmer since three month and I need that you help me. I want to use python in my web site and in particular I want to add to a ref in Html a event. The event is the getmouse of curses. In this way I want to admin the click of the ref to start the function startfile() to open every files (*.pdf, *.word) with the current application. In my editor Python 2.2 that I download in www.python.it I've not the curses. I've looked to used the module console that I install (www.python.it for reference), but it does't exist. I've a computer in Windows, but my program have to start in a computer in Linux. In few word I want (for example) to click in html page and open the file with the application. I've a another questions: Why if the is a large block it don't incremate, and I've use a function to bypass the problem? Tanks for the help From knoppix at laptop.home.net Mon Dec 29 18:04:25 2003 From: knoppix at laptop.home.net (Knoppix User) Date: Mon, 29 Dec 2003 17:04:25 -0600 Subject: Confused Newbie - wxImage vs WxImage pointer References:

    Message-ID: On Mon, 29 Dec 2003 14:26:07 -0500, Mel Wilson wrote: > It's a good place to go. In the meantime, the immediate > error is probably that you wanted to say `img.Scale`. Yeah, but that's not the half of it :-( I received this very helpful reply on the wxPython-users list. The main problem is that bitmaps don't have a scale method. See below for more details. Thanks for your input, Mel. Steve From: Markus Meyer To: wxPython-users at lists.wxwindows.org Subject: Re: [wxPython-users] Resizing wxImage Date: Mon, 29 Dec 2003 16:39:13 +0100 Steve, note that you're converting the image to a bitmap (via ConvertToBitmap). Bitmaps don't have a scale method. wxImage has a scale method, but it has an uppercase letter at the beginning. You could use something like this: img = wxImage(jpgName,wxBITMAP_TYPE_JPEG) imgSmall = img.Scale(100, 100) wxStaticBitmap(self, -1,wxBitmapFromImage(imgSmall)) From dyoo at hkn.eecs.berkeley.edu Thu Dec 11 13:35:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 11 Dec 2003 18:35:15 +0000 (UTC) Subject: ANN: BayPIGies meeting for Thursday, December 11, 2003 Message-ID: (My apologies for the late announcement!) When: Thursday, December 11, 2003 Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: pyNMS features Speaker: Keith Dart About the talk Keith Dart will talk about pyNMS, a project he has hosted on SourceForge. pyNMS allows one to develop network management applications. There will be discussion of the project, as well as discussion about a distributed Python software repository (ala CPAN or Gentoo). For driving directions to Carnegie, as well as information about BayPIGgies, please visit: http://www.baypiggies.net From claird at lairds.com Mon Dec 22 21:40:49 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Dec 2003 02:40:49 -0000 Subject: Singleton process References: Message-ID: In article , Andrew Bennetts wrote: . . . >mkdir has the advantage of being fairly simple, although it does feel a bit >hackish, because that's not what directories are meant to be used for. > >Slightly cleaner would be to use os.open with the O_CREAT and O_EXCL flags, >I think. I'm not sure what the portability of those flags is, though -- >whereas creating directories is supported on most platforms I can think of >:) > >> Here's how I think about this: what does the OS itself manage >> as a process-referring singleton? Socket service! Only one >> server can be on a port at a time; that's exactly the expressed >> requirement. > >Sure, but the OS also ensures that only one file/directory can be at a >particular path at any given time, so that's fine too. Sockets do have the >advantage of being automatically cleaned up when the process exits -- sort >of. SO_REUSEADDR is probably good enough to get the behaviour you'd want, >though. . . . Right: OSs certainly handle filesystems, but there's no "cleanup", as with sockets. Also, while O_EXCL and friends are supposed to be portable, there are a lot of subtleties to them--and even outright errors, when NFS is involved. -- Cameron Laird Business: http://www.Phaseit.net From tismer at tismer.com Wed Dec 24 08:53:42 2003 From: tismer at tismer.com (Christian Tismer) Date: Wed, 24 Dec 2003 14:53:42 +0100 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha In-Reply-To: References: Message-ID: <3FE99A66.30804@tismer.com> A.M. Kuchling wrote: ... > Sheesh, Aaron announces a database system that looks really spiffy from the > examples, like ZODB without the pain of ExtensionClass, and the first two > responses are griping about one aspect of it. Sometimes folks don't know > when they're well-off. (Now if only he'd released it before I wrote the > PyCon proposal tracker using PostgreSQL...) Yes, too bad. By that, Stackless would sit in the PyCon proposal tracker. (and I want to have it everywhere) happy Xmas -- chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From http Sat Dec 13 20:48:42 2003 From: http (Paul Rubin) Date: 13 Dec 2003 17:48:42 -0800 Subject: Examples and Tutorials of SocketServer? References: <826b6ec2.0312131313.10769cda@posting.google.com> <7xiskkjtub.fsf@ruckus.brouhaha.com> Message-ID: <7xvfokxj7p.fsf@ruckus.brouhaha.com> "John E. Barham" writes: > But at some point you should read and try to trace the source to > SocketServer. Really, it's not that complicated. It's actually pretty educational to see how such things are written. The way the threading and forking mixins work is quite elegant. From fredrik at pythonware.com Sun Dec 7 15:03:22 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 21:03:22 +0100 Subject: finding files that have extensions References: <93f5c5e9.0312071154.4e7a1311@posting.google.com> Message-ID: "hokiegal99" wrote: > The problem I'm having is that as I add more and more file types to > the script I have to define more and more 'xxx_skip' variables. My > 'if' conditionals are growing larger and larger. Which leads to my > question: How could I define it so that *any* file that already has a > '.xxx' extension (where x = 'abcdefghijklmnopqrstuvwxyz' upper and > lowercase) would be excluded from the rename? I've considered > something like this: > > ext = re.compile('[abcdefghijklmnopqrstuvwxyz]', re.IGNORECASE) > > But I don't know how to pull 'ext' into something like this: > > ext_skip = string.find(fname,'.xxx') > > Any ideas? os.path.splitext(fname) splits a filename into prefix and extension parts: >>> os.path.splitext("hello") ('hello', '') >>> os.path.splitext("hello.doc") ('hello', '.doc') >>> os.path.splitext("hello.DOC") ('hello', '.DOC') >>> os.path.splitext("hello.foo") ('hello', '.foo') in other words, "if not os.path.splitext(fname)[1]" might be what you want. or more readable: for fname in files: name, ext = os.path.splitext(fname) if ext: continue # ... figure out the new name and rename it ... From mysoso282 at yahoo.com.cn Mon Dec 29 11:06:24 2003 From: mysoso282 at yahoo.com.cn (soso) Date: 29 Dec 2003 08:06:24 -0800 Subject: Hi,can i ask some question about zope? Message-ID: <1efebde.0312290806.130b9821@posting.google.com> Hi,can i ask some question about zope here? From claird at lairds.com Mon Dec 15 19:35:02 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 16 Dec 2003 00:35:02 -0000 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: >Matthew Sims wrote: > >> Is there anyway to assign to an element that wasn't defined in the >> beginning? Like if I wanted element 5 assigned but not element 4 >> without using "" or None? > >You can write your own class: > >class GrowingList(list): > def __init__(self, seq, default=None): > list.__init__(self, seq) > self.default = default > def __setitem__(self, index, value): > if index >= len(self): > self.extend([self.default]*(index - len(self))) > self.append(value) > else: > list.__setitem__(self, index, value) > > >g = GrowingList(["alpha", "beta", "gamma"]) >g[7] = "omega" >print g > >This is a partial implementation, only g[index] = value will work. > >> I'm currently re-writing a Perl script into Python and with Perl I was >> free to assign any element in the array without having to fill in the >> previous elements. I can't seem to do that in Python...unless I'm >> doing it wrong. > >As already pointed out, a mechanical translation will yield substandard >results. As you did not describe the problem you are solving with the >"autogrowing" list, there is little chance for us to come up with a better >or at least more idiomatic approach. . . . We've probably convinced Mr. Sims that Python (and object-oriented programming) is really, really hard, particularly compared to Perl: we have to write hairy Class definitions just to do the simplest things. I think there's a fair probability this is all a misunderstanding, and that what Mr. Sims truly wants, although he doesn't realize it, is simply a dictionary, rather than a list. Mr. Sims, how would you feel if I said you should be using a Perl "hash" rather than an "array"? -- Cameron Laird Business: http://www.Phaseit.net From exarkun at intarweb.us Wed Dec 17 19:25:42 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 17 Dec 2003 19:25:42 -0500 Subject: Using python with SSH? In-Reply-To: <8765gf82kk.fsf@mobile.foo> References: <3fe0dfd7$1@clarion.carno.net.au> <8765gf82kk.fsf@mobile.foo> Message-ID: <20031218002542.GA6259@intarweb.us> On Thu, Dec 18, 2003 at 12:08:43AM +0100, Lawrence Oluyede wrote: > Steve writes: > > > ssh -l user host "/path/to/program" > > > > prompts for a password and I don't know how to supply one via a python > > script. Is there an easy way out? Can I log onto to the other machine via > > ssh somehow? Does a python script support this? Thanks! > You could open ssh in a pty, or you could use a Python module that speaks the SSH protocol, thus obviating the requirement to call out to the ssh command line program. A couple choices for such modules: http:/www.twistedmatrix.com/ http://www.lag.net/~robey/secsh/ > Try something like this: > > import os > > ssh_pipe = os.popen("ssh -l user path") > ssh_pipe.write(password) > ssh_pipe.write("\n") > ssh_pipe.flush() > ssh_pipe.close() > > hope this helps It does not. ssh won't accept a password from standard input, it requires it to be entered into the terminal. Jp From shaleh at speakeasy.net Wed Dec 24 15:19:58 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed, 24 Dec 2003 12:19:58 -0800 Subject: Using Python to send a DNS update packet In-Reply-To: References: Message-ID: <200312241219.59126.shaleh@speakeasy.net> On Wednesday 24 December 2003 10:29, Matt Whiteley wrote: > Hello all, > > I want to use Python to send a request to a Microsft DNS server to tell it > to update an A record. Ideally, this would be a secure update but > primarily, an unsecure one would do. Are there any python modules that will > let me do it or is there some code knocking around I could use ? > > Thanks > Matt twisted is a project to give easy networking support to python. Should get you up and running pretty quickly. From aahz at pythoncraft.com Sun Dec 7 15:02:05 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2003 15:02:05 -0500 Subject: New inited instance of class? References: Message-ID: In article , Francis Avila wrote: >Aahz wrote in message ... >> >>So please stop telling people to avoid classic classes. > >Someone better tell Alex Martelli, too, because IIRC he is far more >gung-ho on using new-style classes absolutely everywhere than I am. I >believe he said the only time he uses them is when he forgets to type >(object), which is about where I'm at. There's a big difference between being gung-ho on new-style classes and telling people to stop using old-style classes. There's also a big difference between saying, "I never use classic classes," and, "You should avoid classic classes." I'll admit that Alex posts enough that I don't read everything he says, but I don't recall him going as far as you do -- and I'd be rather shocked if he did because he almost always appropriately qualifies his advice. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From adalke at mindspring.com Wed Dec 31 14:00:34 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 31 Dec 2003 19:00:34 GMT Subject: Project dream References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> <7xllotv8kq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > There could be a wiki page somewhere with a list of interesting > project suggestions. I'd put stuff there. I can think of all kinds > of cool programs that I'd like for other people to write ;-). Well, isn't that the problem? I can think of quite a few as well. (Again, all chemical and bio- informatics related.) But from experience the odds of anyone else working on them is very low and the effort spent on putting those ideas on a wiki, knowing that it's almost certainly going to be ignored, makes it simply not worth it. Now, if you said "I'm going to work on all kinds of cool programs that others suggested" then that's something different. Even then, you're going to work on things you are interested in, which is only a small number of the projects in the world that others consider interesting. Andrew dalke at dalkescientific.com From __peter__ at web.de Sat Dec 6 07:52:56 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Dec 2003 13:52:56 +0100 Subject: Moving around in a string References: <5Oidnel4EckPJUyiRVn-hA@sysmatrix.net> Message-ID: Mark Engle wrote: > I'm also new to Python, but I think I can point you in the right > direction. Look into split() in library documentation. > > http://www.python.org/doc/current/lib/module-string.html > One caveat (only for the string module), quoting from the above document, but easily overlooked: "Many of the functions provided by this module are also defined as methods of string and Unicode objects; see ``String Methods'' (section 2.2.6) for more information on those." So whenever you're tempted to write string.somefunc(s, moreargs), rather use s.somefunc(moreargs). Peter From purely at unadulterated.nonsense Wed Dec 24 03:09:31 2003 From: purely at unadulterated.nonsense (Moosebumps) Date: Wed, 24 Dec 2003 08:09:31 GMT Subject: "literal" objects Message-ID: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> I've googled all over for this but can't find an answer... I'm fairly new to Python, and wondering if you can just list a bunch of objects as data. For example, in C you would just do something like this: struct { int a; float b; } mystruct; mystruct x = { 3, 5.0f }; mystruct y = { 5, 15.0f }; These are just "data". Obviously in python you could just write an init function like this: x.a = 3; x.b = 5; y.a = 5; y.b = 15; And that would work fine, but the programmer in me says that that's a pretty inelegant way to do it. Why execute code when all you need is to put data in the program? A thought that occured to me is that classes are implemented as dictionaries (correct?). So you could have a dictionary like this: x = {'a': 3, 'b': 5} y = {'a': 5, 'b': 15} This would be the __dict__ attribute of an object I suppose. But I don't see anyway to assign it to a variable so you could access them like x.a and y.a. I don't know if this would be a "nice" way to do it or not. Question 2: If "subfolder" is a folder under "basefolder", and basefolder contains "base.py", and subfolder contains "sub.py", how do I import sub.py into base.py? From what I can tell so far it only works if the files are in the same directory. I need to be able to do this without modifying any environment variables or anything. Because the scripts will be run on many different machines and I have no way of automatically configuring them. thanks, MB From newsgroups at jhrothjr.com Wed Dec 17 21:41:16 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 17 Dec 2003 21:41:16 -0500 Subject: tuples and cartesian coordinates References: Message-ID: "Gerrit Holl" wrote in message news:mailman.262.1071692390.9307.python-list at python.org... > Hi, > > the FAQ says: > > > For example, a Cartesian coordinate is appropriately represented as a > > tuple of two or three numbers. > > I find it strange to use tuples for a coordinate. After all, a > coordinate represents a position of an object. Suppose I have a game > where the player has a position: isn't it stupid to use tuples rather > than lists or another type (maybe complex numbers?), because I want to > be able to change the position? > > Shouldn't coordinates be mutable? I would think not. I look at them as Value Objects: that is, objects which serve to encapsulate a value and which don't have any identity outside of that function. So if you're not going to create an object for them, I'd regard a tuple as perfectly adequate. John Roth > > yours, > Gerrit. > > -- > 231. If it kill a slave of the owner, then he shall pay slave for slave > to the owner of the house. > -- 1780 BC, Hammurabi, Code of Law > -- > Asperger's Syndrome - a personal approach: > http://people.nl.linux.org/~gerrit/english/ > From mwilson at the-wire.com Mon Dec 29 14:26:07 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 29 Dec 2003 14:26:07 -0500 Subject: Confused Newbie - wxImage vs WxImage pointer References: Message-ID:

    In article , Knoppix User wrote: >On Mon, 29 Dec 2003 12:31:42 +0000, Tom wrote: > >> wxPython is a wrapper around wxWindows. The wxBitmapPtr is a handle to >> the C++ object that is the actual object holding the bitmap. >> >> Badly explained but that's basically it (For wxPython questions you >> should try the wxPython mailing list). > >Thanks, Tom. I'll take wxQuestions to the wxPython list - duh, sorry! It's a good place to go. In the meantime, the immediate error is probably that you wanted to say `img.Scale`. Regards. Mel. From spiffy at worldnet.att.net Tue Dec 9 03:38:18 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 08:38:18 GMT Subject: running non-python progs from python References: Message-ID: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> "Michel Claveau/Hamster" wrote in message news:br3t6s$44i$1 at news-reader2.wanadoo.fr... > Hi ! > > You can also do (sample) : > > import os > vret = os.popen('c:\\pfiles\\lplayer.exe') > print vret > > > > @+ > -- > Michel Claveau Hello Michel, thanks for taking the time to respond. Unfortunately, when I tried to run your sample code (changing the name of the file, of course), it did nothing. > How can I run this other program from a python script and pass the filename > as a parameter? import os filename = "myfile" os.system("program %s" % filename) Fredrik, the example you provided is virtually the same as the one from the "Learning Python" book. When I run it, the dos command line appears with the message 'Bad command or file name". Both the .exe and the .mid file are in the python path and the spelling has been checked. What I expected to happen was that the os.system call would start the .exe and begin playing the .mid file. This does not happen. This is what I meant when I said I haven't been able to get this to work. >"it doesn't work" is a really lousy way to describe a >problem what did you >do, what happened, and what did you expect would >happen instead? > >also see: > > http://www.catb.org/~esr/faqs/smartquestions.html#intro > Pardon me for being a newbie, but if you don't have an answer, why do you have to give me attitude? From try_vanevery_at_mycompanyname at yahoo.com Tue Dec 16 22:33:31 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Tue, 16 Dec 2003 19:33:31 -0800 Subject: Is anyone using Python for .NET? References: Message-ID: "Brian Quinlan" wrote in message news:mailman.231.1071616276.9307.python-list at python.org... > > Is anyone using Python for .NET? I mean Brian's version at Zope, > > I'm using it. For what sort of project? -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From eddiembabaali at yahoo.com Wed Dec 17 11:08:41 2003 From: eddiembabaali at yahoo.com (CodeGuru73) Date: 17 Dec 2003 08:08:41 -0800 Subject: Parsing an HTML file Message-ID: <5e290f27.0312170808.4590723e@posting.google.com> I am trying to find the best way to parse a bunch of html files. They are all simillar in structure and I need to get them into a database. Their relevant structure is:

    title

    authors
    Main html content
    I basically need to get the values between

    ,
    and
    I am able to read the the files into an array. From martin at v.loewis.de Mon Dec 29 05:50:35 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 29 Dec 2003 11:50:35 +0100 Subject: Python deutsch In-Reply-To: References: Message-ID: <3FF006FB.40505@v.loewis.de> Werner.Warweg wrote: > - welche deutschen B?cher? Falls Du noch eine Kopie davon erh?lst :-) v. L?wis, Fischbeck: Python 2. Addison-Wesley, 2001. Ansonsten gibt es eine B?cherliste auf http://www.python.org/cgi-bin/moinmoin/GermanPythonBooks > - welche Newsgroup ist die beste? Ich finde die Mailing-Liste am besten: http://starship.python.net/mailman/listinfo/python-de Ciao, Martin From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon Dec 8 17:13:45 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 8 Dec 2003 23:13:45 +0100 Subject: [wxPython] Managing Skin engines References: Message-ID: Hi The WMP's skins are in XML. It's perhaps more easy to look in XML side ? Michel Claveau. From jzgoda at gazeta.usun.pl Mon Dec 29 17:14:01 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 29 Dec 2003 22:14:01 +0000 (UTC) Subject: indendation question References: Message-ID: Robin Munn pisze: > And if someone else is *editing* the same file as you, it will make > matters even worse, because they're likely to be using spaces for > indentation. So you've indented something with one tab, which on their > screen looks like 8 spaces. They add a line at what they believe to be > the same level of indentation: 8 spaces. Then you look at the file and > see their line as being one step more indented than yours. Now try to > guess what Python will do with that file. That's why I have set all my editors (UltraEdit, Vim, Kate) to convert tabs to spaces (1:4) on opening any file. Sometimes this leads to intendation errors on startup, but having only spaces in files this error is easy to trace. -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda-a-chrome.pl http://zgoda.jogger.pl/ From jsbenson at bensonsystems.com Sun Dec 14 01:39:29 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 13 Dec 2003 22:39:29 -0800 Subject: continue and break frustration Message-ID: <01ac01c3c20d$08a4d750$210110ac@jsbwxp3> In reply to Message: 14 Date: Sun, 14 Dec 2003 16:37:09 +1100 From: Glen Wheeler Subject: continue and break frustration To: python-list at python.org Message-ID: Content-Type: text/plain; charset=us-ascii Hello All. I've been coding in python for a reasonable amount of time now (coding in total for approx. 20 years) and am writing a performance intensive program in python. The problem I'm having is I want to use break and continue to get out from more than one level of loop. If I set a variable and then check it my program will take too much of a performance hit. Are there any alternatives people can think of? Thanks, Glen How about raising an exception that can't be caught inside the try:...except:... you want to catch it? (Note: this rules out catchall except:s inside.) From anthony at python.org Fri Dec 5 09:40:53 2003 From: anthony at python.org (Anthony Baxter) Date: Sat, 06 Dec 2003 01:40:53 +1100 Subject: RELEASED Python 2.3.3 (release candidate 1) Message-ID: <200312051440.hB5Eer1P009275@maxim.off.ekorp.com> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.3 (release candidate 1). Python 2.3.3 is a bug-fix release of Python 2.3. A couple of serious bugs related to weakrefs and the cyclic garbage collector have been fixed, along with a number of bugs in the standard library. See the release notes on the web page for more details. For more information on Python 2.3.3c1, including download links for various platforms, release notes, and known issues, please see http://www.python.org/2.3.3 Highlights of this new release include: - A couple of serious bugs in the interactions of weakrefs and cyclic GC have been squashed. - At shutdown, the second call to the cyclic garbage collector has been removed. This caused more problems than it solved. - The xml.parsers.expat module now provides Expat 1.95.7. - urllib2's HTTP Digest Auth support works again. - See http://www.python.org/2.3.3/NEWS.html for other bugfixes. Highlights of the previous major Python release (2.3) are available from the Python 2.3 page, at http://www.python.org/2.3/highlights.html A final version of Python 2.3.3 should follow in a couple of weeks, just in time for your Christmas stockings. Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python 2.3.x Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 234 bytes Desc: not available URL: From km at mrna.tn.nic.in Sun Dec 28 11:32:07 2003 From: km at mrna.tn.nic.in (km) Date: Sun, 28 Dec 2003 22:02:07 +0530 Subject: pointers Message-ID: <20031228163207.GA32601@mrna.tn.nic.in> Hi all, may i know if there is any plans of introducing the concept of pointers into python language as in C ? (atleast in future versions ?) regards, thanks KM From __peter__ at web.de Tue Dec 23 04:07:25 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Dec 2003 10:07:25 +0100 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> Message-ID: John J. Lee wrote: > How do people name their iterator methods / functions? > > eg. .iter_foo(), .foo_iter(), .iterfoo(), .fooiter(), .foos(), ...? > > Of course, dicts have .iterkeys(), .itervalues() and .iteritems(), but > I don't like having words run together like that. My personal naming convention is not yet stable, but I currently favour foos(). I think iterkeys() etc. were only introduced because there already were methods like keys() returning the corresponding list. These I now tend to omit and instead make it explicit when I need a list, e. g. alltags = list(parser.tags()) and instead of parser.filtertags(pred): sometags = [t for t in parser.tags() if pred(t)] When all returned sequences are iterators, a special prefix/suffix seems pointless and you may wonder how to name the few exceptions: list_foo(), foo_list(), listfoo(), foolist(), foos(), ... :-) Peter From http Fri Dec 19 23:05:20 2003 From: http (Paul Rubin) Date: 19 Dec 2003 20:05:20 -0800 Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: <7xekv0b0cf.fsf@ruckus.brouhaha.com> Carl Banks writes: > The only thing is, I very much doubt I'd be willing to take the > performance hit for it. If you don't like performance hits, you're using the wrong language :). Seriously, this hasn't been an issue in Common Lisp, which in general pays far more attention to performance issues than Python ever has. From gte181u at prism.gatech.edu Tue Dec 9 19:09:38 2003 From: gte181u at prism.gatech.edu (Vams) Date: Tue, 09 Dec 2003 19:09:38 -0500 Subject: Pygtk, libglade Message-ID: Hi everyone, I got a little problem that I hope someone can help me out w/ or atleast point me in the right direction. Situation: - I have a python program that continuously runs and does some tasks automatically on a daily basis. - Now, I want to create a gtk frontend that displays its status and provides an exit button so I don't need to keep sending the daemon a kill signal. What I wanted to do: - make a class that creates the GUI using libglade and pygtk. - create the GUI using the outside class and make a function within my main program that continuously updates the GUI instance when called on. Problem: ---------- gtk.main() ------------- The GUI won't show up w/o calling this function. And if I do call this function, the control of my program will stay in the mainloop until it exists (GUI closes). This stops the daemon from doing what it normally does. So, what do I need to do? Should I have the gtk.main() in its own thread or something? Or can I somehow extend the gtk.main() so that it does my program's tasks while keeping an eye on the GUI? Any help would be appreciated. Thank you, Vams From 9974331 at cvm.qc.ca Wed Dec 31 09:00:12 2003 From: 9974331 at cvm.qc.ca (Askari) Date: Wed, 31 Dec 2003 14:00:12 GMT Subject: Try except - bug? References: <104c369a.0312300851.4f23759e@posting.google.com> <1ne3vvobhp2u6mqar4khk84h64hcmu8h1o@4ax.com> <104c369a.0312301901.3e4f8207@posting.google.com> Message-ID: Rene Pijlman wrote in news:gg95vvs4ni6poiht2siml0htcg9qo73j91 at 4ax.com: > Askari: >>OSError: [Errno 2] No such file or directory: '' > > If I'm not mistaken this is another exception!? > >>at line 355 you have : "fileDest.close()" > > No, line 355 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: > > > #afficher confirmation > >>and at line 363 you have : "os.remove(destination)" > > No, line 363 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: > > pass > >>What is your version of python? (I have 2.3.2) > > I use UltraEdit 8.0 on Windows XP to count the line numbers. > Batheme! I didn't know that the exception rest in memory after a "catch". Finaly, it's my mistake with use of "sys.exc_info()" at line 368. But for # of line; check your ultraedit. Are you sure that the line 1 is "#! d:/python23/python" ? From bokr at oz.net Thu Dec 18 14:21:57 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Dec 2003 19:21:57 GMT Subject: Beginner question - How to effectively pass a large list References: <3fde309f$0$19285$626a54ce@news.free.fr> <3fe0a2f6.852386076@news.blueyonder.co.uk> Message-ID: On Wed, 17 Dec 2003 18:46:10 GMT, alan.gauld at btinternet.com (Alan Gauld) wrote: >On Tue, 16 Dec 2003 16:21:00 +0800, "J.R." >wrote: >> Actually, the python is passing the identity (i.e. memory address) of each >> parameter, and it will bind to a local name within the function. >> >> Right? Depends on what you mean by "python" ;-) Python the language doesn't pass memory addresses, but an implementation of Python might very well. The distinction is important, or implementation features will be misconstrued as language features. I suspect Alan is trying to steer you away from discussing implementation. I think it can be useful to talk about both, if the discussion can be plain about which it is talking about. > >Nope. IMO that is a little too dismissive ;-) >This is one case where understanding something of the insides of >Python helps. Basically Python variables are dictionary entries. >The variable values are the the dictionary values associated with >the variable names which are the dictionary keys. > >Thus when you pass an argument to a function you are passing a >dictionary key. When the function uses the argument it looks up >the dictionary and uses the value found there. That's either plain wrong or mighty misleading. IOW this glosses over (not to say mangles) some important details, and not just of the implementation. E.g., when you write foo(bar) you are not passing a "key" (bar) to foo. Yes, foo will get access to the object indicated by bar by looking in _a_ "dictionary". But when foo accesses bar, it will be using as "key" the parameter name specified in the parameter list of the foo definition, which will be found in _another_ "dictionary", i.e., the one defining the local namespace of foo. I.e., if foo is def foo(x): return 2*x and we call foo thus bar = 123 print foo(bar) What happens is that 'bar' is a key in the global (or enclosing) scope and 'x' is a key in foo's local scope. Thus foo never sees 'bar', it sees 'x'. It is the job of the function-calling implementation to bind parameter name x to the same thing as the specified arg name (bar here) is bound to, before the first line in foo is executed. You could write globals()['bar'] = 123 print foo(globals['bar']) and def foo(x): return locals()['x']*2 to get the flavor of what's happening. Functions would be little more than global-access macros if it were not for the dynamic of binding local function parameter names to the call-time args. > >This applies to all sorts of things in Python including modules - >a local dictionary associated with the module, and classes - >another dictionary. Dictionaries are fundamental to how Python >works and memory addresses per se play no part in the procedings. Well, ISTM that is contrasting implementation and semantics. IOW, memory addresses may (and very likely do) or may not play a part in the implementation, but Python the language is not concerned with that for its _definition_ (though of course implementers and users are concerned about _implementation_ for performance reasons). I think the concept of name space is more abstract and more helpful in encompassing the various ways of finding objects by name that python implements. E.g., when you interactively type dir(some_object), you will get a list of key names, but typically not from one single dictionary. There is potentially a complex graph of "dictionaries" to search according to specific rules defining order for the name in question. Thus one could speak of the whole collection of visible names in that process as a (complex) name space, or one could speak of a particular dict as implementing a (simple) name space. HTH Regards, Bengt Richter From claird at lairds.com Thu Dec 4 10:53:04 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Dec 2003 15:53:04 -0000 Subject: Hopelessly Lost And Desperate Newbie References: <20031204092605.01786.00000161@mb-m20.aol.com> <3FCF4732.475184A1@engcorp.com> Message-ID: In article <3FCF4732.475184A1 at engcorp.com>, Peter Hansen wrote: . . . >This sounds far too much like homework for me to want to give any direct >answer, but even if it's not homework, you really ought to do a few things >to get better responses here. > >One is to make at least a token effort to solve the problem yourself, and then >if you can't quite figure it out, post a snippet of your "best effort" to >show that you are actually trying. Nobody wants to help someone who doesn't >try. (Not entirely true, actually, since in this newsgroup there'll always be >someone who does help anyway. :-) You mean, by pointing out that Python-coded solutions to generalizations of this problem have already been posted publicly? It might well be easier for Afgncaap5 to create his or her own, than to track down where those are. > >Secondly, explain exactly what is giving you trouble. Is it a particular . . . >Thirdly, while the problem description seems clear enough, it really seems >like either a homework problem or perhaps an attempt to create more spam >support tools... either of which should scare off most people from giving you >the answer on a silver platter. At least try to explain why you are "desperate" As usual, Peter's level-headed follow-up merits reiter- ation. My own comment: in honor of Dijkstra, I'll propose that computing is unique in the breadth of con- ditions which supplicants believe "I'm having a little trouble" covers. . . . -- Cameron Laird Business: http://www.Phaseit.net From none at none.net Mon Dec 22 12:23:51 2003 From: none at none.net (Iwan van der Kleyn) Date: Mon, 22 Dec 2003 18:23:51 +0100 Subject: manpage of python 2.3? In-Reply-To: References: <3fe63429$0$242$e4fe514c@news.xs4all.nl> Message-ID: <3FE728A7.7030608@none.net> > so, is there a real manpage for python2.3. around? Python doesn't come with extensive man pages like for example Perl (man perintro etc). On Debian Linux there's a rather rudementary man page, showing possible command line options. http://www.die.net/doc/linux/man/man1/python.1.html Of course, you could use links/lynx to view Python's excellent html documentation from the console. Regards, Iwan From pmaupin at speakeasy.net Mon Dec 8 22:10:07 2003 From: pmaupin at speakeasy.net (Patrick Maupin) Date: 8 Dec 2003 19:10:07 -0800 Subject: __slots__ References: <9d5f9ae4.0311070836.7503de86@posting.google.com> <9d5f9ae4.0311100749.362e8cdf@posting.google.com> <653b7547.0311112052.4a7f9b3d@posting.google.com> Message-ID: <653b7547.0312081910.4271652@posting.google.com> Mirko Zeibig wrote: > So while there is a big memory saving in using __slots__, the time savings I > observed are relatively small. Test system is a Pentium Celeron 500MHz with 256 > MB running the Python 2.2 on Linux. Of course never trust measurements you > didn't manipulate yourself ;-). Always excellent advice, which I usually attempt to follow. I think I tried to make it fairly clear in the post you were responding to that __slots__ would not always give great results. However, some empirical evidence I have (aka measurements I manipulated myself :) shows that in _some_ cases the time savings can be substantial. In the cases I have seen, the time savings actually follow the memory savings. In other words, if __slots__ can make the difference between paging or not, or even, possibly, lots of RAM cache misses or not, then it could be worthwhile. (As your detailed post makes clear, saving 70% of the RAM by using __slots__ on simple objects is not out of the question, although I do find it somewhat surprising that on your small objects the __slots__ requirement was even smaller than a tuple!) Also, if I am not misremembering (it was quite a few months back), I think the speed benefit was more pronounced in 2.3 than in 2.2, so maybe there are some additional interpreter optimizations there. FWIW, my use case for __slots__ involved creating at least tens of millions of objects, and I was not exaggerating when I wrote that I was on the way to writing a C extension (in Pyrex). Regards, Pat From jjl at pobox.com Fri Dec 19 08:58:59 2003 From: jjl at pobox.com (John J. Lee) Date: 19 Dec 2003 13:58:59 +0000 Subject: pymozilla ([Python-Dev] RELEASED Python 2.3.3 (release candidate 1) - custom Py_Initialize()) References: Message-ID: <87fzfgoqn0.fsf@pobox.com> JZ writes: > On Fri, 19 Dec 2003 04:30:53 +0100, "Wiktor Sadowski" > wrote: > > >The main problem was to have it run from CD (client requirement) without > >installing anything (Mozilla/Python) > > I had the same problem. I solved it using Webware and SQLite. What's the problem? Does Python not like having nowhere to save .pyc files? John From bignose-hates-spam at and-benfinney-does-too.id.au Mon Dec 1 08:06:56 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 1 Dec 2003 23:56:56 +1050 Subject: test References: <20031201090552.70291edb.agg@astranet.ru> Message-ID: On Mon, 1 Dec 2003 09:05:52 +0300, Damir Hakimov wrote: > test, pls ignore alt.test newsgroup, please use -- \ "One thing vampire children have to be taught early on is, | `\ don't run with a wooden stake." -- Jack Handey | _o__) | Ben Finney From list-python at ccraig.org Fri Dec 5 12:13:36 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 05 Dec 2003 12:13:36 -0500 Subject: Threading - Why Not Lock Objects Rather than lock the interpreter References: <8089854e.0312050632.72cbfb44@posting.google.com> Message-ID: michael at foord.net (Fuzzyman) writes: > Looking at threading code it seems that the Global Interpreter Lock is > a bit of a 'brute force' way of preventing two threads attempting to > access sensitive objects simultaneously.... > > Why not have a new type of object with a 'lock' facility... if an > object is locked then any thread trying to access the object other > than the one obtaining the lock is blocked until the lock is > released..... rather than blocking *all* threads until one thread has > finished with the object..... > > It could be implemented as a new attribute of existing objects... or > new types of objects..... It would slow down the interpreter drastically. The important thing here is that for the above to be true, you'ld need to define "sensitive objects" to be "objects with a reference count" (i.e. all of them). Because of that if you did this you'ld be doing about as much locking and unlocking as you would code execution. For example, calling the following function would require at least 2 lock/unlock pairs (there may be more, I'm not thinking too hard about it): def donothing(): pass -- Christopher A. Craig Code that does not adhere to the documentation is bad code that should be broken, even if it is your own. -- Christian Tismer From bill at rfa.org Sat Dec 20 20:45:39 2003 From: bill at rfa.org (Bill Eldridge) Date: Sun, 21 Dec 2003 02:45:39 +0100 Subject: Unicode from Web to MySQL In-Reply-To: References: Message-ID: <3FE4FB43.8030201@rfa.org> >>What I'd like is something as simple as: >> >>CREATE TABLE junk (junklet VARCHAR(2500) CHARACTER SET UTF8)); >> >>import MySQLdb, re,urllib >> >>data = urllib.urlopen('http://localhost/test.html').read() >> >> > >data2 = data.decode(encoding,'replace') >... >c.execute(''' INSERT INTO junk ( junklet) VALUES ( '%s') ''' % data2 ) > > > >Quick scanning of mysql-python docs reveals that you should also >call connect with unicode='utf-8' parameter. Have you done that? > > > I added that now, but it doesn't seem to make much difference (I think it's more for returning data from MySQL, not storing it, but that will still be useful) I did a test where I grabbed the URL using the same routines and dumped the thing to a file, and then edited out all the English and various HTML, and the SQL insert works at that point. It seems the mixed language is throwing stuff off, which wouldn't bother me if my re.search for only the Vietnamese text were working properly, but it isn't. >>where data2 is somehow the UTF-8 converted version of the original Web page. >> >>Additionally, I'd like to be able to do: >> >>body_expr = re.compile('''(.*)''') >> >>data = urllib.urlopen('http://localhost/test.html').read() >> >>main_body = body_expr.search(data).group(1) >> >> > >Don't do that to data var because data is an 8bit string which >contains bytes not characters, use data2 instead. > >As a rule of thumb you should decode to unicode as soon as you >can and leave unicode world as late as you can. And use unicode >aware APIs when they are available, this way you won't even >need to encode unicode objects. > > > > >>and insert that into the database, and most likely I need to >> >>I'm sitting with a dozen explanations from the Web explaining >>how to do this, >>0) decode('utf-8','ignore') or 'strict', or 'replace'... >>1) using re.compile('''(?u)'''), >> re.UNICODE+re.IGNORECASE+re.MULTILINE+re.DOTALL) >> >> > >You don't need re.UNICODE if you don't use \w, \W, \b, or \B > > > >>2) Convert to unicode before UTF-8 >> >> > >Not sure what that means. > > > >>3) replace quotation marks within the SQL statement: >>data2.replace(u'"',u'\\"') >> >> > >It's not a unicode problem, is it? > >-- Serge. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From manatlan at online.fr Wed Dec 3 14:39:31 2003 From: manatlan at online.fr (marco) Date: Wed, 03 Dec 2003 20:39:31 +0100 Subject: Adding method to object In-Reply-To: References: <72krsvcpeur8hhu74s4bhlsq3bf60fu055@4ax.com> Message-ID: <3fce3c07$0$236$4d4eb98e@read.news.fr.uu.net> Sean Ross wrote: > "marco" wrote in message > news:bql820$uka$1 at s1.read.news.oleane.net... > >>>>Is it possible to do the same thing for an attribut, instead of a > > method > >>? >> >>>>i'd like to wrap an newAttribute to an oldAttribute one : >>>>example: >>>>i've got an instance "n" of an "xmlNode" class >>>>i'd like to use "n.parentNode" instead of "n.parent" ... >>> >>>[snip] >>> >>># try this ... >>>n.parentNode = n.parent >> >>i'll try, >>but ... it s not dynamic .... >> >>if n.parent change .... n.parentNode will not change ... it must be >>re-affected ... not ? >> > > > You're right. Sorry about that. Maybe you could use a property? > > n.__class__.parentNode = property(lambda self: self.parent, ... etc ... ) > > This way you can get/set/del n.parent using n.parentNode, and changes > to n.parent will be reflect in n.parentNode. > > There's probably another way, but I can't think of it at the moment... > > Hope that's a little more helpful than the last suggestion, > Sean > > > perfect ! it works like a charm thanx a lot ! From andreif at mail.dntis.ro Wed Dec 24 04:44:49 2003 From: andreif at mail.dntis.ro (Stormbringer) Date: 24 Dec 2003 01:44:49 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> <7xr7yvjle5.fsf@ruckus.brouhaha.com> Message-ID: <21bb8d55.0312240144.4eb9caab@posting.google.com> Paul Rubin wrote in message news:<7xr7yvjle5.fsf at ruckus.brouhaha.com>... > andreif at mail.dntis.ro (Stormbringer) writes: > > The only thing that bothers me a little is the speed for building the > > index, I tried with around 5000 messages and I am not quite thrilled, > > it's not _extremly_ slow but it has to be faster for what I need. > > Perhaps I'll use the C++ version with some Python bindings. > > Why not do some profiling first. Maybe it's limited by i/o traffic > rather than cpu cycles. I don't know how Lupy works but the one time > I messed with full text indexing, the bottleneck was definitely the > random disk accesses needed for every word of each update. The > solution is to batch the updates. Sorting is much less seek intensive > than random updates. Sounds like a poorly designed system the one you messed with. Even if it was limited i/o traffic I am not sure how to do profiling to find out if this is the case (although I do have doubts about this) - any suggesions how ? Andrei From nospam at nopes Mon Dec 15 21:23:08 2003 From: nospam at nopes (Steve) Date: Tue, 16 Dec 2003 13:23:08 +1100 Subject: Reading pipes in Python In-Reply-To: References: Message-ID: <3fde6c65$1@clarion.carno.net.au> How do we open a pipe programatically? I'm interested in redirecting output from a program to a pipe and then using it from a python script. Thanks Steve Jeroen van der Ham wrote: > Hello, > > During my exploration of Python and rewriting something from Perl to > Python I ran into something odd. I want to use a pipe so that a log of > a program goes into a Python script instead of a log file. > > In Perl you just open a file, but specify that it is actually a pipe, > but you read from it the same way. > So I thought I'd do that with the following Python code: > > f=open('/tmp/myfifo','r') > while 1: > print f.readline() > > Now, here's the weird thing: > - On Darwin this seems to work okay (seen it work odd on netmounts > tho, but not able to test that atm) > - On Linux this works fine until you send something to the pipe, after > which it prints it and starts printing blank lines over and over. > > Even when using os.mkfifo() to create the pipe, this still does not > work properly on Linux. > Anyone any idea why this isn't working and what can be done to make it > work? > > Regards, Jeroen. > From fredrik at pythonware.com Sun Dec 14 04:31:50 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Dec 2003 10:31:50 +0100 Subject: gzip module - help! References: <3fdc2a06.0@news1.mweb.co.za> Message-ID: "bmgz" wrote: > I am having problems trying to use the gzip module, I do the followig > > >>>import gzip > >>>file = gzip.GzipFile("testfile.txt") this attempts to open a compressed file named "testfile.txt". is this what you want? > >>>file.write() -which params does this accept?, archive name? the data you want to store in the file. GzipFile returns a file object, just like an ordinary open. > I get this ERROR: > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/gzip.py", line 139, in write > self.size = self.size + len(data) > AttributeError: GzipFile instance has no attribute 'size' on my machine, that call gives this error: >>> f.write() Traceback (most recent call last): File "", line 1, in ? TypeError: write() takes exactly 2 arguments (1 given) > But if I include a mode in "gzip.GzipFile("testfile.txt", 'wb')" or > something like that I don't get an error > and then I manage to do >>>file.close() but still I can't find any > compressed file? on my machine, that creates a compressed file named "testfile.txt", which unzips to nothing. maybe this is what you want: import gzip, shutil infile = open("testfile.txt") # text file to compress outfile = gzip.GzipFile("testfile.txt.gz", "wb") # archive file shutil.copyfileobj(infile, outfile) outfile.close() to compress a binary file, make sure you pass "rb" as the second argument to the first open: infile = open("testfile.dat", "rb") # binary file to compress (for details, read the gzip and shutil chapters in the library reference) From yan at NsOeSiPnAeMr.com Thu Dec 4 06:34:01 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Thu, 04 Dec 2003 06:34:01 -0500 Subject: Newbie data structes question Message-ID: I have never programmed anyting in python, so this is completely new territory. I've programmed in C for so long it's pretty hard wired in my brain. I'm trying to break out :-) I have a program in mind that I think would be a good learning project. I have a machine that shows movies. There are favorites (most often watched movies) that are kept on the machine and archives that are kept on an NFS server. There are also new arrivals. All movies (new arrivals, favorites, etc) are in the archives. The machine logs movie names of all movies played. The log file is simply a list of movie titles played. If a movie has been played 10 times, it will appear in the list 10 times. I want to write a script that will automatically move most watched movies into favorites, delete movies that are no longer favorites, and replace them with movies that are more frequently watched from archives. So, I have to create a paired list of some sort: (movie, count), (movie, count), (movie, count) .... sort the list on the counts, and then loop through from most often watched movie not in favorites replacing it in the favorites list with the least often watched movie in the favorites list. Stop looping when the watch count for both in favorites and not in favorites is the same. If any movies put in to the favorites were in the new arrivals, delete from new arrivals. So, here's my python question: What data structures and flow controls are most appropriate? Any neat flow control in python? Thanks, -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From bhan at andrew.cmu.edu Mon Dec 22 02:13:46 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Mon, 22 Dec 2003 02:13:46 -0500 (EST) Subject: Singleton process In-Reply-To: References: Message-ID: On Mon, 22 Dec 2003, Andrew Bennetts wrote: > On Mon, Dec 22, 2003 at 01:38:27AM -0500, Benjamin Han wrote: > > On Mon, 22 Dec 2003, Jp Calderone wrote: > [...] > > > import os, errno > > > > > > def shouldRun(): > > > try: > > > os.mkdir(MAGIC_PATH) > > > except OSError, e: > > > if e.args[0] == errno.EEXIST: > > > return False > > > raise > > > return True > > > > But this solution creates a file race condition? > > How? mkdir is atomic. Either it creates the directory and succeeds, or it > fails. I don't see any problems here. ok I see. The reason I'm thinking of using a lock file through fcntl is that even if a lock file exists (maybe due to a crash of some sort before), using the locking mechanism would still work. The "test if it exists" approach would fail because of some leftover from some accidental 'death' of the process before. Any more suggestion? Thanks. From adeleinandjeremy at yahoo.com Mon Dec 1 13:46:33 2003 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon, 1 Dec 2003 10:46:33 -0800 (PST) Subject: Using and Implementing iterators with classes such as linked lists Message-ID: <20031201184633.91490.qmail@web40810.mail.yahoo.com> First of all, I apologize for the double posting - I thought there was some problem with the Yahoo group so I joined the main mailing list and repeated instead of waiting as I should have. Thanks for the speedy and helpful responses. I now grok the downside of using internal iterators. Now, for the external iterator, I am thinking that I would do this: class LinkedList: ... def __iter__(self): return LinkedListIterator(self.__head) class LinkedListIterator: def __init__(self, headNode): self.__current = headNode def __iter__(self): return self def next(self): if self.__current.next == None: raise StopIteration self.__current = self.__current.next return self.__current.next Of course, this LinkedListIterator is for a LinkedList that has a dummy header node, but the concept is the same in any case. I understand the concept of generators, but I do not fully comprehend all of the nuances; for that and a few other reasons, I am avoiding their use here. A few questions though: 1) I think it is best to pass only one node to the iterator, as opposed to the whole list - is that "correct"? 2) The __iter__() method is necessary in LinkedListIterator, am I correct? 3) Does this code display suitable Python idiomatic expression? For example, and in particular, is my use of '==' (as opposed to 'is not') acceptable and good from this viewpoint? Thanks again, - Jeremy __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From robin at jessikat.fsnet.co.uk Tue Dec 16 13:14:31 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 16 Dec 2003 18:14:31 +0000 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: In article , Gustavo Niemeyer writes ...... > >The same as two paragraphs above. > >Also, I should say that I have obvioulsy found some *very* minimal >languages while I was doing the research, but these were either badly >implemented or just didn't offer the basic stuff I was looking for >(easy and elegant C extending, etc). > did you com across bob by any chance? Not very modern, but I remember it was quite small. -- Robin Becker From wtrenker at shaw.ca Thu Dec 25 09:54:55 2003 From: wtrenker at shaw.ca (Bill Trenker) Date: Thu, 25 Dec 2003 14:54:55 +0000 Subject: print arabic characters In-Reply-To: <3014031e.0312242351.d2604c2@posting.google.com> References: <3014031e.0312220305.c38ffa3@posting.google.com> <3014031e.0312242351.d2604c2@posting.google.com> Message-ID: <20031225145455.01ad3747.wtrenker@shaw.ca> Ahmad wrote: > Any other tricks? I don't know if this is of any benefit but I was using the latest Opera web browser on my Linux system and happened to try out the Arabic introduction page on the unicode.org site. The url is: http://www.unicode.org/standard/translations/arabic.html Since I can't read Arabic I don't know if the writing on that page is correctly presented, but I thought you might want to try it out. I know that the Opera folks have put a lot of emphasis into RTL (bidi) support and internationalization. Maybe Opera is an example of at least one application that is making better progress in displaying Arabic. Regards, Bill From aahz at pythoncraft.com Sun Dec 7 09:04:51 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Dec 2003 09:04:51 -0500 Subject: New inited instance of class? References: Message-ID: In article , Francis Avila wrote: > >If you're curious, look in the Python Language Reference at the old >and new style classes to see the differences. There's absolutely no >advantage to old style classes, so stop usin' 'em. In addition to the factors Fredrik mentioned, there's also the issue that new-style classes are more of a moving target WRT syntax and semantics; for complex uses, it can be tricky (or impossible) to get the same code working the same way on both 2.2 and 2.3. More than that, you *can't* use new-style classes for exceptions. So please stop telling people to avoid classic classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From newsgroups at jhrothjr.com Fri Dec 12 08:45:44 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 12 Dec 2003 08:45:44 -0500 Subject: Function application optimization. References: Message-ID: "Jacek Generowicz" wrote in message news:tyf7k128j09.fsf at pcepsft001.cern.ch... > Given > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > > How should one spell > > results = map(lambda f,a: f(a), fncs, args) > > in order to get the result most quickly ? > > > > Unfortunately "apply" takes a tuple of arguments, and there is no > "funcall"[*] in Python. > > > [*] def funcall(fn, *args): > return fn(*args) Building on a couple of other responses: Untested code: fncs = [func1, func2, ..., funcN] args = [arg1, arg2, ..., argN] results = [] for function, arguement in zip(fncs, args): results.append(function(arguement)) Notice the use of zip() to put the two lists together. I haven't timed it, but removing an extra layer of function call has got to be faster. Likewise, zip and tuple unpacking is most likely going to be faster than indexing every time through the loop. The append, on the other hand, might slow things down a bit. John Roth > From list.adam at twardoch.com Fri Dec 5 12:32:39 2003 From: list.adam at twardoch.com (Adam Twardoch) Date: Fri, 5 Dec 2003 18:32:39 +0100 Subject: Unicode 4.0 support Message-ID: As far as I know, currently, Python only supports Unicode 3.0. That is, for example, the unicodedata module only holds the data from the Unicode Standard version 3.0. Since Unicode 4.0 is now released, shouldn't it be included at least in Python 2.4? Best, -- Adam Twardoch adam{at}twardoch{dot}com http://www.twardoch.com/adam From sdb1031 at yahoo.com Sat Dec 6 00:52:35 2003 From: sdb1031 at yahoo.com (Stephen Briley) Date: Fri, 5 Dec 2003 21:52:35 -0800 (PST) Subject: question on HTMLParser and parser.feed() Message-ID: <20031206055235.17827.qmail@web21509.mail.yahoo.com> Hi, I'm new to Python, so please bear with me.. I am satisfied with the HTMLparse of my htmlsource page. But I am unable to save the output of parser.feed(htmlsource). When I type parser.feed(htmlsource) into the interpreter, the correct output streams across the screen. But all of my attempts to capture this output to a variable are unsucessful (e.g. capt_text = parser.feed(htmlsource)). What am I missing and how can I get this to work? Thanks in advance! from htmllib import HTMLParser from formatter import AbstractFormatter, DumbWriter parser = HTMLParser(AbstractFormatter(DumbWriter())) parser.feed(htmlsource) __________________________________ Do you Yahoo!? New Yahoo! Photos - easier uploading and sharing. http://photos.yahoo.com/ From jjl at pobox.com Thu Dec 11 18:42:53 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 23:42:53 +0000 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> Message-ID: <87r7za2a6a.fsf@pobox.com> Richie Hindle writes: > [Jarek] > > Most of the world still blocks execution with synchronous sockets. Event > > driven programming is not a wholly accepted idea. > > I just came across this in Moshe Zadka's blog. Not strictly relevant but > it made me smile: > > "The correct way to explain [async programming] is as some kind of Zen, > and even Buddhism. > > In order to program on the network, which is filled by buggy and evil > agents, one must give up all expectations. One must sit quietly, without > desires to plague the flesh, quietly meditating. Only when an event is > received, one must react to it, and then get back to meditating. In this > way, enlightment is achieved. This is why async systems have no read() > call. Reading from the network means you have expectations of what will > arrive. If it doesn't, your hopes are shattered. If you have no hopes to > shatter, you cannot be disappointed." :-) Now, if he'll just publish that in a glossy magazine and make asynchronous network programming fashionable... then half of all programmers will mindlessly stop using threads even when *they're* the sane way to do the job :-( John If you ever reach total enlightenment while you're drinking a beer, I bet it makes beer shoot out your nose. Jack Handey From http Mon Dec 15 16:53:03 2003 From: http (Paul Rubin) Date: 15 Dec 2003 13:53:03 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <3fde2b38$0$19276$626a54ce@news.free.fr> Message-ID: <7xiskhwxxc.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > Not sure this one could make it but : > http://www.iolanguage.com/Comparisons/Size.html > > I only played a few minutes with it so far, but Io might be something > interesting... That comparison list is pretty useless. There are plenty of perfectly good Lisp implementations with 5k or fewer lines of code. SIOD probably has about 1000-2000 lines. From tismer at stackless.com Wed Dec 31 10:05:43 2003 From: tismer at stackless.com (Christian Tismer) Date: Wed, 31 Dec 2003 16:05:43 +0100 Subject: Project dream In-Reply-To: References: <7xfzf1llvy.fsf@ruckus.brouhaha.com> Message-ID: <3FF2E5C7.7000906@stackless.com> Will Stuyvesant wrote: ... > I was not looking for a job! I was just thinking about a project to > work on in my spare time, to sharpen my Python skills and because it > is fun. I already have a job (with some Python programming). Sorry, I've misread your posting. I thought you had money to spend on a new, larger project. No offense in any way. > But um, Christian: what is that "really innovative application" you > mention? Something stackless? Or can't you share the idea because > you don't want others to start working on it? I have several. One of them is a radically different file system. But in fact, I won't talk about it before getting a first version done :-) ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From bill at rfa.org Sat Dec 20 19:18:20 2003 From: bill at rfa.org (Bill Eldridge) Date: Sun, 21 Dec 2003 01:18:20 +0100 Subject: Unicode from Web to MySQL In-Reply-To: References: Message-ID: <3FE4E6CC.6030504@rfa.org> Serge Orlov wrote: >"Bill Eldridge" wrote in message news:mailman.375.1071937328.9307.python-list at python.org... > > >>I'm trying to grab a document off the Web and toss it >>into a MySQL database, but I keep running into the >>various encoding problems with Unicode (that aren't >>a problem for me with GB2312, BIG 5, etc.) >> >>What I'd like is something as simple as: >> >>CREATE TABLE junk (junklet VARCHAR(2500) CHARACTER SET UTF8)); >> >>import MySQLdb, re,urllib >> >>data = urllib.urlopen('http://localhost/test.html').read() >> >> > >You've got 8-bit data here. urllib doesn't currently handle encoding issues, >maybe submitting sf feature request will change that. But right now you have >to do it yourself. Scan (or parse) the html header for encoding, if it's absent >grad the encoding from the http header. > This part is fairly known - I'm setting up feeds that I'll actually look at to scrape content, so identifying the encoding will be part of that. . What's driving me crazy is knowing the encoding but still not getting the data all the way through the chain to MySQL. > If it's absent too, then the encoding >ASAIR is latin1. So you code should look like: >connection = urllib.urlopen('http://localhost/test.html') >encoding = 'latin-1' >header_encoding = get_http_header_encoding(connection) >data = connection.read() >content_encoding = get_http_content_encoding(data) >if header_encoding: > encoding = header_encoding >if content_encoding: > encoding = content_encoding > > > The latin-1 stuff isn't giving me problems, it's the Asian languages, but I'll look at the connection end. >>data2 = ??? >> >> > >data2 = data.decode(encoding,'replace') > > > >>... >>c.execute(''' INSERT INTO junk ( junklet) VALUES ( '%s') ''' % data2 ) >> >> > >Quick scanning of mysql-python docs reveals that you should also >call connect with unicode='utf-8' parameter. Have you done that? > > > No, I haven't, I'll try it. >>where data2 is somehow the UTF-8 converted version of the original Web page. >> >>Additionally, I'd like to be able to do: >> >>body_expr = re.compile('''(.*)''') >> >>data = urllib.urlopen('http://localhost/test.html').read() >> >>main_body = body_expr.search(data).group(1) >> >> > >Don't do that to data var because data is an 8bit string which >contains bytes not characters, use data2 instead. > > > Alright, I've tried it both ways, but this makes it clearer why. >As a rule of thumb you should decode to unicode as soon as you >can and leave unicode world as late as you can. And use unicode >aware APIs when they are available, this way you won't even >need to encode unicode objects. > > > > >>and insert that into the database, and most likely I need to >> >>I'm sitting with a dozen explanations from the Web explaining >>how to do this, >>0) decode('utf-8','ignore') or 'strict', or 'replace'... >>1) using re.compile('''(?u)'''), >> re.UNICODE+re.IGNORECASE+re.MULTILINE+re.DOTALL) >> >> > >You don't need re.UNICODE if you don't use \w, \W, \b, or \B > > > Thanks, I don't. >>2) Convert to unicode before UTF-8 >> >> > >Not sure what that means. > > > data.decode(None,'strict') or unicode(data,'unicode','strict') >>3) replace quotation marks within the SQL statement: >>data2.replace(u'"',u'\\"') >> >> > >It's not a unicode problem, is it? > > > Occasionally instead of getting the encoding error I get a SQL syntax error, and figured somewhere it was misinterpreting something like the end delimiter. No proof though, just a guess, so I tried the replaces. Thanks much, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Thu Dec 11 18:15:29 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Dec 2003 23:15:29 +0000 Subject: minidom and pulldom References: Message-ID: <871xrb2bfy.fsf@pobox.com> martin at v.loewis.de (Martin v. L?wis) writes: > pinto at map.com (David Pinto) writes: > > > I'm trying to use either the minidom or pulldom to find table tags in > > html web pages. I've tried parsing two web pages that show up fine in [...] > minidom is an XML parser. Most Web pages are not XML, but some form of > HTML. > > You should have better chances with parsing HTML using htmllib. Or, better, HTMLParser.HTMLParser -- works better with XHTML. If you don't mind dependencies and want a document tree, a good plan is to shove everything through mxTidy or uTidylib to generate XHTML, then use the XML API of your choice. John From ask_me at gmx.de Wed Dec 24 10:31:34 2003 From: ask_me at gmx.de (=?iso-8859-1?q?Thorsten_R=FChl?=) Date: Wed, 24 Dec 2003 16:31:34 +0100 Subject: writing recursive lambda functions References: Message-ID: Am Wed, 24 Dec 2003 07:08:41 -0500 schrieb Francis Avila: > > You need to return the lambda. You've been coding too much lisp. ;) i never did bit once i will ;) > I'm not sure why you want to code Python as if it were lisp. This will only > lead to tears. It's also quite a bit slower, because calling is expensive > in Python. (I understand if this is simply an academic exercize, but still, > try to read beyond the formal definitions). thank you for your help i read your solutions with much interesting. :))) !!! grettings Thorsten From hwlgw at hotmail.com Mon Dec 8 10:32:35 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 8 Dec 2003 07:32:35 -0800 Subject: Help: Uploading .zip to Python CGI References: <3d06fae9.0312071255.44609881@posting.google.com> Message-ID: > [jmdeschamps at cvm.qc.ca] > Had a similare problem with *.jpg uploads > > uploading files with a shebang such as: > #! c:/python23/python -u > reolved it for me > the -u part telling Windows to get data "unbuffered", so I read somewhere... Great! Solved it for me too! Thank you! From skip at pobox.com Mon Dec 8 11:49:23 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Dec 2003 10:49:23 -0600 Subject: from spam import eggs, spam at runtime, how? In-Reply-To: References: Message-ID: <16340.43923.678949.485036@montanaro.dyndns.org> Rene> How do I do: Rene> from spam import eggs Rene> ... when 'spam' is only known at runtime? help(__import__) Skip From pinard at iro.umontreal.ca Mon Dec 22 11:04:34 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 22 Dec 2003 11:04:34 -0500 Subject: Anyone use ELSE minor-mode in Emacs? In-Reply-To: References: <87ekv3frho.fsf@pobox.com> <20031217154206.GA21073@alcyon.progiciels-bpi.ca> <20031221170409.GA7667@titan.progiciels-bpi.ca> <20031221235511.GA11803@titan.progiciels-bpi.ca> <20031222032550.GA15674@titan.progiciels-bpi.ca> Message-ID: <20031222160434.GA5685@titan.progiciels-bpi.ca> [John J Lee] > I had the impression that Mark's thing (Pythonwin, I think it's called -- > or is that the MFC wrapper? I can never remember.) used the standard > library, or hooked in at the C level, so that syntax colouring is always > correct -- unlike Emacs (and unlike vi, I guess). You can never be sure to have syntax colouring correct unless you scan the source from its beginning. Consider for example that you could have long sections of Python code embedded in triple quotes, turning it all into a single long string indeed. Most editors try to limit the amount of text to consider for syntax colouring, as analysing a lot of text may slow down the editor considerably. They try to limit the analysis to the currently displayed text, and a bit before, not far. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From BJ at replyhere.now Tue Dec 2 00:19:29 2003 From: BJ at replyhere.now (BJ MacNevin) Date: Tue, 02 Dec 2003 05:19:29 GMT Subject: Can Python be run off of a CD-ROM? Message-ID: Hi all, I teach middle school and am currently trying to bring some computer science to the students. Our district has a wonderfully linked network throughout all our schools... done via MS Windows Network. In order to protect the network, our district's IT department does not want things installed on the system (or at least makes it VERY difficult to get it done). SO, I am using MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it off of them. BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I can do the same thing... or something similar? Is there a way to install Python on a CD-ROM, too, if we don't need it to be accessed from a command prompt? Thanks, BJ MacNevin -- _______________________________ I didn't say it was your fault... I said I was going to blame you. From timothy.williams at nvl.army.mil Fri Dec 5 08:32:36 2003 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 5 Dec 2003 05:32:36 -0800 Subject: tkFileDialog.askopenfilenames not regonizing -multiple option Message-ID: Hi. I'm using Python 2.3 and trying to use tkFileDialog to get a list of files. I get a message about the '-multiple' option is not a valid option in the call to Open. Python 2.3 (#1, Aug 4 2003, 10:43:11) [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import * >>> import tkFileDialog >>> root=Tk() >>> files=tkFileDialog.askopenfilenames() Traceback (most recent call last): File "", line 1, in ? File "tkFileDialog.py", line 133, in askopenfilenames return Open(**options).show() File "tkCommonDialog.py", line 52, in show s = w.tk.call(self.command, *w._options(self.options)) _tkinter.TclError: bad option "-multiple": must be -defaultextension, -filetypes, -initialdir, -initialfile, -parent, or -title ~> tclsh % info tclversion 8.3 Thanks for any help. From tjreedy at udel.edu Fri Dec 26 09:57:01 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Dec 2003 09:57:01 -0500 Subject: Question about functions References: Message-ID: "Aubrey Hutchison" wrote in message news:I_2dnalUksLsg3GiRVn-uA at comcast.com... > Question about functions: It is not clear what your question is. Some comments anyway: > 1)--- module "A" contains the following > X = 999666 #easy to notice value > Y = 111222 #easy to notice value > Product = 69696969 #easy to notice value Should this just be "Product = X*Y' ? > def DoSomething(): > global Product,X,Y global Product # is sufficient since X,Y are read only > Product = X*Y return X*Y # might be better > return 0 Omit: better to allow default return of None when there is no real return value > module imported I presume this is a comment missing # > from A import * and that this belongs with the toplevel code below. But you almost certainly do not want to import everything. 'import A' or 'from A import DoSomething'. > 2)--- toplevel code > > def Mult(): > global Product,X,Y omit since not used in this function > DoSomething(): > return 0 Again, no return. Better would simply be 'Mult = DoSomething' > """start of top level code """ > ... > ... > Product =Mult() > ... > print Product ( Result ----> print out is 69696...) > > Per "Python Nutshell" this appears to be the correct result. > How do you or can you modify the imported variables without using > classes objects? You have not used any class objects, so I do not understand question. In any case, you can only modify mutable objects. Otherwise, you can only rebind name in one namespace or another. You must keep module A namespace and main module namespace distinct in your mind since interpreter does. Terry J. Reedy > Aubrey > > From tjreedy at udel.edu Mon Dec 29 15:40:14 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Dec 2003 15:40:14 -0500 Subject: Hi,do i can ask some question about Zope? References: <1efebde.0312290755.57f8c83c@posting.google.com> Message-ID: <_rOdneD-XoW3DG2iRVn-jQ@comcast.com> "soso" wrote in message news:1efebde.0312290755.57f8c83c at posting.google.com... > I have some question in zope,but i can't get answer from Zope.org,may > i ask the question here? There are over 50 mailing lists for discussing various aspects of Zope and associated applications. Some are listed on the zope.org site. But an easy way to read (and maybe post) is through gmane, a mailing list - newsgroup gateway. In your newsreader set up an account for news.gmane.org (no password needed), download its newsgroup list, and search it for zope. Terry J. Reedy From skip at pobox.com Wed Dec 17 15:36:29 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Dec 2003 14:36:29 -0600 Subject: tuples and cartesian coordinates In-Reply-To: <20031217201815.GA5831@nl.linux.org> References: <20031217201815.GA5831@nl.linux.org> Message-ID: <16352.48717.970544.828159@montanaro.dyndns.org> Gerrit> the FAQ says: >> For example, a Cartesian coordinate is appropriately represented as a >> tuple of two or three numbers. Gerrit> I find it strange to use tuples for a coordinate.... Gerrit> Shouldn't coordinates be mutable? See the recent (long) thread on this subject: http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=7x7k1b4yqn.fsf%40ruckus.brouhaha.com&rnum=1&prev=/groups%3Fq%3Dg:thl2494494598d%26dq%3D%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D7x7k1b4yqn.fsf%2540ruckus.brouhaha.com or http://tinyurl.com/zoyt Skip From http Tue Dec 30 22:13:53 2003 From: http (Paul Rubin) Date: 30 Dec 2003 19:13:53 -0800 Subject: Project dream References: Message-ID: <7xfzf1llvy.fsf@ruckus.brouhaha.com> Christian Tismer writes: > > Suppose you have the time and the money to start a new project in > > Python. What would you like to do? > > I would like to provide some ideas which I'm carrying around since > quite some time. My reluctance is about the fact that I almost never > saw an announcement like this being a serious offer. Most of the > time it was just some sugar spread around to make people excited, > creating lengthy threads with no result. How serious are you about > spending a reasonable amount for a really innovative application in > Python. I'm a bit curious since none of my google hits reach beyond 2003. I don't see any bad consequences of posting interesting ideas for projects, even if nobody takes them up. From michael at foord.net Thu Dec 4 09:49:11 2003 From: michael at foord.net (Fuzzyman) Date: 4 Dec 2003 06:49:11 -0800 Subject: Creating a List of Empty Lists Message-ID: <8089854e.0312040649.4a7f1715@posting.google.com> Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or* just created a new pointer to the original value.... For example I wanted to initialize a list of empty lists.... a=[ [], [], [], [], [] ] I thought there has to be a *really* easy way of doing it - after a bit of hacking I discovered that : a = [[]]*10 appeared to work however - using it in my program called bizarre crashes.... I eventually discovered that (as a silly example) : a = [[]]*10 b=-1 while b < 10: b += 1 a[b] = b print a Produced : [ [9], [9], [9]...... Which isn't at all what I intended............... What is the correct, quick way of doing this (without using a loop and appending...) ? Fuzzyman http://www.Voidspace.org.uk The Place where headspace meets cyberspace. Online resource site - covering science, technology, computing, cyberpunk, psychology, spirituality, fiction and more. --- http://www.atlantibots.org.uk http://groups.yahoo.com/group/atlantis_talk/ Atlantibots - stomping across the worlds of Atlantis. --- http://www.fuchsiashockz.co.uk http://groups.yahoo.com/group/void-shockz --- Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera From mysoso282 at yahoo.com.cn Mon Dec 29 10:55:57 2003 From: mysoso282 at yahoo.com.cn (soso) Date: 29 Dec 2003 07:55:57 -0800 Subject: Hi,do i can ask some question about Zope? Message-ID: <1efebde.0312290755.57f8c83c@posting.google.com> I have some question in zope,but i can't get answer from Zope.org,may i ask the question here? From echols at uclink.berkeley.edu Thu Dec 4 00:02:40 2003 From: echols at uclink.berkeley.edu (Nat Echols) Date: Wed, 3 Dec 2003 21:02:40 -0800 Subject: segfault in extension module In-Reply-To: References: <6250403b.0312010017.27f5f341@posting.google.com> Message-ID: > Post some code. may god have mercy on my soul: #include #include "nw.h" static PyObject *nw_align (PyObject *self, PyObject *args) { char *seq1, *seq2, *mfile; char *out1, *out2, *match; int penalty, status, score; PyObject *results; if (! PyArg_ParseTuple(args, "sssi", &seq1, &seq2, &mfile, &penalty)) { return NULL; } status = nw(seq1, seq2, mfile, penalty, &out1, &out2, &match, &score); if (status == -1) { PyErr_NoMemory(); return NULL; } results = Py_BuildValue("(sssi)", out1, out2, match, score); return results; } static PyMethodDef nwMethods[] = { {"align", nw_align, METH_VARARGS, "Perform Needleman-Wunsch alignment of two protein sequences."}, {NULL, NULL, 0, NULL} /* This is required! No idea why. */ }; void initnw (void) { (void) Py_InitModule("nw", nwMethods); } This is just the wrapper; the function that it calls is defined such: int nw (char *seq1, char *seq2, char *matrixfile, int penalty, char **_out1, char **_out2, char **_match, int *_score); (I can supply this too, but I already know this works fine in a standalone C program.) In Python, I simply do this: (out1, out2, match, score) = nw.align(seq1, seq2, "BLOSUM62", 0) This is it; should be simple to fix, no? From Scott.Daniels at Acm.Org Sat Dec 6 19:20:55 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 06 Dec 2003 16:20:55 -0800 Subject: Newbie question: Any way to improve this code? In-Reply-To: References: Message-ID: <3fd13b81$1@nntp0.pdx.net> Gustavo Campanelli wrote: > I'm begining to work in a program that cicles through a list of phrases > (basically, a changing signature file). I started yesterday, and I only > have abput 8 full hours of real Python experience. Too much fun. I wrote a random quote generator. Spec is to to pull a quote from a quote file at random, with each quote appearing equally often. I threw in a command line arg to seed the RNG or replace the quote file name. Try it yourself before looking below (I'll wait). import sys, random def choose_quote(args=None): """Choose a quote at random from a quote file. args should be a list of string arguments. Args begins with '@' are used to seed the random number generator. Otherwise the arg is presumed to be the quote file name. If args is passed in as None, args is grabbed from sys.argv (the command line). """ quotefile = SOURCE best, quote = -1.0, 'Sorry, no quote today. -- the Management' if args is None: args = sys.argv[1:] for arg in args: if arg.startswith('@'): random.seed(arg) else: quotefile = arg try: source = file(quotefile) except IOError, e: print >>sys.stderr, 'I cannot seem to read %r.' % quotefile else: # The file is open. Choose the line with the highest score. # Each line is assigned a value by random(), any of which is # greater than the initial -1. This gives each line in the # file an equal chance of being chosen. try: for line in source: score = random.random() if score > best: best, quote = score, line except IOError, e: print >>sys.stderr, 'Error reading file %r.' % quotefile # Treat any I/O error as EOF. We may already have a quote. source.close() return quote.strip() if __name__ == '__main__': print choose_quote() -Scott David Daniels Scott.Daniels at Acm.Org From Ax10 at gmx.de Mon Dec 1 10:39:12 2003 From: Ax10 at gmx.de (Mike Abel) Date: Mon, 1 Dec 2003 16:39:12 +0100 Subject: tkFileDialog.askdirectory Message-ID: <0u3s91-v42.ln1@6.mabelsoft.org> Hello i have a Linux Mandrake Distribution with Python 2.3 and Tcl/Tk 8.4. Python 2.2 and Tcl/Tk 8.3.3 returns an String if i made this: x = tkFileDialog.askdirectory(initialdir="was auch immer", title="xxx") print type(x) With the combination Python 2.3 and Tcl/Tk 8.4 it returns I have asked an other user (he used Windows 2000 Python 2.3.2 Tcl/Tk 8.4) and it returns an string. Is the Python version the reason or what goes wrong, or is it a new feature? Mike From rob02omni at vodafone.it Wed Dec 17 04:50:55 2003 From: rob02omni at vodafone.it (Roberto) Date: Wed, 17 Dec 2003 10:50:55 +0100 Subject: Lanching application Message-ID: Hi there, Hi want to start multiple sessions of an application that is not multi-tread (in windows) any idea about this. I think that it can be started as a subprocess of a (python) session?? Thanks ! Rob From me at privacy.net Fri Dec 12 18:50:55 2003 From: me at privacy.net (Tobias Pfeiffer) Date: 12 Dec 2003 23:50:55 GMT Subject: Working with copies of a dictionary Message-ID: Hi! Damnit, am I angry! Please look at the following example: class bla: def __init__(self): self.ho = {'a': ['b'], 'c': ['b', 'e', 'f', 'd'], 'b': ['a', 'e', 'f', 'c'], 'e': ['b', 'c', 'g', 'h'], 'd': ['c'], 'g': ['e', 'h'], 'f': ['b', 'c'], 'h': ['e', 'g']} # shall be an adjacence list of a graph... self.oha = [('a', 'b'), ('b', 'c'), ('b', 'e'), ('b', 'f'), ('c', 'd'), ('c', 'e'), ('c', 'f'), ('e', 'g'), ('e', 'h'), ('g', 'h')] def do_stuff(self): next = self.ho.copy() # HERE!!! edges = self.oha[:] next['c'].remove('e') next['g'].remove('h') del next['b'] edges.pop(0) edges.pop(3) edges.pop(6) f = bla() print f.ho print f.oha OK, so the two last lines, what surprising thing give me exactly the long dictionary I defined in __init__. f.do_stuff() Now you see that I do nothing with the self.* thingies themselves. So why in hell do the following two lines give me a different output??? print f.ho print f.oha f.oha hasn't changed, but f.ho now lacks the two elements I deleted from next with the remove() call, while the 'b' array is still there. Now can anyone please explain me why do_stuff() ha changed the attributes of the class?? Even the following: next = {} for v, e in self.ho.items(): next[v] = e , where one can easily see that next does not even have the slightest connection to f.ho, changes it!! I am completely desparate, because I would just like to work with the copy of that dictionary, without deleting the proper one. How can I do such a thing? Thanks in Advance Tobias -- please send any mail to botedesschattens(at)web(dot)de From michele.simionato at poste.it Thu Dec 18 11:29:20 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 18 Dec 2003 08:29:20 -0800 Subject: Installing tcl/tk on Linux References: Message-ID: <95aa1afa.0312180829.18e1da0f@posting.google.com> ? ? wrote in message news:... > Hi,I'm a newbie on python. > > When I was trying to install python on Linux Making Tkinter to work under Red Hat can be difficult (this is one of the reason why I switched to Mandrake). Google for "Tkinter Red Hat" on this newsgroup and you will find plenty of advice. Michele From skip at pobox.com Sun Dec 21 09:39:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Sun, 21 Dec 2003 08:39:30 -0600 Subject: web programming: experiences with non-zope frameworks? In-Reply-To: References: Message-ID: <16357.45218.33433.60825@montanaro.dyndns.org> Brendan> I was wondering if anyone would like to share their experiences Brendan> with the various frameworks in non-zope land. I like Quixote from the good folks at the MEMS Exchange (all significant members of the Python development team, BTW). It's clearly geared for Python programmers, not web designers, but that fits me to a 'T'. http://www.mems-exchange.org/software/quixote/ http://www.quixote.ca/ Skip From Mike at DeleteThis.Geary.com Wed Dec 24 16:01:50 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 24 Dec 2003 13:01:50 -0800 Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: python newbie wrote: > Ok, now I'm thinking _not_ Komodo, because it requires ActivePython, > and I'd prefer to stick with my python.org installation of Python. Komodo doesn't require ActivePython. It works fine with the python.org distribution. The Komodo release notes say that some advanced features require ActivePython, but I would bet that if you install the same extra modules that ActivePython provides (especially Mark Hammond's extensions on Windows) it would work just as well. > If you still have advice as to what debugger you use for wxPython > programs, I'd welcome the advice. I would suggest trying more than one and see which you like the best. Komodo is my favorite, but I tried all of the ones people have mentioned in this thread before settling on it. -Mike From jjl at pobox.com Fri Dec 5 12:03:35 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Dec 2003 17:03:35 +0000 Subject: How to tell the difference between string and list References: Message-ID: <877k1bmc2g.fsf@pobox.com> Jan Kokoska writes: > I need to recognize 'var' and ['var'], usually I would use: [...] All the other solutions posted are bad because they fail for user-defined string-like classes (unless those classes use the new 2.2 features by deriving from str or unicode). As long as your strings aren't huge: def isstringlike(x): try: x+"" except TypeError: return False else: return True I think I stole this off Alex Martelli. John From brendano at stanford.edu Sun Dec 21 02:06:39 2003 From: brendano at stanford.edu (Brendan O'Connor) Date: Sat, 20 Dec 2003 23:06:39 -0800 Subject: web programming: experiences with non-zope frameworks? Message-ID: Hello world, I love python and desparately want to get away from php for programming a web app. I've read numerous summaries of the toolkits out there -- especially the shootout, http://colorstudy.com/docs/shootout.html -- but there are SO many frameworks, it really feels like there's no clear-cut choice for an appserver-based or even mod_python-based framework, and very few judgement calls on what differentiates toolkits from each other. I was wondering if anyone would like to share their experiences with the various frameworks in non-zope land. WebWare and SkunkWeb both look quite good to me; sqlobject was mentioned earlier here, and looks intuitive and quite useful. Spyce looks like a good templating system. But so does skunkweb's stml, and then there's a zillion more of them... Can anyone make comparisons among the different frameworks? What combinations of packages do people use? Are *any* of them substantially more popular than any other? I think it would be nice to have not another list of several dozen one-man projects, but rather a collection of practical knowledge to narrow a python web programmer's options to the realistic and mature choices. If I can't find any clarity, I'm gonna be consigned to php hell for a long time coming... Thanks a lot! Brendan O'Connor Links: http://webware.sf.net http://skunkweb.sourceforge.net/ http://www.sqlobject.org Summaries: http://colorstudy.com/docs/shootout.html http://www.python.org/cgi-bin/moinmoin/WebProgramming From JoeyTaj at netzero.com Fri Dec 5 09:59:43 2003 From: JoeyTaj at netzero.com (Paradox) Date: 5 Dec 2003 06:59:43 -0800 Subject: PyDoc Private Functions Message-ID: <924a9f9c.0312050659.4888767c@posting.google.com> How do i get PyDoc to generate HTML for private member variables? Thanks Joey From mwh at python.net Mon Dec 1 13:32:13 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Dec 2003 18:32:13 GMT Subject: Printing dots in single-line References: <3fb39e32$1_1@nova.entelchile.net> <8J4yb.249740$mZ5.1858603@attbi_s54> Message-ID: "Rainer Deyke" writes: > Alok Singhal wrote: > > Incidentally, I saw other responses, and most of them suggest > > sys.stdout.write(). Is there a reason that is preferable over the > > solution above? > > Yes: the print statement is an abomination. Says you. I mean, just take a look at Joe Strout's brilliant little "python for beginners" page. Replace all print-statements with sys.stdout.write( string.join(map(str, args)) + "\n") and you surely won't get any new beginners. And That Would Be A Very Bad Thing. -- Fredrik Lundh, 27 Aug 1996 Cheers, mwh -- : Giant screaming pieces of excrement, they are. I have a feeling that some of the people in here have a MUCH more exciting time relieving themselves than I do. -- Mike Sphar & Dave Brown, asr From nospam at covad.net Fri Dec 12 20:12:33 2003 From: nospam at covad.net (Douglas Crockford) Date: Fri, 12 Dec 2003 17:12:33 -0800 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> <87vfon0w1j.fsf@pobox.com> Message-ID: <1ebda$3fda6782$44a4afc5$7027@msgid.meganewsservers.com> > JavaScript (no, don't run away!) is actually quite similar to Python > and is prototype-based. > > JavaScript (ECMAScript, now) has a global object (that happens to be > window in web browsers) that functions rather like the global > namespace in other languages. Right you are, John. For example, http://www.crockford.com/javascript/inheritance.html From piir at earthlink.net Thu Dec 4 03:54:11 2003 From: piir at earthlink.net (Todd Gardner) Date: 4 Dec 2003 00:54:11 -0800 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 Message-ID: <9b849915.0312040054.66484ff1@posting.google.com> --------------------------------------------------------------- I would appreciate any ideas how to write to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2. In C and LabVIEW I use the OutP command to write to directly to a memory address. Thank you -- Todd piir at earthlink.net --------------------------------------------------------------- From try_vanevery_at_mycompanyname at yahoo.com Fri Dec 26 01:55:47 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 25 Dec 2003 22:55:47 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "Dan Olson" wrote in message news:pan.2003.12.25.23.08.46.632062 at fakeemail.com... > On Thu, 25 Dec 2003 14:12:12 -0800, Brandon J. Van Every wrote: > > C is not a good language for anything but portable assembly. > > This will be fun, the same flamewar we had last month... but with Python > fans involved! But this discussion would only (properly) be about the appropriateness of various languages for prototyping Game Designs. I say Python is appropriate, and C isn't. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Desperation is the motherfucker of Invention." - Robert Prestridge From http Wed Dec 17 20:07:10 2003 From: http (Paul Rubin) Date: 17 Dec 2003 17:07:10 -0800 Subject: Save the pythons. References: Message-ID: <7xfzfjndc1.fsf@ruckus.brouhaha.com> Hans Nowak writes: > > Classes are great, but once there are 1000 of them, inheriting > > from each other, I cannot avoid comparing this unpleasant > > situation to java. > > Python's standard library hasn't quite reached the size of Java's, though. I think it's less an issue of library size, than tasteless design. Java's libraries really seems to take OO obsession to unhealthy lengths. I think there's some truth to the notion that Python is getting that disease a little bit. It's often more convenient to pass a function to some module (e.g. a callback), than to subclass a library class, but Java programmers want to do stuff by subclassing anyway. You can see something similar in the Python urllib class (to provide an http basic auth password you have to make a subclass) or in the SocketServer library. From guettli at thomas-guettler.de Wed Dec 3 04:44:12 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 03 Dec 2003 10:44:12 +0100 Subject: Adding method to object Message-ID: Hi! How can I add a method to an object. This code does not work: class Foo: def __init__(self): self.counter=0 f=Foo() def incr(self): self.counter+=1 f.incr=incr f.incr() ===> python extend.py Traceback (most recent call last): File "extend.py", line 12, in ? f.incr() TypeError: incr() takes exactly 1 argument (0 given) From corey.coughlin at attbi.com Wed Dec 3 17:18:35 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 3 Dec 2003 14:18:35 -0800 Subject: Module for doing some Parsing in Python References: Message-ID: I actually wrote a gate level verilog parsing module as part of a generic netlist manipulating/translating package for work a while back. It allowed me to do fun stuff like translate verilog to spice and vice versa, construct netlists from python scripts, and so on. Although it was one of my earlier python projects, so it was awfully C-like, not particularly pythonic. I recently wrote up a new version that was a lot more pythonic, but I haven't added verilog input or output routines yet, just spice. And my boss might not like me sending out that code. But in general, verilog gate level stuff isn't too tricky to parse, buses make things kind of tricky, and there are a lot of different variations (mine was only really reliable with Synopsys output). And behavioral level code would be a real nightmare to parse, I'm sure. It's a shame no one has come up with a nice BNF to python parser package yet, although I'm pretty sure the BNF for verilog is pages and pages (well, OK, 12 pages in my verilog book), so doing a full parser would be a real pain regardless. Anyway, good luck to you, if you do come up with something good, be sure to keep us posted! :D "Boris Boutillier" wrote in message news:... > Hi all, > > I'm looking for parsing a Verilog file in my python module, > is there already such a tool in python (a module in progress) to > help instead of doing a duplicate job. > And do you know of some generic parsing module in python, in which you > give some kind of grammar and callbacks ? > > Thanks for the help > > Boris From jeremy at alum.mit.edu Mon Dec 15 16:36:35 2003 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: Mon, 15 Dec 2003 16:36:35 -0500 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031215191023.GB26055@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> Message-ID: <1071524194.15985.660.camel@localhost.localdomain> One kind of problem is that newer Python features were designed without taking rexec into account. It's possible for untrusted code to cause the trusted interpreter to execute its code without restriction using descriptors. It would be really difficult to reconcile new-style classes and rexec. Perhaps a worthwhile project, but probably one accomplished by design a new restriction mechanism that builds on some of the basic mechanism of rexec. Jeremy From claird at lairds.com Fri Dec 26 10:04:05 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 26 Dec 2003 15:04:05 -0000 Subject: dynamic typing question References: Message-ID: In article , Jason Tesser wrote: >I work for at a college where I am one of 2 full-time developers and we >are looking to program a new >software package fro the campus. This is a huge project as it will >include everything from registration to >business office. We are considering useing Java or Python. I for one >don't like Java because I feel the >GUI is clunky. I also think that we could produce quality programs >faster in Python. . . . >OK what are your guys thoughts here? How have you all overcome the lack >of static typing? Is Python a >bad decision here? By the way we will be using Postgres in the back if >that matters to anyone. > Along with everything others have already written--that you want to focus on test-driven development, that Python is a proven success in Serious Applications, and so on-- your description raises a few concerns in my mind: 1. Why, in your mind or your teammate's, is dynamic typing a "lack"? What, pre- cisely, is the benefit of static typing? There are a number of legitimate answers. It occurs to me that, without precision on which interest you, we might be missing an opportunity to clarify "The Python Way" significantly. 2. Most application-level Python code doesn't--and shouldn't!--employ dynamic typing in any material way. Does that help? 3. Postgres is good stuff. Its support for Python has improved quite a bit over the past few years. 4. My instinct tells me that, yes, you can produce quality results quicker with Py- thon. 5. In writing, "the GUI is clunky" about Java, what do you mean? Are you refer- ring to a particular IDE, or a specific GUI toolkit? Java has several of each; perhaps alternatives would suit you better. 6. Are there alternatives to having the two of you write a "package" from scratch? A LOT of software for college administration has been written already; is none of it appropriate for your situ- ation? -- Cameron Laird Business: http://www.Phaseit.net From noemail at noemail4u.com Tue Dec 23 10:27:54 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Tue, 23 Dec 2003 15:27:54 GMT Subject: list.index() like...but returning lists (for avoiding '0' on multiples hits) References: Message-ID: <34576b357a19be878b19f0df7f0751e5@news.teranews.com> On Mon, 22 Dec 2003 17:37:46 -0300, Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina wrote: >Hi....i asume this is a veeeery usual question. I'm searching on python.org, >but their results is not giving me the answer that i looking for...So, here i >go...when i have myList = [2,4,2,0] ...myList.index(2) returns 0 (python >2.2)....There is a built-in function-method that returns [0,2]? > >Well, sory if RTFM is the answer!! Do you mean a function that returns a list of the indices of all occurrences of the specified value? I don't think there's a builtin, but you could do something like this: def indices(lst, val): """ Return a list of indices of matches. """ return [i for i in range(0, len(lst)) if lst[i] == val] myList = [2, 4, 2, 0] print indices(myList, 2) # [0, 2] --dang From christian.eslbauer at liwest.at Tue Dec 30 14:10:42 2003 From: christian.eslbauer at liwest.at (EsC) Date: Tue, 30 Dec 2003 20:10:42 +0100 Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> <79v2vv0ijgdvqu354uh4mh21v4b3liurj0@4ax.com> <1072798233.200308@news.liwest.at> Message-ID: <1072809902.14197@news.liwest.at> hy JCM! damned - you are right! i didn't know the way Python is handling arguments up to now! It's a little bit different to other languages i know - and somtimes even a little bit easier. i made some (useless) performance-tests to proof your exclamations ... if somebody is interested: i enclosed the code and results ... - String 1 & String2: only read-access within the called function the runtime is almost identical; therefore the text of the string can't be copied - String 3: the argument string is modified but NOT passed back to the caller; - String 4: the argument string is passed "by reference" within a list object and modified. i think this informations are very interesting thanks! greetings iolo ------------ CODE ------------- import sys from string import * from time import * def ls(str): return len(str) def ll(str): return len(str[0]) def as(str): str += "x" return len( str ) def al(str): str[0] += "x" return len( str[0] ) loop = 2000 strlen = 30000 strl = [] strl.append("") strs = "" for a in range(strlen): strs += 'x' strl[0] += 'y' print "Loop: ", loop print "Stringlength: " , strlen print print 'String 1' l = 0 start = time() for x in range(loop): l += ls(strs) end = time() print "duration in seconds: ", end - start print "result: ", l if strlen == l / loop: print 'OK' else: print 'ERROR' print print 'String 2' l = 0 start = time() for x in range(loop): l += ll(strl) end = time() print "duration in seconds: ", end - start print "result: ", l if strlen == l / loop: print 'OK' else: print 'ERROR' print print 'String 3' l = 0 start = time() for x in range(loop): l += as(strs) end = time() print "duration in seconds: ", end - start print "result: ", l if l == loop * strlen + loop: print 'OK' else: print 'ERROR' print print 'String 4' l = 0 start = time() for x in range(loop): l += al(strl) end = time() print "duration in seconds: ", end - start print "result: ", l if l == (loop / 2 ) * ((strlen + 1) + (strlen + loop)): print 'OK' else: print 'ERROR' ---------------- RESULT ---------------- Loop: 50000 Stringlength: 200000 String 1 duration in seconds: 0.0620000362396 result: 10000000000 OK String 2 duration in seconds: 0.0779999494553 result: 10000000000 OK String 3 duration in seconds: 3.2349998951 result: 10000050000 OK String 4 duration in seconds: 5.93700003624 result: 11250025000 OK -------------------------------------------------- "JCM" schrieb im Newsbeitrag news:bss7u2$18e$1 at fred.mathworks.com... > EsC wrote: > > hy! > > > thanks for your explanations! > > > i want to avoid performance-problems by repeated (very often) > > function-calls with very long strings. > > in some languages (C, PHP, Powerbuilder, ...) i have the opportunity, > > to pass "by value" or "by reference/pointer)". > > The text of the string is not copied; a reference to the string/object > is passed into the function. You can modify objects passed into > functions (but only if they're mutable--strings and integers are > examples of immutable objects), but you cannot rebind the variable > holding the value in the caller's scope. > > There have been some discussions in this newsgroup about whether > Python is call-by-value or not. I'm not sure if I want to recommend > looking for them; there was no good consensus about the terminology. From piir at earthlink.net Mon Dec 8 21:25:43 2003 From: piir at earthlink.net (Todd Gardner) Date: 8 Dec 2003 18:25:43 -0800 Subject: How to graph two columns of x,y numbers? References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: <9b849915.0312081825.3d0a3aa1@posting.google.com> John Hunter wrote in message news:... > >>>>> "Colin" == Colin J Williams writes: > > Colin> Todd, If you are using wxPython, you might consider > Colin> wxPyPlot: > Colin> http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html > > Also matplotlib has a wxpython backend now. It's about a week away > from being ready, but there is a reasonably good development version > at http://matplotlib.sourceforge.net. > > JDH Excellent! Thanks for the heads up, I can't wait to try it. Todd From just at xs4all.nl Wed Dec 10 17:11:40 2003 From: just at xs4all.nl (Just) Date: Wed, 10 Dec 2003 23:11:40 +0100 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> Message-ID: In article , claird at lairds.com (Cameron Laird) wrote: > In article , > Jarek Zgoda wrote: [ ... ] > >Most of the world still blocks execution with synchronous sockets. Event > >driven programming is not a wholly accepted idea. > . > . > . > Sooooooo true. Hang out with Perlites or C++ians sometime; > you'll hear them talk about how easy it is to do networking > now, and then they start saying words like "fork" and "thread". > My point is that their accepted concurrency models involve > serious burdens in regard to performance and developmental > fragility. > > Mr. Zgoda's right: event-driven networking remains poorly > appreciated, and those of us who favor it find it MUCH > preferable to the alternatives. This ties nicely into the xsdb + stackless discussion: - threads + blocking sockets is attractive since the code can be written in a natural style, yet cause overhead and synchronization headaches. - async sockets are attractive because they avoid threads and therefore avoid overhead and synchronization issues. Yet it is often a bit harder to code, since you need to turn your code inside out, using callbacks. But there is a "perfect" solution: co-routines. With co-routines you can both write the code in a "natural" style, but still using an even-driven core. This is a very pleasant model to work with, so I totally understand that some people (eg. Aaron) choose to use Stackless to make this possible. Just From faizan at jaredweb.com Mon Dec 15 22:49:30 2003 From: faizan at jaredweb.com (Fazer) Date: 15 Dec 2003 19:49:30 -0800 Subject: Strip HTML tags? References: <7b454334.0312131911.70647953@posting.google.com> <7b454334.0312141157.8383dd5@posting.google.com> <7b454334.0312151121.edae739@posting.google.com> Message-ID: <7b454334.0312151949.50f903b8@posting.google.com> BW Glitch wrote in message news:... > Fazer wrote: > > BW Glitch wrote in message news:... > > > >>Fazer wrote: > >>>Thanks! The recipe works out fine! The problem is that I saved the > >>>class in a file and I want it to be included in my other script. How > >>>can that be done? My other script is in the same directory as the > >>>class and doing import doesn't work. > >> > >>You should import > > > > Thanks for the responce! I put the class and the final function in a > > tags.py file. I make another script and do : "import tags" > > It works, but when I try to make a new class instance, it can't seem > > to find it. > > There are two ways to import modules, "import module" and "from module > import *". The latter is seldom recommended. > > By doing a "import module", anything inside the module must be called > like this: > > ### begin example > import sys > > sys.exit(0) > ### end example > > When you do a import tags, everything inside tags must be called > tags.CLASS . > > HTH, > > -- > Glitch > Ahh...thanks a lot! I get it know. From cbrown at metservice.com Tue Dec 16 14:44:14 2003 From: cbrown at metservice.com (Colin Brown) Date: Wed, 17 Dec 2003 08:44:14 +1300 Subject: Cropping log files References: Message-ID: <3fdf607a$1@news.iconz.co.nz> "Kamus of Kadizhar" wrote in message news:brmp3g$b4ar$1 at news3.infoave.net... ... > I'm tyring to figure out how to best crop a log file. I have a file > that grows infinitely in length. I want to keep only the last n entries > in the file. ... An alternative solution may be to write date-based files with deleting of files older than some limit. Here is an example (class HourlyLog) of date-based hourly logging with day-based cleanup: ------------------------------------------------------ import glob, os, time def Now(): # UTC time now as a string return time.asctime(time.gmtime()) def DD_HH(): # 2 digit utc day & hour return time.strftime("%d_%H",time.gmtime()) def Hhmmss(): # "hh:mm:ss" string return time.strftime("%H:%M:%S",time.gmtime()) def DaysAgo(number): # time days ago return time.time() - (86400 * number) class Hour: def __init__(self): self.hour = time.gmtime()[3] def change(self): hour = time.gmtime()[3] if hour != self.hour: self.hour = hour return 1 else: return 0 # filename must contain '##_##' for the 2 digit day and hour fields def FileHourLog(f,s): # append string to daily logfile (nb: win32 does lf -> crlf) try: ff=open(DD_HH().join(f.split('##_##',1)),'aU') except: ff=open(DD_HH().join(f.split('##_##',1)),'wU') ff.write(''.join(['-----< ',Now(),' >-----','\n',s.replace('\r\n','\r').replace('\r','\n'),'\n'])) ff.close() def FileBefore(f,time): # return true if file modification date is before time()-secs try: if os.stat(f)[8] < time: return 1 else: return 0 except: return 0 # may not exist in multi-threaded app. def FileTidy(list,at): # delete files older than time for file in list: try: if FileBefore(file,at): os.remove(file) except: pass # may not exist in multi-threaded app. def FilesMatching(path,pattern): # return a list of files matching pattern. return glob.glob(os.path.join(path,pattern)) class HourlyLog: # filename as per FileLog; number of days to keep def __init__(self,f,n): self.hour = Hour() self.f = f self.n = n def log(self,s): FileHourLog(self.f,s) if self.hour.change(): [path, name] = os.path.split(self.f) pattern = name.replace('#','?') folder = FilesMatching(path,pattern) FileTidy(folder,DaysAgo(self.n)) ------------------------------------------------------------- Colin Brown PyNZ From peter at engcorp.com Fri Dec 12 09:43:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 12 Dec 2003 09:43:05 -0500 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> <3FD8C13F.6BC2B2DD@engcorp.com> <3fd8c97b$0$574$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3FD9D3F9.2304606D@engcorp.com> Brian Kelley wrote: > > When I said "why isn't > there a .write(...) method for these widgets? Why can't I use a text > widget like
    " that wasn't a specious Robin should do this > for me question. It really was more like, is this a way a text widget > should behave? That wasn't clear from the wording you used. Thanks for clarifying. :-) It's a good question... I don't have the answer. -Peter From jsbenson at bensonsystems.com Tue Dec 16 11:48:12 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Tue, 16 Dec 2003 08:48:12 -0800 Subject: lookin' for Python magazines Message-ID: <005c01c3c3f4$6505c7a0$d709500a@jsbwxp3> At first, I looked for Linux magazines to convince me that Linux was worthwhile, and then realized that the real information flow was on the Internet: in point of fact, that's how it really got rolling. As a result, I never even looked for a magazine for Python, since just plowing through the mailing list keeps me well occupied and greatly entertained. I don't see how any print-based media could improve on scanning the mailing list, except that you see a few ads and some glossy pictures. But I can post a question to a list and get pretty immediate gratification, which print-based media just can't supply. It's fun to see pictures of the people that bulk large in the different open source tribes, so maybe a kind of "Life" photojournalism offering or picture calendars would be more entertaining than static text on dead trees. Think of the possibilities (besides the swimsuit issue): "Programmers and their cars," "90-second Programmer Biographies," "I was a COBOL programmer: Now it can be told," and, of course "Storage Jars: The Programmer's Best Friend." From hungjunglu at yahoo.com Fri Dec 12 19:25:14 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 12 Dec 2003 16:25:14 -0800 Subject: Prototype-based programming References: <8ef9bea6.0312101637.33574fb9@posting.google.com> <3fd7bf36$0$28702$626a54ce@news.free.fr> <8ef9bea6.0312111011.6a49053d@posting.google.com> <95aa1afa.0312112228.7f0e09e8@posting.google.com> Message-ID: <8ef9bea6.0312121625.3e4857c5@posting.google.com> michele.simionato at poste.it (Michele Simionato) wrote in message news:<95aa1afa.0312112228.7f0e09e8 at posting.google.com>... > hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0312111011.6a49053d at posting.google.com>... > > Why do you want to print out the source code of a block? Are you thinking > about dynamic modification of the source code and recompilation of the > code block on the fly? If you want those features then lisp-like languages > are a natural choice. Or do you have something else in mind ? > The latter. Keeping reference to the source code means that you have taken into account the needs of debugging/tracing: you can step through the code, set break points, etc., even if the pieces are dynamically assembled. Dynamically compiling code is piece of cake, even C# does that. But have you thought about break points and debugging issues? regards, Hung Jung From mark at mceahern.com Sun Dec 14 10:49:41 2003 From: mark at mceahern.com (Mark McEahern) Date: Sun, 14 Dec 2003 09:49:41 -0600 Subject: Find and Delete all files with .xxx extension In-Reply-To: <93f5c5e9.0312140706.312a3ab1@posting.google.com> References: <3FDBC1B8.4010205@hotmail.com> <93f5c5e9.0312140706.312a3ab1@posting.google.com> Message-ID: <1071416980.11531.199.camel@dev.internal> On Sun, 2003-12-14 at 09:06, hokiegal99 wrote: > > I would say: if fname.lower().endswith( '.mp3' ): > > Why the '.lower()' part? Wouldn't if fname.endswith('.mp3'): work just > as well, or am I missing something here? Because the filename might be WHATEVER.MP3 and endswith, presumably, is case-sensitive. Cheers, // m From rainerd at eldwood.com Fri Dec 19 12:54:03 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Fri, 19 Dec 2003 17:54:03 GMT Subject: How to use a 5 or 6 bit integer in Python? References: <4h95uvg1jpbt1psdon9m4ov7tbc79d586g@4ax.com> Message-ID: <%WGEb.598357$Tr4.1565545@attbi_s03> Glen Wheeler wrote: > I'll be sure to do this. Will it increase the hash speed for the > big dictionary significantly? Will lookup times or memory storage > requirements decrease? Using strings instead of tuples of integers should decrease memory usage. A character in a string is stored as a single byte, whereas each tuple element needs four bytes. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From bokr at oz.net Sat Dec 6 00:16:19 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Dec 2003 05:16:19 GMT Subject: memory usage References: Message-ID: On 5 Dec 2003 20:20:17 -0800, jaguar4096 at yahoo.com (Dave) wrote: >Hi, >I'm writing code which deals with lists of millions to tens of >millions of >elements. It seems to me that python gobbles up memory faster than it >should in these cases. > >For example, I start the python interpreter and then execute the >following code: > >>>> f = [] >>>> for i in range(1e7): >... f.append(0.1) > >In another window on my Linux system I then run top. The python >process is now using 155 MB of memory. Why is python using such a >large amount of memory, nearly nearly 16 bytes for a float in this >case? What system are you using and what python version? The above should generate 10**7 references to a single float value of 0.1, so it's not floats, at least python 2.3.2 for windows nt. The references the list should be just 32-bit pointer, I think, with some boilerplate for the list. However, range allocates a list of individual numbers once you get past the 100 or so that are shared for optimizing small lists. That's a list of 1e7 references to ~1e7 integers, and the integers will be objects, not just 32-bit values, so that is what takes up the first chunk of memory, though it will be released for reallocation (not back to windows) at the end of the loop. You started f empty, and as you add to its length, it has to grow, which is done by allocating ever larger spaces, by some percentage (not just a single item space, of course, or appending would be deadly slow). As the list grows, the space for the out-grown list versions will get released, but still (I think) for reallocation, not back to windows. So you see a lot of space, but most of it is waiting for garbage collection or sitting in pools as freed re-usable-by-python space. For comparison, you might run a fresh program with just f = [0.1]*10**7 and see how much space that uses. Strategy has changed over time re memory allocation, so ymmv according to platform and version. For storing a homogeneous sequence of numeric items like floats or ints etc., check into the array module, where each element just takes its C size effectively. I'm not sure about allocation/reallocation during growth of an array. Perhaps it releases directly back to windows. I would have hoped that there would be a way to allocate an array with a single memory allocation for a specified initial capacity (as opposed to size), as you can do IIRC with C++ STL vectors, but I couldn't find a capacity-setting mechanism. Did I miss it? And the initializer has to be a string or list. Why not any sequence that can deliver the right type elements? Then at least you could make an initializer object that could act like a list without allocating a big initialization list just to chuck it. That's not a good substitute for capacity setting though ;-/ Regards, Bengt Richter From fortepianissimo at yahoo.com.tw Wed Dec 24 16:45:17 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 24 Dec 2003 13:45:17 -0800 Subject: Threaded server: what's wrong with this code? Message-ID: Below are three simple scripts: jmSocketLib.py contains library code for socket server and client, server.py instantiates a server binding to port 50000+ (grab the first available port), and client.py simulates 1000 consecutive connection requests to the server (stress test). The client searches from port 50000 for the server, and sends a challenge "JM?" and expects to get a response "0_87" - otherwise anything that happens to own a port 50000+ would be mistaken to be the real server. The code: ---------- jmSocketLib.py ---------- #!/usr/bin/env python import SocketServer,socket,threading PORT_MIN=50000 PORT_MAX=50005 THREAD_COUNT=0 class JMSocketThread (threading.Thread): def __init__ (self, theSocket): threading.Thread.__init__(self,target=self._myRun,args=[theSocket]) def _myRun (self,theSocket): global THREAD_COUNT THREAD_COUNT+=1 print 'Threaded request started (%d)...'%THREAD_COUNT input='' while 1: input += theSocket.recv(1024) if len(input) and input[-1]=='\n': break input=input.strip() print 'Got input: \'%s\''%input if input=='Is it you?': theSocket.sendall('Yes honey.\n') print 'Threaded request finished.' THREAD_COUNT-=1 class JMHandler (SocketServer.BaseRequestHandler): def handle (self): print 'Client connected...' JMSocketThread(self.request).start() print 'Request handed off to a thread.' class JMServer (SocketServer.TCPServer): def __init__ (self): port=PORT_MIN while port", line 1, in sendall File "/sw/src/root-python23-2.3.2-22/sw/lib/python2.3/socket.py", line 143, in _dummy raise error(EBADF, 'Bad file descriptor') error: (9, 'Bad file descriptor') -------------------------- Of course the client then freezes: ---- Client output ---- 124 Query sent... (and freezes) Does anyone have an explanation why this didn't work? Thanks a lot! From nav+posts at bandersnatch.org Fri Dec 12 14:49:52 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 12 Dec 2003 14:49:52 -0500 Subject: Case sensitive and ludicrous statements (was: True, False, None) References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> Message-ID: Douglas Alan writes: > I have met people who use Perl > and can't be convinced to try Python merely because they have gathered > an opinion that Python devotees are rude and unfriendly, and they'd > rather stick with the friendly Perl people. Who are they? I'll set them straight! But seriously, I'm somewhat surprised that anyone would characterize the Python community as being rude and unfriendly. Have they never been to comp.object or rec.pets.cats? Sure, I've had some less than happy encounters with folk here, but I understood that the tone of the reply I got was in response to the tone of my original post. Nick (or should that be "|\|1c|<"? :^) -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From glenfant at NOSPAM.bigfoot.com Wed Dec 17 13:48:34 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Wed, 17 Dec 2003 19:48:34 +0100 Subject: Spell checking and Python References: Message-ID: "JanC" a ?crit dans le message de news:Xns945447CD5CFE9JanC at 213.119.4.35... > "Gilles Lenfant" schreef: > > > Any experience or pointer on using a spell checker (aspell, ispell ?) > > with a Python app ? > > Maybe snakespell: > > -- > JanC > > "Be strict when sending and tolerant when receiving." > RFC 1958 - Architectural Principles of the Internet - section 3.9 Great... Many thanks JanC -- Gilles From yet-another at no-domain.cn Fri Dec 19 19:32:06 2003 From: yet-another at no-domain.cn (Jules Dubois) Date: Fri, 19 Dec 2003 17:32:06 -0700 Subject: linux wine py2exe ?? References: Message-ID: <1pq860g27f6uw$.llup7i34nxcj$.dlg@40tude.net> On Fri, 19 Dec 2003 20:22:23 +0100, in article , duikboot wrote: > Does anybody know what I've done wrong? No. > Or is it just not possible Maybe. > arjen at linux Python23]$ wine python.exe setup.py py2exe [...] > py2exe_util.bind_error: C:\Python23\DLLs\_sre.pyd Did you copy the pyd file into C:\Python23\DLLs\ on the (WINE-mapped) C: drive? In the past, I've copied DLLs one by one into my WINE configuration directory as applications complained about not finding them. In some cases, I've successfully run the programs; some not. Does the WINE log provide more information? From http Thu Dec 18 00:24:15 2003 From: http (Paul Rubin) Date: 17 Dec 2003 21:24:15 -0800 Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: <7xzndqr94w.fsf@ruckus.brouhaha.com> "Greg Ewing (using news.cis.dfn.de)" writes: > In this case, evaluating the default args at call time would > have a negative payoff, since it would slow down every call to > the function in cases where the default value doesn't need > to be evaluated more than once. In those cases the compiler should notice it and generate appropriate code to evaluate the default arg just once. In many of the cases it can put a static value into the .pyc file. From gerrit at nl.linux.org Wed Dec 17 15:18:15 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 17 Dec 2003 21:18:15 +0100 Subject: tuples and cartesian coordinates Message-ID: <20031217201815.GA5831@nl.linux.org> Hi, the FAQ says: > For example, a Cartesian coordinate is appropriately represented as a > tuple of two or three numbers. I find it strange to use tuples for a coordinate. After all, a coordinate represents a position of an object. Suppose I have a game where the player has a position: isn't it stupid to use tuples rather than lists or another type (maybe complex numbers?), because I want to be able to change the position? Shouldn't coordinates be mutable? yours, Gerrit. -- 231. If it kill a slave of the owner, then he shall pay slave for slave to the owner of the house. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From evan at 4-am.com Thu Dec 11 12:13:13 2003 From: evan at 4-am.com (Evan Simpson) Date: Thu, 11 Dec 2003 11:13:13 -0600 Subject: Zope import PythonScript.standard unauthorized In-Reply-To: References: Message-ID: <3FD8A5A9.30103@4-am.com> Lucas Branca wrote: > I've just insalled Zope to test a web application by thirdy part .... > well .... it's very embarrassing cause I'm not able to > see it at work because of Zope ..... (yeah... I'm really newbie :( ) You're more likely to get help with Zope problems from one of the Zope mailing lists. > # Example code: > from Products.PythonScripts.standard import html_quote, urlencode > return 1 Works for me -- what version of Zope and Python are you using? Cheers, Evan @ 4-am From aahz at pythoncraft.com Tue Dec 30 10:33:59 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2003 10:33:59 -0500 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: In article <99dce321.0312300655.14c5a8db at posting.google.com>, David M. Wilson wrote: > >g = re.compile('...') > >def uses_global_yuck(x): > global g > pass Why not just use the global? Without the ``global`` statement, that is. Don't like that? How's it any different from using a class instance? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From blk at srasys.co.in Fri Dec 5 01:21:08 2003 From: blk at srasys.co.in (bala) Date: Fri, 5 Dec 2003 11:51:08 +0530 Subject: Getting Extended Error Information Message-ID: <004601c3baf7$f8458560$440210ac@Bala> Hi,I Need Clear Explanaiation of this below code...Bcos my requirement is similar to the below codeI found this code example code in this link http://www.python.org/doc/lib/unittest-error-info.htmlrunner is not returning the MyTestResult class object, instead it is returning the TestResult Class object.import unittest class MyTestCase(unittest.TestCase): def defaultTestResult(self): return MyTestResult() class MyTestResult(unittest.TestResult): def __init__(self): self.errors_tb = [] self.failures_tb = [] def addError(self, test, err): self.errors_tb.append((test, err)) unittest.TestResult.addError(self, test, err) def addFailure(self, test, err): self.failures_tb.append((test, err)) unittest.TestResult.addFailure(self, test, err) suite = unittest.TestSuite()suite.addTest(unittest.makeSuite(MyTestCase))result = unittest.TextTestRunner(verbosity=2).run(suite)if you run this code,defaultTestResult(self) method not get called....Pls tell me how to extract the error information from MyTestResult classI will be thankfull to you...if u give a solution for the above problem.RegardsBala -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.nospam at removeme.free.fr Wed Dec 10 20:07:47 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2003 02:07:47 +0100 Subject: Prototype-based programming In-Reply-To: <8ef9bea6.0312101637.33574fb9@posting.google.com> References: <8ef9bea6.0312101637.33574fb9@posting.google.com> Message-ID: <3fd7bf36$0$28702$626a54ce@news.free.fr> Hung Jung Lu wrote: > Hi, > > Description of PBP (Prototype-based programming) can be found at: > http://en.wikipedia.org/wiki/Prototype_based > http://www.dekorte.com/Proto/Chart.html > > ("Self" is an example of a PBP language: > http://research.sun.com/self/language.html) > > The most naive PBP would imply a overwhelming redundancy in namespace > entries. (E.g: all object instances carry bindings for their methods.) > Efficient in time, but not very efficient in space (memory usage). But > I am sure people have looked at lookup-precedence strategies, much > like how Python finds names first in the local, then the global, then > the built-in namespace, or how instance attributes are looked up in > multiple inheritance. You may want to have a look at Io http://www.iolanguage.com/ (snip) Bruno From jburgy at hotmail.com Mon Dec 1 09:10:57 2003 From: jburgy at hotmail.com (Jan Burgy) Date: 1 Dec 2003 06:10:57 -0800 Subject: split on blank lines Message-ID: <807692de.0312010610.4461c0e3@posting.google.com> Hi everyone, can somebody tell me why (using Python 2.3.2) >>> import re >>> re.compile(r"^$", re.MULTILINE).split("foo\n\nbar\n\nbaz") ['foo\n\nbar\n\nbaz'] ? Being used to Perl semantics, I expect ['foo\n', 'bar\n', 'baz'] or something equivalent without the '\n' characters in the result strings. I have found that >>> re.compile(r"^\n", re.MULTILINE).split("foo\n\nbar\n\nbaz") ['foo\n', 'bar\n', 'baz'] I prefer the first version however because my intent is stated more clearly. Could this be a bug in sre.py (I looked at the code for a good two minutes but then my head started hurting) Thanks for your help, Jan From reply.in.the.newsgroup at my.address.is.invalid Mon Dec 8 11:33:23 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 Dec 2003 17:33:23 +0100 Subject: from spam import eggs, spam at runtime, how? Message-ID: How do I do: from spam import eggs ... when 'spam' is only known at runtime? -- Ren? Pijlman From naerbnic at uclink4.berkeley.edu Tue Dec 16 17:07:37 2003 From: naerbnic at uclink4.berkeley.edu (Naerbnic) Date: 16 Dec 2003 14:07:37 -0800 Subject: Build classes/packages dinamicaly References: Message-ID: > I want to make the module available to the > caller as if he did an import. > > For example, if I make the following call > > some_module.generate_module('dummy') > > Where some_module is the module that generates > modules dinamicaly, and dummy is the name of the > new module. > > I would like to be able to do > > dummy.something() > > after that call. Well, this isn't the perfect solution, but you can create modules in the system at runtime like so: In your code: >>> mymodule = generate_module() #As above >>> import sys >>> sys.modules['dummy'] = mymodule Now, the user can just do the following: >>> import dummy >>> dummy.something() It's not _quite_ what you want, since it doesn't automatically include it, but it's pretty easy to do. Furthermore, if you standardize the name of the module, you can just have the user import that by default, and then use whatever dynamic content you've put inside. Also, note that mymodule can actually be anything, although you should still use a value that responds to __getattr__ (anything else would be really confusing, and probably a Bad Thing). I hope this helps. - Brian Chin From tchur at optushome.com.au Tue Dec 30 23:32:19 2003 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 31 Dec 2003 15:32:19 +1100 Subject: Formal reference for Python Message-ID: <200312310432.hBV4WI015291@mail009.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From nospam at nopes Wed Dec 17 18:00:48 2003 From: nospam at nopes (Steve) Date: Thu, 18 Dec 2003 10:00:48 +1100 Subject: Using python with SSH? Message-ID: <3fe0dfd7$1@clarion.carno.net.au> Hi, I need to run a remote program from a server that I have access rights to. I want to be able to do this from within in my python script and I want to use ssh (or anything else that will work). However, doing something like: ssh -l user host "/path/to/program" prompts for a password and I don't know how to supply one via a python script. Is there an easy way out? Can I log onto to the other machine via ssh somehow? Does a python script support this? Thanks! Steve From niemeyer at conectiva.com Sat Dec 13 17:11:12 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 13 Dec 2003 20:11:12 -0200 Subject: ANN: lunatic-python 0.1 In-Reply-To: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> References: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> Message-ID: <20031213221111.GB18920@burma.localdomain> > Accessing above with default IE6 brings up Untrusted > Certificate page. With choices Proceed, Stop, > AddCertificate (to root table). It seems conectiva issued > itself its own certificate. I hope this is just silliness > rather than a devious attempt to get people to accept its > self-certification, which I was not about to do. I know This is mostly a developers site. The https server is used just to protect passwords from being sent as plain text. Also, this is not silliness, and neither an attempt to get people to do anything. It's just "do what you can, with what you have, where you are". > enough that I thought it probably safe to proceed without > adding cert, but not enough to be sure. Some people would > stop there, and I might have on another day. I recommend > you take this up with conectiva. I have mentioned this in the past, and will mention again now. Thanks. -- Gustavo Niemeyer http://niemeyer.net From mertz at gnosis.cx Fri Dec 12 02:52:32 2003 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Fri, 12 Dec 2003 02:52:32 -0500 Subject: Generator state/parameters References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> <7xisknr9nm.fsf@ruckus.brouhaha.com> <95aa1afa.0312112244.3baf7883@posting.google.com> Message-ID: |mertz at gnosis.cx (David Mertz, Ph.D.) wrote: |> >>> def echo(): |> ... message = [None] |> ... while message[0] != "EXIT": |> ... yield message |> ... |> >>> for mess in echo(): |> ... if mess[0] is not None: print mess[0] |> ... mess[0] = raw_input("Word: ") michele.simionato at poste.it (Michele Simionato) wrote previously: |A more verbose but arguably more elegant way would be to wrap the |generator in a class. Let me repost some code I wrote some time ago. |class MyIterator(Iterator): | def __gen__(self): | self.x=1 | yield self.x # will be changed outside the class | yield self.x | |iterator=MyIterator() |print iterator.next() |iterator.x=5 |print iterator.next() I don't disagree, of course, with Michele's class-based approach. For something fleshed out, his style lets you do a lot more with the underlying class. But there *is* something awfully elegant about the function-like definition syntax of simple generators. Doing what I do in the simple example--yielding a mutable object, and manipulating that object outside the generator--feels very Pythonic to me. I use a list for this, but a different mutable object would work similarly (a dictionary, instance, shelve, etc.) But obviously, keep both styles in mind; either might be a good solution to a problem. It just depends on your needs and coding style. Yours, David... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From fredrik at pythonware.com Sat Dec 13 07:13:24 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Dec 2003 13:13:24 +0100 Subject: hex and little endian References: Message-ID: Matteo Memelli wrote: > I'm trying to convert an hex address like 0xbfffe2f1 in little endian > format \xf1\xe2\xff\xbf. Is there any funcion that can make this? >>> import struct >>> struct.pack(" Whe I try to code somethig like this: > "\x%s\x%s\x%s\x%s" % (string1, string2, string3, string4) > I obtain this error: > ValueError: invalid \x escape > and if I escape the charachter "\" making something like this: > "\\x%s\\x%s\\x%s\\x%s" % (string1, string2, string3, string4) > It works but the resulting string is not an hex representation "\x" is used in string literals; it has no special meaning when it's used in a string object. From garabik-news-2002-02 at kassiopeia.juls.savba.sk Thu Dec 11 07:28:35 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 11 Dec 2003 12:28:35 GMT Subject: seek in a zip file?? References: Message-ID: Enrique wrote: > hello all! > i?m working with big size files, to maintain them, it would be better to > compress the files. > to recover a little part of the big file, how can i extract that little > parte instead of the whole file that will bring a lot of time? > Can i know the offset in a zip file?? i know the offset in the big one. > Any idea will be welcome. > I used dictzip for the same purpose, and it works well. download serpento from http://melkor.dnp.fmph.uniba.sk/~garabik/serpento/ and look for dictzip module (compress the files with dictzip from dictd package) -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From jacek.generowicz at cern.ch Tue Dec 9 16:31:15 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 09 Dec 2003 22:31:15 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: "Terry Reedy" writes: > "Jacek Generowicz" wrote in message > news:tyfy8tmz7hq.fsf at pcepsft001.cern.ch... > > "Terry Reedy" writes: > > > Can any of your callables be memoized by list rather than dict? > > > (ie, any count or restricted int args?) > > > > You've lost me there. > > Lookup tables. Dicts can memoize any function. Lists can memoize or > partially memoize functions with one or more periodic domains. Perhaps I am > being too obvious or simple for *you*, but I have seen people memoize fib() > or fac() with a generic dict-based wrapper, which is overkill compared to a > simple list. The arguments passed to the functions I have memoized are usually types, so, no, I cannot memoize them by list. > In another post, you said > > > If I want to compete on speed with C++, I'm > >simply going have to eliminate Python bytecode from my inner loops[*]. > > [*] Unless my overall algorithm is completely wrong, of course. > > For speed, you need to eliminate *executed* and *expensive* bytecodes, not > static, possibly skipped-over, bytecodes. I'll take that as what you meant. > It is certainly what our comments are aimed at. Hence my other suggestion > to eliminate a layer of (expensive) function calls by combining value > calculation and storage in one function (more space, less time). You are suggesting that I hand-memoize my functions, rather than using the generic memoizer I posted at the top of the thread? in order to save, in the case of cache misses, the function call overhead to the memoized function? If I had a high proportion of cache misses, then I suspect that would be worth while. In my case, however, I doubt that would have any appreciable effect. Almost all the calls to the memoized functions are cache hits, so effectively there is no value calculation ... it's pretty much all lookup, so my "expensive" function is *effectively*: def proxy(*args): try: return cache[args] except KeyError: pass (where proxy is a closure over cache). Yes, there is something other than "pass" in the handler, but we (essentially) never go there. There's really not much left to play with (though I'm open to suggestions), which is why I wanted to try recoding in C. From blk at srasys.co.in Thu Dec 4 03:09:10 2003 From: blk at srasys.co.in (bala) Date: Thu, 4 Dec 2003 13:39:10 +0530 Subject: I want to know to create our own TestResult Class Message-ID: <004701c3ba3d$e56c0960$440210ac@Bala> Hi, I want to know how to Create our Own TestResult Class...Shall we override the method in the Unitest.TestResult class.If so give some examples... Shall i have my own method in the TestResult Class.... If...so give some example and also how to print the UserDefined TestResult class ..... Regards Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Mon Dec 15 12:55:27 2003 From: bokr at oz.net (Bengt Richter) Date: 15 Dec 2003 17:55:27 GMT Subject: Simple question from Python Newbie References: <83eqtvgdadtv80564iiv8t83ubqts4fh7e@4ax.com> Message-ID: On Sun, 14 Dec 2003 20:34:34 -0800, Tim Roberts wrote: >"Phil D." wrote: >> >>Hello Python Hackers! >> >>I just started working with Python a few days ago and have a simple >>question that I can't seem to figure out. I am trying to build an >>application to monitor my mouse moving habits while I'm surfing >>the web for a project at MIT and I can't seem to figure out how >>to capture mouse clicks. A lot will depend on what you mean by "mouse moving habits" ;-) Do you really mean you want to track your surfing? Or are you interested in such things as copy/paste or drag/drop from the browser to other apps? Be prepared to search for unique title bar text and such kludging to identify windows, etc. ;-/ > >Actually, this is not a particularly simple question. The issue is that it >isn't related to Python at all: this is an operating system issue. An >application is expected to be interested only the events that relate >directly to that application. Doing so on a system wide basis is usually >only interesting for toy apps, such as the one you want to build. > >Fortunately, Windows provides a way to do that: it's called a "hook". In >this case, what you want is the "journal record hook" (WH_JOURNALRECORD), >which gets all key and mouse events in the system. This requires a >callback, which means it needs C help. I don't know if it is implemented >in any of the Win32 extensions; I will have to investigate that (and hope >someone like Mark Hammond posts the canned answer). I don't have a canned answer, but I think the OP will want to look at the docs for HHOOK SetWindowsHookEx( int idHook, // type of hook to install HOOKPROC lpfn, // address of hook procedure HINSTANCE hMod, // handle to application instance DWORD dwThreadId // identity of thread to install hook for ); (for which WH_JOURNALRECORD is one of many possible idHook values to pass). Seems like WH_CBT and/or WH_MOUSE might be useful to consider also. I imagine there will be some "interesting" problems when you start monitoring events from multiple threads and processes. If I had to write it, I think I would make sure I understood the spy sample app that comes with MSVC++6.0, of which it is said """ Spy demonstrates the following techniques: Using a system message hook. Using the WM_COPYDATA message to pass data to another application. Reading and writing the registry. Creating a thread. Creating a DLL for the hook. """ Then decide how I really want to access the data. And/or control the whole thing through a python module, so you could import pyspy in a separately running python process and monitor all the mouse activity in some sensible way. Maybe so the monitoring thread could hang on a queue until there was synchronized buffered data available to grab. If you (OP) describe what you'd like a hypothetical pyspy module to do (and its interfaces), that might be a good way to communicate your project goals. One thing to decide is how to specify what you are interested in and what you want to ignore. Run spyxx.exe (tool that comes with MSVC6.0) for ideas. > >>Thoughts anyone? What's the easiest way to get mouse clicks outside of a GUI? Raw mouse clicks won't mean all that much in terms of monitoring "browsing habits," unless you can know what windows and menus and widgets are being accessed, and what a click means. > >Your terminology is a bit confusing. The entire desktop is "a GUI". What >you really want is to get mouse clicks outside of your own process. And probably not just mouse clicks, so what hooks to use will depend on what information is really sought. Regards, Bengt Richter From mark at mceahern.com Wed Dec 31 14:10:44 2003 From: mark at mceahern.com (Mark McEahern) Date: Wed, 31 Dec 2003 13:10:44 -0600 Subject: Maybe a stupid idea In-Reply-To: <56f42e53.0312310949.39826ffd@posting.google.com> References: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: <1072897844.27658.282.camel@dev.internal> On Wed, 2003-12-31 at 11:49, sebb wrote: > I'm kind of newbie to programming, but I thought of something and I > want some opinions on that. > > It's about a new instruction block to do some cycles. Regarding the subject, I find it comforting to think that all ideas are stupid. Just like all questions are. ;-) Heh, I don't really know what you mean by cycle. It'd be helpful to know what problem you're trying to solve. Anyway, consider this admittedly pointless example: #!/usr/bin/env python import sys def makecycle(doUp, doDown): def cycle(start, end): for i in range(start, end): yield i, doUp for i in range(end, start, -1): yield i, doDown return cycle def doUp(i): sys.stdout.write('^') def doDown(i): sys.stdout.write('v') cycle = makecycle(doUp, doDown) for i, func in cycle(1, 10): func(i) Cheers, // m From mfranklin1 at gatwick.westerngeco.slb.com Mon Dec 15 16:53:14 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 15 Dec 2003 21:53:14 +0000 Subject: Python in a spreadsheet In-Reply-To: <3064b51d.0312151318.277c8c06@posting.google.com> References: <3064b51d.0312151318.277c8c06@posting.google.com> Message-ID: <1071525193.1096.9.camel@m-franklin> On Mon, 2003-12-15 at 21:18, beliavsky at aol.com wrote: > Is it possible to call a Python function from Calc (the Open Office > spreadsheet) or Microsoft Excel? Are their web sites or books > describing how to do this? > > I would prefer not to write any more VBA :). Yes to both I believe... the first with the python openoffice bridge Python-UNO google for 'python openoffice' scores about 115000 hits The second would I guess be do-able with the win32 extensions..... google 'win32 extensions python' about 34000 hits Happy reading... Martin. -- Martin Franklin From imbosol at aerojockey.invalid Tue Dec 23 18:19:40 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 23 Dec 2003 23:19:40 GMT Subject: return statement in functions References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: Francis Avila wrote: > > > > hokiegal99 wrote in message > <93f5c5e9.0312221718.23e42dac at posting.google.com>... >>I was told earlier (w/o explanation) that functions should return >>something. I was under the impression that it was OK with Python to >>leave the return statement off. > > Functions return something in Python, by definition. If you leave the > return statement off, Python inserts an implicit 'return None' to the end of > the text of your function. It seems that Python inserts the implicit "return None" even if you do return a value. Python 2.2.3c1 (#12, May 27 2003, 21:32:04) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def a(): ... return 1 ... >>> import dis >>> dis.dis(a) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 (1) 9 RETURN_VALUE 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> today's-trivia-tidbit-brought-to-you-by-truly yr's -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From __peter__ at web.de Tue Dec 9 11:51:01 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Dec 2003 17:51:01 +0100 Subject: regex confusion References: Message-ID: John Hunter wrote: > > In trying to sdebug why a certain regex wasn't working like I expected > it to, I came across this strange (to me) behavior. The file I am > trying to match definitely contains many instances of the letter 'a', > so I would expect the regex > > rgxPrev = re.compile('.*?a.*?') > > to match it the string contents of the file. But it doesn't. Here is [...] > I read the regex to mean non-greedy match of anything up to an a, > followed by non-greedy match of anything following an a, which this > file should match. There is a nice example where non-greedy regexes are really useful in A. M. Kuchling's Regex Howto (http://www.amk.ca/python/howto/regex/regex.html) > Or am I insane? This may be off-topic, but the easiest if not fastest way to find multiple occurences of a string in a text is: >>> import re >>> r = re.compile("a") >>> for m in r.finditer("abca\na"): ... print m.start() ... 0 3 5 >>> Peter From jroznfgre at jngpugbjreQBGbet.cy Tue Dec 16 05:04:40 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Tue, 16 Dec 2003 11:04:40 +0100 Subject: I am lookin' for Python magazines Message-ID: I would like to buy a subscription to some good Python oriented magazines. I found only ZopeMagazine. Do you know any other worth to buy? -- JZ From harry_chillboy at rediffmail.com Tue Dec 16 03:24:27 2003 From: harry_chillboy at rediffmail.com (Harish) Date: 16 Dec 2003 00:24:27 -0800 Subject: How to access MFC classes in Python using SWIG ? Message-ID: I am using Python2.3 version with SWIG-1.3.19 to access C++ interface provided by a DLL. Some of its function returns MFC class objects like CString , CMap. I tried to generate wrapper for these classes using SWIG by including respective header files in .i file. But it doesn't work. Swig reports hundreds parsing errors in MFC's file. Could you give me any directions.. Thank you in anticipation Harish From gb at cs.unc.edu Tue Dec 9 11:31:52 2003 From: gb at cs.unc.edu (Gary Bishop) Date: 9 Dec 2003 11:31:52 -0500 Subject: Help on MSAA References: Message-ID: <3fd5f8f8_1@news.unc.edu> Mythili Madhav wrote: > I need to write a wrapper around MSAA in Python for having my own control > classes like MyApplication, MyWindow, MyPushButton etc which I think is > basically to subclass from MSAA's classes. I have downloaded pyAA but I > don't know how and from what to subclass. Has anybody worked on this? If > yes, kindly revert. pyAA is a low-level wrapper for MSAA and WindowsEvents which are two really tricky to use APIs. What is there is just what we have needed so far. Look at the bottom of pyAA.py at the example of watching Internet Explorer. It demonstrates a primitive series of classes that go from AAbase to a WindowWatcher, to AAapp and on to AAIE (a wrapper for Internet Explorer). gb From claird at lairds.com Thu Dec 11 12:46:08 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 17:46:08 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> Message-ID: In article <7xad5z1jq5.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: . . . >> but don't take my word for this, why don't you see what you like the best? >> >> http://www.wxpython.org/ >> http://www.gtk.org/ >> http://www.scriptics.com/ >> http://www.trolltech.com/ > >I don't know what I can really tell from these without more experience >with them. In particular, which is the most solid and reliable across >a wide range of Windows versions (95, 98, ..., XP whatever)? That >matters too. . . . I want to say a few words about portability and comparisons. I'm very reluctant to advise "see what you like the best" in regard to GUI toolkits the way I do for high-level languages. We all know it's entirely realistic to counsel a newcomer, "Give yourself an hour, and you can download and install Python (or Perl, or Ruby, or ...) and try it out for yourself. You'll get a good first impression of how the language operates." It's not the same, though, for C# vs. Java, or the GUI toolkits. There's a considerably greater start-up cost involved in exercising them meaning- fully. You really are best off with advice from a live person whom you trust. You probably must "see what you like the best" ultimately, because your requirements are unlikely to duplicate those of your potential mentors. We can, however, help focus your search--and I'm posting because I think we should. isn't the URL I recommend; Scriptics stopped doing business under that name three and a half years ago. is a safe choice. You ask, "which is the most solid ...?" for Windows. I *am* a fan of Tkinter, and the answer to this question explains much of that. Tkinter's portability story is at least as good as that of any of the alternative toolkits, and, I argue, better than all but Qt (depending on your sentiments about licensing). You're likely to get quite a range of testimony in this regard; I certainly know GTK+ experts who seem quite productive under Windows. In my experience, though, Tkinter just *thumps* all the others, in regard to the robustness of its portability. How's it happen you're not talking about Java (Jython, say)? In fact I think it wouldn't be right for you; I'm surprised, though, not to hear you mention it. -- Cameron Laird Business: http://www.Phaseit.net From CousinStanley at hotmail.com Wed Dec 3 09:56:49 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Dec 2003 07:56:49 -0700 Subject: Can Python be run off of a CD-ROM? References: <7Zlzb.290907$ao4.1008621@attbi_s51> Message-ID: | I tried to download KNOPPIX last night, and to no avial. | The knoppix servers are currently restricted from allowing downloadings. | DOH! I tried to find an available mirror someplace, but had no luck. BJ .... Knoppix 3.3 is available on CD from CheapBytes.Com for $5 US .... http://www.cheapbytes.com I was lucky enough to download an earlier version, and although I have a fairly fast connection, I will order the next one pre-burned on CD .... -- Cousin Stanley Human Being Phoenix, Arizona From hokiegal99 at hotmail.com Sat Dec 13 20:49:44 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Sat, 13 Dec 2003 20:49:44 -0500 Subject: Find and Delete all files with .xxx extension Message-ID: <3FDBC1B8.4010205@hotmail.com> The below code does what I need it to do, but I thought that using something like ext = os.path.splitext(fname) and then searching ext[1] for '.mp3' would be a much more accurate approach to solving this problem. Could someone demonstrate how to search ext[1] for a specific string? This script works great for deleting illegal music on user machines ;) Thanks!!! import os, string setpath = raw_input("Enter the path: ") #This can be hard coded. for root, dirs, files in os.walk(setpath, topdown=False): for fname in files: s = string.find(fname, '.mp3') if s >=1: fpath = os.path.join(root,fname) os.remove(fpath) print "Removed", fpath, "\n" From arjen.dijkstraNoSpam at hccnet.nl Thu Dec 18 03:44:24 2003 From: arjen.dijkstraNoSpam at hccnet.nl (duikboot) Date: Thu, 18 Dec 2003 09:44:24 +0100 Subject: Installing tcl/tk on Linux References: Message-ID: <3fe16951$0$43998$e4fe514c@dreader9.news.xs4all.nl> I have been struggeling with this too for a long time. But I see you use Red Hat, so why don't you just download the rpm packages, http://www.python.org/2.3.2/rpms.html and install these. It worked for me. Good luck, Arjen From skip at pobox.com Mon Dec 22 16:16:41 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 22 Dec 2003 15:16:41 -0600 Subject: Counting how many chars equal to a given char are in the beginning of a string In-Reply-To: <21bb8d55.0312221204.51d86182@posting.google.com> References: <21bb8d55.0312221204.51d86182@posting.google.com> Message-ID: <16359.24377.5101.789601@montanaro.dyndns.org> Andrei> Given a string s and a char c, is there a short & elegant way to Andrei> determine how many consecutive occurences of c are in the Andrei> beginning of s ? Andrei> For example if s = ">>>>message1" and c = ">" then the number I Andrei> am looking for is 4 (the string begins with 4 '>'). How about: def howmanyatstart(s, pfx): return (len(s) - len(s.lstrip(pfx)))/len(pfx) ? This works for prefixes which are longer than a single character: >>> howmanyatstart(">>>>message1", '>') 4 >>> howmanyatstart("bobbobbob>>>>message1", 'bob') 3 Skip From gh at ghaering.de Thu Dec 4 11:13:02 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2003 17:13:02 +0100 Subject: stddev bug in util.py In-Reply-To: <000a01c3ba80$515103f0$421210ac@telesyn.corp> References: <000a01c3ba80$515103f0$421210ac@telesyn.corp> Message-ID: <3FCF5D0E.50500@ghaering.de> Ted Nienstedt wrote: > Gentlemen, et al: > > The stddev function in the current, as of 11/03, utils.py module has a > bug. Corrected code excerpt below, in red; comments in blue. [...] Thanks for informing the whole Python community of this bugfix in your software, Ted. -- Gerhard From bucodi_no_spam at ahoo.fr Wed Dec 24 05:51:02 2003 From: bucodi_no_spam at ahoo.fr (Rony) Date: Wed, 24 Dec 2003 11:51:02 +0100 Subject: replace line #1 with "newline\n" in text file References: <3fe955b8.0@news1.mweb.co.za> Message-ID: Group : comp.lang.python > Hiya, > I am trying to replace the first line of a config file.. with a new string > been googlizing and reading the python manual.. but can't find what I need.. > it's all rubbish about bits and bytes etc.. > > > Perhaps this is what you want ? flag=0 newlines = [] lines = open('test.txt','r').readlines() for l in lines: if flag==0: newlines.append('\n') flag=1 else: newlines.append(l) open('test.txt','w').writelines(newlines) Rony -- Rony /_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ / bucodi_no_spam at yahoo.fr (delete _no_spam) / | www.bucodi.com - My work \ www.ifrance/karamusique -- My hobby \_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/ From whisper at oz.net Fri Dec 26 19:26:38 2003 From: whisper at oz.net (David LeBlanc) Date: Fri, 26 Dec 2003 16:26:38 -0800 Subject: _sre Import Error Python 2.3.3 Final Win98SE In-Reply-To: Message-ID: > > The windows installer added a couple of environmental variables: > PYTHON_LIB > looked suspect: c:\Python23\Libs\python22.lib > Better idea to change the above to c:\Python23\Libs\python23.lib and see how that works! Mixing distros is not a good idea! FWIW, I have (Wyse installer installed) Python 2.3.1 on my Windows 2000 box and have no PYTHON_LIB variable in my environment. Dave LeBlanc Seattle, WA USA From hans at zephyrfalcon.org Mon Dec 1 12:28:22 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 01 Dec 2003 12:28:22 -0500 Subject: passing global data to a function In-Reply-To: <3064b51d.0312010855.66f4e2@posting.google.com> References: <3064b51d.0312010855.66f4e2@posting.google.com> Message-ID: <3FCB7A36.8070402@zephyrfalcon.org> beliavsky at aol.com wrote: > How can I pass global data to function stored in a separate file? > For example, in file "funk.py" is the code > > ipow = 2 > def xpow(xx): return xx**ipow > > and in "xfunk.py" is the code > > from funk import xpow,ipow > xx = 4.0 > print xpow(xx) > ipow = 3 > print xpow(xx) Try: import funk xx = 4.0 print funk.xpow(xx) funk.ipow = 3 print funk.xpow(xx) Of course, there might be a better way to do this than with globals... a class comes to mind as one possible alternative. HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From gh at ghaering.de Mon Dec 1 10:31:06 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 01 Dec 2003 16:31:06 +0100 Subject: Turning off warnings In-Reply-To: References: Message-ID: <3FCB5EBA.9010501@ghaering.de> Paulo Pinto wrote: > [...] Now when I use os.tempnam() or os.tmpnam() > I get a runtime warning about security issues. [...] > > Is there any way to turn the message off? >>> import os, warnings >>> warnings.filterwarnings("ignore", "tempnam") >>> os.tempnam() 'C:\\DOCUME~1\\GERHAR~1.HAE\\LOCALS~1\\Temp\\2' -- Gerhard From martin at v.loewis.de Fri Dec 5 13:05:02 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Dec 2003 19:05:02 +0100 Subject: gettext crazy question References: <43e3984e.0311201935.64aac584@posting.google.com> <43e3984e.0311230527.74eed7a3@posting.google.com> <43e3984e.0312030436.3640d21b@posting.google.com> <43e3984e.0312050048.1948e841@posting.google.com> Message-ID: ulysses_dm at yahoo.com.cn (ulysses) writes: > I post a bug report with demo app in python in SF. > Track Number is 854589 ,subject is "Can't use GetText in win32,i386" . > Please help me. Thanks. See the SF report. You need to open mo files in binary mode. Regards, Martin From __peter__ at web.de Sun Dec 7 12:39:54 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Dec 2003 18:39:54 +0100 Subject: Instance Exception Oddity: Implicit and Explicit not the same? References: Message-ID: RT Lange wrote: >>>> class E1(Exception): pass > >>>> class E2(E1): pass > >>>> i = E2('foo') >>>> raise E1(i) > Traceback (most recent call last): > File "", line 1, in ? > raise E1(i) > E1: foo >>>> raise E1, i > Traceback (most recent call last): > File "", line 1, in ? > raise E1, i > E2: foo >>>> > > Is there a reason the exception type is not the same? > Is this behavior something that should be expected? This is interesting. I thought of raise E, o # 1 and raise E(o) # 2 as equivalent. Well, until today: "If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value." (quoted from http://www.python.org/doc/current/ref/raise.html) So, if isinstance(o, E), the first form is indeed equivalent to raise o and your code works as advertised. Peter From donn at u.washington.edu Mon Dec 15 12:41:24 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 15 Dec 2003 09:41:24 -0800 Subject: Python vs Unix shells References: <2ae25c6b.0312130213.2f5452c6@posting.google.com> <2ae25c6b.0312140316.77f7059f@posting.google.com> Message-ID: In article , claird at lairds.com (Cameron Laird) wrote: > ... In other articles, I've said a few > words about the difficulty of writing good examples for an > audience of systems administrators; I do find it hard not > being "maybe a little artificial" (I appreciate your gentle > touch), without complexification that loses the reader. Maybe the category is a little artificial, in that system administration isn't really a computer programming domain like numeric, hardware control, rendering, web publishing. I suppose that's part of your point, when you talk about writing your own tools rather than buying packaged solutions. Not many good packaged solutions for Miscellaneous Little Tasks. Donn Cave, donn at u.washington.edu From rstephens at vectron.com Tue Dec 23 08:32:25 2003 From: rstephens at vectron.com (Ron Stephens) Date: 23 Dec 2003 05:32:25 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in message news:... > Anyone used Tkinter on 10.3 yet? I have been using Tkinter on Mac OS X 10.3 and it works fine. I havev not really stressed it however, just running IDLE, and some other programs that use Tkinter GUI's. No heavy lifting, I'm afraid. Still, come on in, the water feels fine ;-))) From aahz at pythoncraft.com Wed Dec 10 10:28:01 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Dec 2003 10:28:01 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: In article , Jacek Generowicz wrote: > >I tried something similar, namely inlining the > > try: return cache[args] > except KeyError: return cache.setdefault(args, callable(*args)) > >rather than using proxy. This gives a little over a factor of 3 >speedup, but it's not something I can use everywhere, as often the >proxy is called inside map(...) Why are you using map()? Generally speaking, map() won't be any faster than a for loop. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From ny_r_marquez at yahoo.com Wed Dec 10 09:01:29 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 10 Dec 2003 06:01:29 -0800 Subject: Explorer Shell extensions are here! References: <8a27e309.0312081137.18c2810b@posting.google.com> <87brqiszbc.fsf@pobox.com> Message-ID: <8a27e309.0312100601.29984d64@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87brqiszbc.fsf at pobox.com>... > ny_r_marquez at yahoo.com (R.Marquez) writes: > You can do shell extension stuff quite easily with ctypes, too. > There's a good O'Reilly book on the subject (based on VB, but that > doesn't matter). Use the CVS version, not the tarball, there's at > least one important COM bug fixed there. > > One tip: some common COM interfaces don't have type libraries, but > it's easy to write your own interface specifications for ctypes, just > by following the very readable output of the ctypes script (equivalent > of gen_py in win32com) that usually does this job for you. John, I appreciate the tip. I'll have to take a deeper look at ctypes as well. -Ruben From alan_salmoni at yahoo.com Fri Dec 12 06:56:51 2003 From: alan_salmoni at yahoo.com (Alan James Salmoni) Date: 12 Dec 2003 03:56:51 -0800 Subject: Python progamming certification References: Message-ID: Actually, this does raise a serious question - would there be any use in having such a scheme. As I am in the job market (not necessarily for Python!), I'm finding it hard to convince people that I *can* write in Python (note: I didn't say my programming was any good ;)), even with my own open source project. A lot of suits and personnel type people just don't consider FOSS work to be of any value (but then would I want to work for such a company...?), rather commercial experience only being the thing of worth. A certification or accredidation might go some way to solving this, and it might have more status if it were "led" by the PSF, PBF or whoever. And like someone else in the thread suggested, it could be a way of generating income... Alan. Apollo <_ at _._> wrote in message news:... > Hi All, > > Is there a Python programming certification like Sun's Java certificates? > > Thanks in advance, From claird at lairds.com Thu Dec 11 17:02:02 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 22:02:02 -0000 Subject: Python code to replace shell scripts References: Message-ID: In article , Daven Nair wrote: >Hi, > >I would like to know if Python supports codes similar to shell scripts: > >count=`ps -ef|grep "pattern"|wc -l` >for count in `echo $count` > do > done >fi > >Can I export a variable say var from os.system("var=`ps -ef|grep pattern|wc >-l`") . . . While I don't understand your questions, I suspect the series I've launched with will interest you. When you write, "Can I export a variable ...", are you asking that the result of an external process be bound to a Python name (or variable), OR that a Python process export a "shell" variable to its environment, OR ...? -- Cameron Laird Business: http://www.Phaseit.net From jsbenson at bensonsystems.com Sun Dec 7 15:41:24 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Sun, 7 Dec 2003 12:41:24 -0800 Subject: apologies for a previous post mistitling Message-ID: <052f01c3bd02$7c280e50$210110ac@jsbwxp3> Hi, "Re: how to display clock?, plus musings on the Nerd factor in Python (John Benson)" was actually split up into two postings. The "Nerd factor" comments ended up in "Thanks for all the help". From x at x.com Fri Dec 12 20:30:11 2003 From: x at x.com (Apollo) Date: Sat, 13 Dec 2003 01:30:11 GMT Subject: Python progamming certification In-Reply-To: References: Message-ID: <3FDA6B81.1060009@x.com> Mark Carter wrote: >>consider FOSS work to be of any value (but then would I want to work >>for such a company...?) > > > At the end of the day, aren't we all wage slaves anyway? > > >> rather commercial experience only being the > > > I had the same problem with programming in academia; because it's not > "real", or something. Makes me feel like punching someone in the neck. I don't know but I think I have done more interesting, complex and challenging programs in schools than what I am doing now in the profession. From bkelley at wi.mit.edu Thu Dec 4 12:02:15 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 04 Dec 2003 12:02:15 -0500 Subject: Building a GUI agnostic database application In-Reply-To: <3fcdd2ba@mail.netspeed.com.au> References: <3fcd9d2a@mail.netspeed.com.au> <3fcdd2ba@mail.netspeed.com.au> Message-ID: <3fcf6861$0$563$b45e6eb0@senator-bedfellow.mit.edu> Rasjid Wilcox wrote: >>Why not just make a database model that doesn't know anything about the >>GUI? The model can a python compliant database driver (say odbc or >>whatnot) and you can supply the proper business logic in a concise model. > > > This is _precisely_ what I was planning to do. > > The issue is that the 'client' program (GUI or text based interface or some > other scripted component or whatever) may or may not be running on the same > machine as the 'business logic' backend component, which may or may not be > on the same machine as the database. > This can still be handled the same way. Version I View ^ | v Controller <--> Model Version II View ^ | v Controller <-> (Adapter <-> wire protocol <-> Model) Now, if the Adapter behaves exactly the same as the oroginal Model you are in luck and you can replace I with II without ever having to change the view and the controller. Of course, this means you will need a good Model to start with the enables it being used as an Adapter. A good wire protocol that I have used in the past is pyro (pyro.sourceforge.net) that almost seamlessly wraps python objects and can use them remotely. As long as you don't use your model in ways that pyro can't you can transparently replace the model with the remote calls. Brian From bkelley at wi.mit.edu Thu Dec 11 08:23:32 2003 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 11 Dec 2003 13:23:32 GMT Subject: What GUI toolkit looks the best? In-Reply-To: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I've been approached about writing a Windows app which will need a > really professional looking GUI. Forget TKinter, this has to actually > look good (real artists will be available to get the visual stuff > right). Assuming I write in Python, what's the best toolkit to use? > Some cost in implementation pain is tolerable if the finished > interface looks better as a result. It would be nice if the toolkit > runs on multiple platforms rather than being Windows-only. Why forget Tkinter? I've seen Tkinter applications that look incredibly fabulous. A lot depends on what you are trying to do. If you are making a graphics-heavy application then Tkinter's canvas is pretty sweet. I also think IDLE looks pretty good. > I'm thinking Glade. Is that reasonable? I don't know squat about > Windows and haven't done much fancy GUI programming since the early X > days. Glade isn't a GUI, it is a GUI builder that uses GTK. In my experience, GTK doesn't look quite right on windows boxes, especially the menus. Of course I have the same basic view of Qt and Swing so know you know my biases. I tend to use Tkinter for canvas heavy applications and wxPython for other stuff. As for application building, here are my rankings 1 Emacs :) 2 Glade with libglade and Mitch Chapman's python libglade wrapper 3 BlackAdder with Qt 4 Boa-constructor (largish learning curve here I think) 5 wxGlade (layout isn't quite right) So let me ask what kind of application are you building? The bottom line is that I have seen great looking and really poor looking apps in all of these gui's. Here is my humble opinions in a nutshell (missing a lot here): wxPython has a grid control to die for and many, many classes, good printer support and looks like a native GTK app on Linux and a native app on windows and macintosh. Qt is better for developing - it has a better class structure and I tend not to have to look up docs as often and can look really, really nice. Tkinter has a killer canvas and great postscript output. GTK is really quite fast. but don't take my word for this, why don't you see what you like the best? http://www.wxpython.org/ http://www.gtk.org/ http://www.scriptics.com/ http://www.trolltech.com/ Speaking of Qt, does anyone want to make a python binding to jakasha? http://www.jahshaka.com/ Brian From peter at engcorp.com Wed Dec 3 09:22:12 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Dec 2003 09:22:12 -0500 Subject: python's threading has no "interrupt"? References: <9btu91-s04.ln1@beastie.ix.netcom.com> Message-ID: <3FCDF194.EFF269A@engcorp.com> Aahz wrote: > > In article <9btu91-s04.ln1 at beastie.ix.netcom.com>, > Dennis Lee Bieber wrote: > > > >There's the first point of departure: Python threads (as long as you > >aren't in a C language number crunching extension) are preemptive > >scheduled, on something like a 10-20 byte-code interval. Cooperative > >basically means /you/ had to handle the scheduling of threads; in > >Python you don't, it happens automatically. > > Actually, that's not really correct. Cooperative threading means that > there's no way to force a thread to yield up a timeslice, which is > precisely the way Python works, because any bytecode can last an > arbitrarily long time (consider 100**100**100). It is true that the > Python core does switch between bytecodes, but that should not be > considered preemptive in the traditional sense. I would say that Python is actually much closer to preemptive in the traditional sense than it is to being cooperative. Yes, some bytecodes could have almost unbounded duration under some (perverse?) conditions, but the parallel between bytecodes and opcodes in machine language is very strong, and you can't interrupt (most) machine opcodes either... they just take much less time to execute, and their durations generally span many times fewer orders of magnitude... Thinking of Python as preemptive, but in a "softer" sense, is in my opinion the most useful view... -Peter From wtrenker at shaw.ca Wed Dec 24 06:32:12 2003 From: wtrenker at shaw.ca (Bill Trenker) Date: Wed, 24 Dec 2003 11:32:12 +0000 Subject: ungetch in Python In-Reply-To: References: Message-ID: <20031224113212.31c0eb2c.wtrenker@shaw.ca> Scott Fenton wrote: > I'm writing a small parser for a minilanguage in Python, Hi Scott, You might want to have a look at "pyparsing -- an object-oriented approach to text processing in Python". http://pyparsing.sourceforge.net The Python source code is only 34K, or just under 1000 lines of code, so it may be small enough to include with your project and save you the trouble of writing yet another parser. Regards, Bill From sunas at web.de Thu Dec 11 03:52:49 2003 From: sunas at web.de (Alexander Schwaigkofler) Date: Thu, 11 Dec 2003 09:52:49 +0100 Subject: numarray doesn't work on win2k References: <3fd82588$0$18044$3b214f66@aconews.univie.ac.at> Message-ID: <3fd82ffd$0$17706$3b214f66@aconews.univie.ac.at> "Thomas Heller" schrieb im Newsbeitrag news:... > "Alexander Schwaigkofler" writes: > [..] > You need a working C compiler. > > Thomas Is it possible to work with an other Linker than cl.exe from MS? I have alread installed cygwin. Alexander From dw-google.com at botanicus.net Mon Dec 8 14:50:00 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 8 Dec 2003 11:50:00 -0800 Subject: Understanding and working with __metaclass__ Message-ID: <99dce321.0312081149.2a32575d@posting.google.com> Hi there, I've been sitting on the __metaclass__ feature for about 2 weeks now, and haven't really got that far with it. It looks like a very powerful tool, and I think I have even already identified places in my code where I could use it quite effectively, but I can't quite tell what it is /meant/ to be used for, or indeed what it is popularly used for. Is there a page, posting, or other place I can turn to to get a developer's run-down on the practical uses of __metaclass__? The Python documentation states very clearly what it does, but I fear that journeying off on my own with it will lead to some terrible habit formation, and I already have enough of those to deal with. :) (:set ts=3 ;) Thanks for your time, David. From roy at panix.com Sun Dec 7 22:42:17 2003 From: roy at panix.com (Roy Smith) Date: Sun, 07 Dec 2003 22:42:17 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: In article , "Greg Ewing (using news.cis.dfn.de)" wrote: > Douglas Alan wrote: > > mwilson at the-wire.com (Mel Wilson) writes: > > > >> To me, it's a distinction without a difference. Tuples > >>*act* like immutable sequences, and I use them that way. I > >>don't know, though, that I won't get caught some day. > > > > You'll be fine. The only thing you have to watch out for is that some > > rude folks here might call you names. > > That would add some spice to Python's error messages... > > Python 3.7 (#1, Sep 31 2007, 14:19:37) > [GCC 5.6.7] on slartibartfast > Type "help", "copyright", "credits" or "license" for more information. > >>> t = (1, 3, 77, 654, 8) > Traceback (most recent call last): > File "", line 1, in ? > HumiliationError: The programmer is a pink-faced baboon (tuple used where > list would be more appropriate) In MVP (Microsoft Visual Python), the "auto-correct" function would just silently change the ()'s to []'s as you typed them. If you tried to change them back, clippy would pop up on the screen and say, "You seem to be trying to do something un-pythonic. Would you like some assistance?". If you tried to make clippy go away, it would offer to "install this critical security patch immediately". From bokr at oz.net Fri Dec 19 01:38:59 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Dec 2003 06:38:59 GMT Subject: Default attribute in base class precludes delegation References: <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> <5.2.1.1.0.20031219003155.01fd0830@192.168.0.115> Message-ID: On Fri, 19 Dec 2003 02:33:59 -0300, Gabriel Genellina wrote: >At 19/12/2003 00:02, you wrote: > >>>class Worker: >>> def __init__(self, foo, bar): >>> self.foo = foo >>> self.bar = bar >>> >>>class Base: >>> bar = None >>> >>>class Derived(Base): >>> def __init__(self, worker): >>> self.worker = worker >>> def __getattr__(self, name): >>> return getattr(self.worker, name) >>>w = Worker(1234, 'Hello') >>>print 'w.foo', w.foo # prints 1234 >>>print 'w.bar', w.bar # prints Hello >>>d = Derived(w) >>>print 'd.foo',d.foo # prints 1234 >>>print 'd.bar',d.bar # prints None, I want to get Hello >> >>As you already found out, d.bar looks up Base.bar, and __getattr__ isn't >>invoked (since it is only called if an attribute is *not* found). >> >>The easiest solution might be, to change the name of the attribute 'bar' >>in Worker, since you can modify this class. If at all possible, make sure >>it has no attribute names that are defined in Base also. Is this an >>acceptable solution for you? It sounds cheesy, but it might be better >>than inventing all kinds of twisted code constructs to get around this problem. > >That won't work, unfortunately. Other code expects Derived to have a 'bar' >attribute (since it inherits from Base). > >My workaround was to *really* set an instance attribute 'bar' in Derived, >and try to ensure that it's always in sync with Worker: > > def __init__(self, worker): > self.worker = worker > self.bar = worker.bar > > def setBar(self, bar): > self.worker.bar = bar > self.bar = bar > >This works if a) all people always use setBar on Derived, and b) no one >assigns to worker.bar directly. >I would like another way, more "automatic", where people dont have to >"remember" these rules... >(BTW, the real attribute name is 'title', wich is used all around the >system, that's why it's a bit difficult to assert the above rules everywhere) > > If you change the Derived class in your original post (and above) to: class Derived(object,Base): def __init__(self, worker): self.worker = worker def __getattribute__(self, name): return getattr(object.__getattribute__(self, '__dict__')['worker'], name) I think it will get all the attributes, for better or worse, from worker (and the output you wanted). You'll have to sort out what names you might want to deal with differently, though ;-) Regards, Bengt Richter From Greg.Lindstrom at acxiom.com Fri Dec 19 09:09:32 2003 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Fri, 19 Dec 2003 08:09:32 -0600 Subject: SQL Server Questions Message-ID: Hello- I am connecting to a Microsoft SQL Server (6.0) via Python 2.3 using the MSSQL package and have a question about the database name. This particular database was designed with a two-word name (i.e. "My Database"). When I try to connect using the MSSQL.connect method, I get a syntax error: MSSQL.connect('my_server', 'my_username', 'my_password', 'my database') I get an "Incorrect syntax near My" error. I can't change the name of the database; too many applications are feeding into it. What do I do? Also, I'm connecting to a Microsoft Exchange Mail server using the methods described in Mark Hammond and Andy Robinson's Book "Python Programming on Win 32". My problem is that when I connect to the Exchange Server, a dialog box pops up to verify the connection. Since I'm writing a utility script, I'd just like to connect without a user having to get involved. Is this possible? Thanks for your help --greg ********************************************************************** The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not 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 re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From simonb at webone.com.au Wed Dec 17 16:29:59 2003 From: simonb at webone.com.au (Simon Burton) Date: Thu, 18 Dec 2003 08:29:59 +1100 Subject: Sound generation recommendations? References: Message-ID: On Wed, 17 Dec 2003 10:46:34 -0800, Charles Hixson wrote: > I'm looking for a simple means of generatings sounds. Basically what I > want to do is play music from the information available in sheet music. I [cut] > All the sound modules I've looked at seem to run off of sampled wave forms > ... and this is nearly the opposite of what I want. Hi Charles, take a look at hypersonic: http://arrowtheory.com/software/hypersonic/index.html It's fairly rough around the edges, and the windows port is not ready yet, but it might do what you want. The next big release will be licensed LGPL if that helps. Simon. From roy at panix.com Sat Dec 13 08:38:27 2003 From: roy at panix.com (Roy Smith) Date: Sat, 13 Dec 2003 08:38:27 -0500 Subject: "Do this, and come back when you're done" References: Message-ID: Kamus of Kadizhar wrote: > Is there any way to rewrite each half of the function to run in the > background, so to speak, and then have a master process that waits on > the results? Yup. Two ways in fact. The traditional way would be to fork another process to do the work and have the parent process wait for the child to finish. You'll need to use the fork() and exec() functions that can be found in the os module. The other way would be to do something similar, but with threads instead of processes. The basic flow is the same; you create a thread, have that thread do the stuff that takes a long time, and then rejoin with the primary thread. Of course (just like with child processes), you could have multiple of these running at the same time doing different parts of a parallelizable job. Take a look at the Threading module. I'm intentionally not including any sample code here, because the possibilities are numerous. Exactly how you do it depends on many factors. I'm guessing that doing it with threads is what you really want to do, so my suggestion would be to start by reading up on the Threading module and playing with some examples to get the feel for how it works. Working with threads is becomming more and more mainstream and more operating systems and languages provide support for it, and the programming community at large becomes more familiar and comfortable with the issues involved. From mesteve_b at hotmail.com Wed Dec 24 21:07:42 2003 From: mesteve_b at hotmail.com (python newbie) Date: Thu, 25 Dec 2003 02:07:42 GMT Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: Thanks MIke. I forgot to add another note, by the way, that I received an email from ActiveState correcting me on this. I will add your positive mention to my ultimate decision. "Michael Geary" wrote in message news:vujvlup1v3cs99 at corp.supernews.com... > python newbie wrote: > > Ok, now I'm thinking _not_ Komodo, because it requires ActivePython, > > and I'd prefer to stick with my python.org installation of Python. > > Komodo doesn't require ActivePython. It works fine with the python.org > distribution. > > The Komodo release notes say that some advanced features require > ActivePython, but I would bet that if you install the same extra modules > that ActivePython provides (especially Mark Hammond's extensions on Windows) > it would work just as well. > > > If you still have advice as to what debugger you use for wxPython > > programs, I'd welcome the advice. > > I would suggest trying more than one and see which you like the best. Komodo > is my favorite, but I tried all of the ones people have mentioned in this > thread before settling on it. > > -Mike > > From tjreedy at udel.edu Tue Dec 30 13:26:06 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 13:26:06 -0500 Subject: When to put my modules References: <3ff0e744_1@dns.sd54.bc.ca> <3ff1ab8c_1@dns.sd54.bc.ca> Message-ID: > Okay...so I just need to add paths to the sys.path variable. Seems > simple enough. Thanks. If your modules are specific to an application, adding the application module-dir to the front of sys.path is probably best. If your modules constitute a library that other Python programmers might want to access (such as pygame or numerical), then the package should go in lib/site-packages. TJR From opengeometry at yahoo.ca Sat Dec 13 16:50:40 2003 From: opengeometry at yahoo.ca (William Park) Date: 13 Dec 2003 21:50:40 GMT Subject: Python vs Unix shells References: <2ae25c6b.0312130213.2f5452c6@posting.google.com> Message-ID: In Paddy McCarthy wrote: > This is really a comment on "Python in Systems Administration: Part I > -- Better Scripting" > http://www.samag.com/documents/s=8964/sam0312a/0312a.htm > by Cameron Laird. > > Reading the article, although I am a fan of Python, I kinda take issue > with the example given. It doesn't seem to fit with the concept of > 'many smaller utilities doing one thing well, connected via pipes' What did you expect from a Python consultant? He has the right to make a living and advertise his expertise. -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From beliavsky at aol.com Mon Dec 1 11:55:38 2003 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Dec 2003 08:55:38 -0800 Subject: passing global data to a function Message-ID: <3064b51d.0312010855.66f4e2@posting.google.com> How can I pass global data to function stored in a separate file? For example, in file "funk.py" is the code ipow = 2 def xpow(xx): return xx**ipow and in "xfunk.py" is the code from funk import xpow,ipow xx = 4.0 print xpow(xx) ipow = 3 print xpow(xx) Running Python against xfunk.py, I get the output 16.0 16.0, so the value of ipow in function xpow is not being changed. I want ipow to equal 4 in the 2nd call to xpow, so that the output would be 16.0 64.0 How can this be done? Thanks. From webmaster at beyond-thoughts.com Tue Dec 9 11:44:25 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Tue, 09 Dec 2003 17:44:25 +0100 Subject: Using XUL with python In-Reply-To: References: Message-ID: <3FD5FBE9.6060203@beyond-thoughts.com> Gabriele Farina wrote: > Hi guys, > > hiow can I create a XUL application that runs with python?? Which libreries > I need?? > > bye > > I only know two ways, that are worth considering (searching on the net shows a lot of results but it's hard to pick the good ones ...): - "LUXOR": afaik written in Java with Python/Jython abilities. Could be a promising platform (but I don't know much about this) ... - PyXPCOM: enable Python in the Mozilla-Framework (most of the stuff on the net is quite old, however the actual code is stored in Mozilla-cvs and recent. ActiveState use Python+XUL/Mozilla for their apps) (Useful links might be: http://lxr.mozilla.org/seamonkey/source/extensions/python/xpcom/ !!! http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/ http://pygecko.sourceforge.net/) IMO pygecko is a bit of "the right idea". Mozilla Project should split up their stuff and make a standalone XUL-Server supporting multiple languages. (Hey M$ is currently doing something similar for Longhorn...) cu cbf From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 30 05:03:20 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Dec 2003 11:03:20 +0100 Subject: Compiler? In-Reply-To: References: Message-ID: <3ff14d68$0$317$e4fe514c@news.xs4all.nl> J. A. Ek wrote: > I just heard about Python today. Is there a compiler for it, or does it > need to work through the interpreter only? FAQ: http://www.python.org/doc/faq/general.html#can-python-be-compiled-to-machine-code-c-or-some-other-language --Irmen From skip at pobox.com Wed Dec 10 11:56:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Dec 2003 10:56:01 -0600 Subject: ANN: pythonfs - create linux filesystems in python In-Reply-To: References: Message-ID: <16343.20513.446685.458768@montanaro.dyndns.org> Paul> Here's another idea, piggybacking on the /proc filesystem: >> Here's another idea. Provide a /proc filesystem on systems which don't >> support one out of the box. Tim> Yes, but his pythonfs product is extremely Linux-centric, where the Tim> /proc filesystem is ALWAYS available. Whoops, yeah... Skip From romany at actimize.com Wed Dec 17 02:32:47 2003 From: romany at actimize.com (Roman Yakovenko) Date: Wed, 17 Dec 2003 09:32:47 +0200 Subject: A GUI toolkit for Python that is NOT x-windows dependent Message-ID: <2CD84621099A814598AE3EFEFB5C1421046CF7@exchange.adrembi.com> curses -- Terminal handling for character-cell displays. May be this will help you. This module built-in in Python distribution. Roman > -----Original Message----- > From: Andre Brightway [mailto:andreb at warpmail.net] > Sent: Wednesday, December 17, 2003 9:05 AM > To: python-list at python.org > Subject: A GUI toolkit for Python that is NOT x-windows dependent > > > I need a script to draw a keyboard to the screen and animate the > marking each key when the key is pressed (among other things like > being able to draw menus). This script is for testing keyboards and > needs to be run by people who may never have touched a computer before > so it needs to have an easy to follow GUI interface. But the Linux > boxes these will be runned on are very low-end, 'diskless' terminals > where running a full X-Windows system would be very slow. Does anybody > know of a GUI toolkit (or a way to draw to the screen) that can be > used from Python script in Linux without having to run X-Windows? > -- > http://mail.python.org/mailman/listinfo/python-list > From Spam_Sucks at rr.com Tue Dec 9 11:16:42 2003 From: Spam_Sucks at rr.com (Luther Barnum) Date: Tue, 09 Dec 2003 16:16:42 GMT Subject: regex confusion References: Message-ID: MAybe you meant: import re, urllib rgxPrev = re.compile('.*?a.*?') url = 'http://nitace.bsd.uchicago.edu:8080/files/share/showdown_example2.html' s = urllib.urlopen(url).read() ***m = match(rgxPrev,s)*** print m print s.find('a') match takes two arguments "John Hunter" wrote in message news:mailman.266.1070985064.16879.python-list at python.org... > > In trying to sdebug why a certain regex wasn't working like I expected > it to, I came across this strange (to me) behavior. The file I am > trying to match definitely contains many instances of the letter 'a', > so I would expect the regex > > rgxPrev = re.compile('.*?a.*?') > > to match it the string contents of the file. But it doesn't. Here is > a complete example > > import re, urllib > rgxPrev = re.compile('.*?a.*?') > > url = 'http://nitace.bsd.uchicago.edu:8080/files/share/showdown_example2.html' > s = urllib.urlopen(url).read() > m = rgxPrev.match(s) > print m > print s.find('a') > > m is None (no match) and the s.find('a') reports an 'a' at index 48. > > I read the regex to mean non-greedy match of anything up to an a, > followed by non-greedy match of anything following an a, which this > file should match. > > Or am I insane? > > John Hunter > > > hunter:~/python/projects/poker/data/pokerroom> uname -a > Linux hunter.paradise.lost 2.4.20-8smp #1 SMP Thu Mar 13 17:45:54 EST 2003 i686 > i686 i386 GNU/Linux > hunter:~/python/projects/poker/data/pokerroom> python > Python 2.3.2 (#1, Oct 13 2003, 11:33:15) > [GCC 3.3.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > Welcome to rlcompleter2 0.95 > for nice experiences hit multiple times > > From mwh at python.net Tue Dec 23 12:49:24 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 23 Dec 2003 17:49:24 GMT Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> Message-ID: miki.tebeka at zoran.com (Miki Tebeka) writes: > Hello All, > > Can anyone tell me why when builiding Python gcc gets "-g" option as well as "-O3"? > Apart from bigger objects what does "-g" gives a non-developer of Python? It means if you manage to core python, we can hold your hands to find out with gdb where it's crashed. Why do you ask? Disk space is cheap. Cheers, mwh -- I'll write on my monitor fifty times 'I must not post self-indulgent wibble nobody is interested in to ucam.chat just because I'm bored and I can't find the bug I'm supposed to fix'. -- Steve Kitson, ucam.chat From km at mrna.tn.nic.in Thu Dec 25 22:32:10 2003 From: km at mrna.tn.nic.in (km) Date: Fri, 26 Dec 2003 09:02:10 +0530 Subject: indendation question Message-ID: <20031226033210.GA24039@mrna.tn.nic.in> Hi all, What is the standard and recommended way of indendation one should get to use in python programming ? is it a tab or 2 spaces or 4 spaces ? i am confused. kindly enlighten thanks, KM From francisgavila at yahoo.com Mon Dec 22 19:25:35 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Mon, 22 Dec 2003 19:25:35 -0500 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> Message-ID: John J. Lee wrote in message <87fzfch0bu.fsf at pobox.com>... >How do people name their iterator methods / functions? > >eg. .iter_foo(), .foo_iter(), .iterfoo(), .fooiter(), .foos(), ...? > >Of course, dicts have .iterkeys(), .itervalues() and .iteritems(), but >I don't like having words run together like that. Well, you have already discovered and rejected what little convention there is. ;) It seems that the emerging convention is .iters() for methods, and i() for functions (see itertools). This is what I stick to, as well. >The class pullparser.PullParser can iterate over HTML tokens (which >includes tags, comments, declarations, etc.) or just over the tokens >representing tags, skipping all other tokens. So __iter__ returns an >iterator over tokens, and tag_iter() over tags. Then I wondered if I >should be following a standard naming convention. There's a method >.get_tag(), so I guess the should be related to that in some obvious >way. I would have done .itertags(). This seems the most natural to me: iter + plural of thing to be iterated. I suppose it's just because it follows the dict convention, but it fits my way of thinking naturally, too. I don't like tag_iter(), because it seems more a noun than a verb. I almost expect it to *be* the iterator rather than *return* one. Having a verb as a function name is clearer. All this said, it's more important to be consistent with yourself than with the convention. *That* said, you'll be loved more if your self-consistency is also consistent with convention. :) -- Francis Avila From martin at v.loewis.de Sat Dec 27 04:31:10 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 27 Dec 2003 10:31:10 +0100 Subject: print arabic characters In-Reply-To: References: <3014031e.0312220305.c38ffa3@posting.google.com><3014031e.0312242351.d2604c2@posting.google.com><20031225145455.01ad3747.wtrenker@shaw.ca> Message-ID: Serge Orlov wrote: > Unicode _is_ rocket science And Web browsers are the category of software that deals best with Unicode and i18n. It's a long way until terminal emulators can do what web browsers can do today, wrt to rendering non-ASCII text. Regards, Martin From richie at entrian.com Tue Dec 2 12:06:34 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 02 Dec 2003 17:06:34 +0000 Subject: PyMeld and PyMeldLite (was Re: Separation of content and code for web) In-Reply-To: <3FCCBF61.9587D06@engcorp.com> References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> <3FCCBF61.9587D06@engcorp.com> Message-ID: Peter, > The reason that license wouldn't be suitable for us is that we build > embedded web server interfaces into some of our products, allowing them > to be monitored and configured remotely via the web. Very nice way to > go, but of course it would by definition require us to be able to > redistribute the code. It's not just going to be in our own servers, > but in effect installed on servers that we sell to others. Sure, I see. (A worldwide PyMeld license is a flat $300, BTW.) > Very interesting... we built ours around a sort of ElementTree-lite that > we whipped up -- which is based on the expat parser, and which therefore > also handles only valid X[HT]ML as well. You've written PyMeldLite exactly. Get out of my head! From the source: ## Super-lightweight DOM-like tree. ## ## The externally-visible `Meld` class is just a thin wrapper around a ## lightweight DOM-like tree. The classes `_Node`, `_RootNode`, ## `_ElementNode` and `_TextNode` implement the tree, and `_TreeGenerator` ## generates it from XML source. Mine uses expat in recent Python versions, and xmllib in older versions. > you've done things like make > items with "id" attributes available as named attributes of the PyMeld > object, whereas we concluded that since an id could contain things that > weren't legal in Python names, we should stick with a dictionary approach > instead. Yes. `element.class = something` is an example that one PyMeld user ran into. You need to say `setattr(element, 'class', something)`, which is messy. Adding a dictionary-like interface alongside the attribute-based one is a six-ish-line edit: def __getitem__(self, name): # XXX ...and setdefault... return getattr(self, name) def __setitem__(self, name, value): setattr(self, name, value) def __delitem__(self, name): delattr(self, name) I've smoke-tested that and it seems to work, but I'd need to write some extra unit tests before I was sure. [ The attribute-based system results in so much neater-looking code - one character of line noise in `element.attribute` vs. four in `element['attribute']` - that I decided I'd rather write HTML with Python-compatible id names. The odd unavoidable exception like 'class' I can put up with. But that's my personal opinion - PyMeld[Lite] should work both ways. ] -- Richie Hindle richie at entrian.com From oussoren at cistron.nl Tue Dec 30 16:19:36 2003 From: oussoren at cistron.nl (Ronald Oussoren) Date: Tue, 30 Dec 2003 22:19:36 +0100 Subject: Is Python Mac Centric??? In-Reply-To: References: Message-ID: On 30 dec 2003, at 21:41, Dennis Lee Bieber wrote: > >> looks as if something similar already exists for Macs with all these >> Mac only modules. Why is this? >> > Not really. I don't think the Mac modules are accessing down > to the > core Mac programming interface, they are more utilities. They are wrappers for a large part of the MacOS API's. And they are actively maintained. Ronald From santa at sbox.tugraz.at Wed Dec 3 17:39:41 2003 From: santa at sbox.tugraz.at (Gerald Senarclens de Grancy) Date: Wed, 03 Dec 2003 23:39:41 +0100 Subject: Why Python (a bit different) Message-ID: <3fce6605$0$248$a3f2974a@nnrp1.numericable.fr> Hi everybody! I recently gave a little lecture to my collegues at University and couldn't answer a nontechnical question of my prof afterwards. He wanted to know 'why python', but not in the way 'Why should so. use Python?', but meaning 'Why did Guido create Python?'. I couldn't find a good ressource online yet, maybe so can give me a good link or just the straightforward answer. Thanks, Gerald From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 30 12:51:30 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 30 Dec 2003 18:51:30 +0100 Subject: Try except - bug? References: <104c369a.0312300851.4f23759e@posting.google.com> Message-ID: <1ne3vvobhp2u6mqar4khk84h64hcmu8h1o@4ax.com> Askari: >Ops! For test (to do the error), you must click on button "crypter!" with >blank textField The program runs fine and displays a dialogue with "!ERREUR! :: Vous devez avoir un code pour l'encryption.". -- Ren? Pijlman From martin at v.loewis.de Mon Dec 29 20:03:38 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 30 Dec 2003 02:03:38 +0100 Subject: Monitoring an MS Exchange mailbox In-Reply-To: References: Message-ID: Lindstrom Greg - glinds wrote: > I have written a script to monitor my MS Exchange mailbox for certain > messages and post information to an MS SQL Server Database. Everything > works great except that each time I run the script I am prompted by Windows > to choose the profile of the mailbox via a dialog box. I'd like to run the > script every hour, so this is not good. > > Is there any way to either specify the profile or accept the default? > Certainly. Just pass the profile name as an argument to the function opening the connection to exchange. Regards, Martin From __peter__ at web.de Mon Dec 29 04:27:52 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Dec 2003 10:27:52 +0100 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: Bengt Richter wrote: > On 29 Dec 2003 00:36:09 -0800, danb_83 at yahoo.com (Dan Bishop) wrote: > >>engsolnom at ipns.com wrote in message >>news:<6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com>... >>> Hi, >>> I've been using constructs(?) like the below. >>> >>> def display(instance, start = None, end = None): >>> if instance.__class__.__name__ == 'UPCA': >> >>You might want to try the isinstance function. > > > > That's the usual idiom, but it should be noted that > it's not exactly the same, e.g., > > >>> class A: pass > ... > >>> class B(A): pass > ... > >>> a=A(); b=B() > >>> isinstance(a, A) > True > >>> isinstance(b, A) > True > >>> a.__class__.__name__ == 'A' > True > >>> b.__class__.__name__ == 'A' > False > > That last, again, is not the same as > >>> isinstance(b, A) > True > > A few more lines to the fine print: >>> class A: pass ... >>> a1 = A() >>> class A: pass ... >>> a2 = A() >>> a1.__class__.__name__ == "A" True >>> a2.__class__.__name__ == "A" True >>> a1.__class__ == A False >>> a2.__class__ == A True >>> If you care about the class at all (and I think most of the time you shouldn't) then compare classes, not names: instance.__class__ == Class instance.__class__ is Class Peter From R.Byrom at rl.ac.uk Mon Dec 1 11:40:31 2003 From: R.Byrom at rl.ac.uk (Byrom, R (Rob) ) Date: Mon, 1 Dec 2003 16:40:31 -0000 Subject: gzipping several files Message-ID: thanks Gerrit, I should of been a bit more specific, I actually did intent to use *.gz format and not *.zip (a faux-pas on my behalf). I've worked around the problem for the moment by just using the commands.getstatusoutput() to execute the linux gzip command. Obviously Im not worried about portability! -----Original Message----- From: Gerrit Holl [mailto:gerrit at nl.linux.org] Sent: Monday, December 01, 2003 3:31 PM To: Byrom, R (Rob) Cc: python-list at python.org Subject: Re: gzipping several files Byrom, R (Rob) wrote: > Does anyone know how to read-in several files and then batch all together > into a *.zip format? I've looked at the gzip module but I'm not sure how to > use this with several files. Any help gratefully received! The gzip module is about gzip, not about zip. Zip is different from gzip: zip is both an archiver and a compressor: it bundles several files into 1 file, *and* compresses them. In Unix, there are two different protocols for that: archiving is done with tar (tarfile[0]), compressing is done with gzip or bzip[1]. If you want to create a zip file, you may use the zipfile module ;)[2]. A good place to look for a module if you can't find it is the standard library documentation[3]. It is very useful! yours, Gerrit. [0] http://www.python.org/dev/doc/devel/lib/module-tarfile.html [1] http://www.python.org/dev/doc/devel/lib/module-gzip.html, http://www.python.org/dev/doc/devel/lib/module-bz2.html [2] http://www.python.org/dev/doc/devel/lib/module-zipfile.html [3] http://www.python.org/dev/doc/devel/modindex.html -- 273. If any one hire a day laborer, he shall pay him from the New Year until the fifth month (April to August, when days are long and the work hard) six gerahs in money per day; from the sixth month to the end of the year he shall give him five gerahs per day. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From bokr at oz.net Tue Dec 23 07:12:56 2003 From: bokr at oz.net (Bengt Richter) Date: 23 Dec 2003 12:12:56 GMT Subject: Operator overloading and __getattr__ References: Message-ID: On Mon, 22 Dec 2003 10:03:03 -0600, Samuel Kleiner wrote: >I'm trying to create methods on method access- but __getattr__ fails >with operator overloading(below) Any suggestions? EG: First please explain why you are trying to do whatever it is you're trying to do ;-) What do you mean "create methods"? A method like __add__ is returned by the attribute mechanism as a bound method, with self bound to something, and other being bound during the call of the method to the other operand. You are apparently trying to intercept this for _instance_ attribute access, when there exists no same_named method in class NewM or dict (since lookup of methods will bypass __getattr__ for new style classes). (Maybe you want to override __getattribute__, which is trickier, but I still don't know how you are going to supply a compatible pair of operands for __add__ unless you hope to do something useful by ignoring self. But a method grabbed from some random operand is not going to do that, in general). So what are you trying to do? I seem to be missing it. What do you expect to be self and other in this scenario? BTW, IWT type(name) would be str all the time, so I don't know what the code is doing, or even trying to do ;-/ > >class NewM(dict): > def __getattr__(self,name): > def fi(m): > if type(name) in self: > self[type(name)]=self[type(name)].__dict__[name](m) > else: > self[type(name)]=m > return fi > >p=int(2) >s=NewM() >print p.__add__(2) >print s.__add__(2) >print p+2 >print s+2 > >Causes TypeError on the last line I doubt if that's the first problem ;-) Regards, Bengt Richter From usenet_spam at janc.invalid Wed Dec 3 00:28:53 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 03 Dec 2003 05:28:53 GMT Subject: Tkinter question: how to the red "Tk" window title bar icon? References: Message-ID: "John Benson" schreef: > I've often seen Tkinter referred to as the "standard" Python GUI. I > assume that this is because it may be the oldest and perhaps the most > cross-platform. Is that all that can be said for it? Tkinter is included with official Python releases, other GUI toolkits have to be installed separately... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bokr at oz.net Thu Dec 18 16:06:02 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Dec 2003 21:06:02 GMT Subject: AW: traceback as string References: Message-ID: On Thu, 18 Dec 2003 11:44:46 +0100, "Oliver Walczak" wrote: >This seems to be a quite difficult approach. Try this: [ snip nice code] Here is a variant with repeat counting (may be a bit format-sensitive): I rather wish something like it was built into the traceback print itself, especially when recursing forever interactively, and one loses initial output context. ##################################################################### import traceback class MyTraceback: def __init__(self): self.clear() def clear(self): self.line = [] self.lines = [] self.repeat = 0 def write(self, s): self.line.append(s) if s[-1:] == '\n': s = ''.join(self.line) self.line = [] self.lines.append(s) if len(self.lines)>=4 and self.lines[-4:-2] == self.lines[-2:]: self.repeat += 1 del self.lines[-2:] else: if self.repeat and s!= self.lines[-3]: if self.repeat==1: self.lines.extend(self.lines[-2:]) else: self.lines.insert(-1, ' *** previous two lines repeated %s times ***\n\n'% self.repeat) self.repeat = 0 def read(self): return ''.join(self.lines + self.line) def catch(self): traceback.print_exc(None, self) if __name__ == '__main__': myTcb = MyTraceback() def foo(n): if n<0: foo(n) # blow stack print '---> foo(%s)'%n if n>0: foo(n-1) 1/0 try: foo(5) except: myTcb.clear() myTcb.catch() print myTcb.read() try: foo(-5) except: myTcb.clear() myTcb.catch() print myTcb.read() ###################################################################### Result: [13:19] C:\pywk\clp>mytracebk.py ---> foo(5) ---> foo(4) ---> foo(3) ---> foo(2) ---> foo(1) ---> foo(0) Traceback (most recent call last): File "C:\pywk\clp\mytracebk.py", line 41, in ? foo(5) File "C:\pywk\clp\mytracebk.py", line 38, in foo if n>0: foo(n-1) *** previous two lines repeated 4 times *** File "C:\pywk\clp\mytracebk.py", line 39, in foo 1/0 ZeroDivisionError: integer division or modulo by zero Traceback (most recent call last): File "C:\pywk\clp\mytracebk.py", line 47, in ? foo(-5) File "C:\pywk\clp\mytracebk.py", line 36, in foo if n<0: foo(n) # blow stack *** previous two lines repeated 998 times *** RuntimeError: maximum recursion depth exceeded Regards, Bengt Richter From mwh at python.net Mon Dec 15 05:38:21 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 15 Dec 2003 10:38:21 GMT Subject: codecs latin1 unicode standard output file References: Message-ID: "Marko Faldix" writes: > Hello, > > with Python 2.3 I can write umlauts (a,o,u umlaut) to a file with this piece > of code: > > import codecs > > f = codecs.open("klotentest.txt", "w", "latin-1") > print >>f, unicode("My umlauts are ?, ?, ?", "latin-1") > > > This works fine. This is not exactly what I wanted to have. I would like to > write this to standard output so that I can use same code to produce output > lines on console or to use this to pipe into file. It was possible before > Python 2.3. Isn't possible anymore with same code? If your locale is setup up in an appropriate way, you should be able to print latin-1 characters to stdout without any intervention at all. If that doesn't work, we need more details. Cheers, mwh -- Also, remember to put the galaxy back when you've finished, or an angry mob of astronomers will come round and kneecap you with a small telescope for littering. -- Simon Tatham, ucam.chat, from Owen Dunn's review of the year From imbosol at aerojockey.invalid Fri Dec 19 22:18:27 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 03:18:27 GMT Subject: dynamic typing questions References: Message-ID: <7cPEb.22795$031.18599@fe3.columbus.rr.com> Jason Tesser wrote: > OK what are your guys thoughts here? How have you all > overcome the lack of static typing? Is Python a > bad decision here? By the way we will be using > Postgres in the back if that matters to anyone. Maybe try the confrontational approach, if all else fails: Acknowledge that static typing is "cute." Then mercillessly press him on how often it really helps, and how much time does it save relative to Python. Whenever he cites an advantage of static typing, ask him how often it really helps. How often does the compiler really catch that, and is this really something that Python won't catch at runtime? If he cites the ability of the compiler to catch incorrectly passed arguments, point out that Python can still catch these at run time, probably as well as Java could. Remind him that static typing can catch these only if the incorrect argument happens to have a different type: static typing is a swiss cheese protection mechanism. If he cites the ability to catch spelling errors: first point out that that's unrelated to static typing. Some statically-typed languages have this problem (Fortran). And a dynamically-typed language can require declarations. But, even though Python doesn't, it's not that serious a problem in Python. Unlike a certain other dynamically typed (I guess) language beginning with P, variables just don't pop out of nowhere if you just use them. So the only time Python can't catch a spelling error is when it's on the left side of an assignment (or imported, or whatever). If he says that's still worse than Java, concede it. It's true after all. Then ask him how often that happens, and how much time he thinks that will save compered to Python. If he says that compiler errors are easier to locate than runtime errors, point out that Python, like Java, has a very good exception handling mechanism that identifies the locus of errors. While you're at it, ask him whether debugging run time errors was ever that bad. After all, Java has those, too. At the same time, pimp the advantages of dynamic typing. Ask him if he's ever written a class, a union, or done some other silly thing to define a variable that can have a "special" value. Remind him that this isn't necessay in Python, thanks to dynamic typing. (Incidentally, this happens to me a lot.) Ask him how many times he's defined some ridiculous class hierarchy to get some pathetic, contrived imitation of polymorphism. Point out that, in Python, this isn't necessary. Things don't have to be subclasses to be polymorphic. Subclasses can be used for what they were intended for: inheritance. Ask him how often he uses type casting (which should be a lot, since he prefers Java). Remind him that every time he uses type casts he defeats the point of static typing, and has to go though more effort to do so. Ask him if he's ever gotten a Runtime error in Java for a type casting error. If no, or not often, ask him why he expects this so much in Python. If yes, ask him if he felt annoyed that the Java compiler wasn't able catch it for him, or happy that Java's runtime was up to the task. I believe there is very little practical advantage of static typing. Most of the advantages are small, cute little things, but not things that won't still be caught at runtime by Python. The wrong type is almost certain to be caught by Python sooner or later. And, in the end, I really don't think type mismatch errors are very common (compared to other types of error). Finally, if you still end up using Java, count your blessings. Java is not that bad. You could be using C++ or Visual Basic. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From bokr at oz.net Thu Dec 4 05:33:33 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Dec 2003 10:33:33 GMT Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: On 04 Dec 2003 08:28:16 +0100, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >"Mike C. Fletcher" writes: > >> AFAIK, that's the plan. IIRC, rationale was that there would be some >> other type for 8-bit data, while all "normal" strings would become >> Unicode strings. > >No. will remain a byte string type for any foreseeable >future. The only change that is likely to happen is this: To denote >bytes > 128 in source code, you will need to use escape codes. > Anyone considered extending the hex escape with delimiters to make long runs more dense? E.g., 'ab\x00\x01\x02\x03cd' being spellable as 'ab\<00010203>cd' or 'ab' x'00010203' 'cd' or x'6162000102036364' >A change that might happen in the future is this: A string literal >does not create an instance of , but an instance of 'unicode'>. However, IMO, this should only happen after a syntax for >byte string literals has been introduced. > Still, the actual characters used in the _source_ representation will have to be whatever the -*- xxx -*- thing says, right? -- including the characters in the source representation of a string that might wind up utf-8 internally? (so you could have several modules whose sources are encoded differently and have the run time see a single unified internal representation of utf-8? Or wchar/utf-16le? >> >I'm very unimpressed with this decision if that's the case. >> > >> Doesn't make me ecstatic, either, as I like the simple 8-bit-clean >> string type. But maybe we'll luck out and it will turn out that I'm >> all wet on this one :) . > >The byte string type is not going away. It is a useful type, e.g. when >reading or writing to or from a byte stream. > Is this moving towards a single 8-bit str base type with various encoding-specifying subtypes? Regards, Bengt Richter From francisgavila at yahoo.com Wed Dec 10 22:54:27 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Wed, 10 Dec 2003 22:54:27 -0500 Subject: List Comprehension question References: Message-ID: Mark Elston wrote in message ... >Anyway, I thought I was following the discussions of List >Comprehension (LC) until I got to Recipe 1.16. In this recipe >we have the following: > > arr = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] > print [[r[col] for r in arr] for col in range(len(arr[0]))] > -> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] All the second line is saying, is, for every pass of the innermost (here, rightmost) for-loop, execute this list comprehension: [r[col] for r in arr]. Same as: res = [] for col in range(3): res.append([r[col] for r in arr]) Unrolling a bit more: res = [] for col in range(3): innerres = [] for r in arr: innerres.append(r[col]) res.append(innerres) Note this is NOT the same as [r[col] for col in range(3) for r in arr]! res = [] for col in range(3): for r in arr: res.append(r[col]) -> [1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12] See? It's flattened, because the list comp's expression evaluates to an integer instead of a list. >I thought I understood this until I got to the above recipe. Here >it looks like the order of evaluation is reversed. That is, instead >of translating to: > > for r[col] in arr: > for col in range(len(arr[0])): > ... > >we actually have > > for col in range(len(arr[0])): > for r[col] in arr: > ... Nope. See above. >While I don't really understand it I may have some kind of rationale. >Please let me know if this is correct. You're thinking too much. :) > The expression, itself, is also a LC. This is the part that's causing you confusion. This is a nested list comp: for every iteration in the outer list comp, execute the expression. The fact that the expression happens to be a list comp itself just means that the outer list comp will append a new list on each pass. Wrap the inner list comp in a function call and it will make sense to you: def innercomp(col): return [r[col] for r in arr] [innercomp(col) for col in range(3)] -> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] (It's also significantly slower.) >Well, hmmmmm. OK. Maybe I do understand it. It just wasn't apparent >at first. > >Am I close, or did I guess wrong? You got it. Note, however, that the same thing is far easier with zip(): >>> zip(*arr) [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] If you need the items to be lists, >>> [list(i) for i in zip(*arr)] [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] or, >>> map(list, zip(*arr)) [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] -- Francis Avila From vincent at visualtrans.de Sun Dec 14 12:59:39 2003 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 14 Dec 2003 18:59:39 +0100 Subject: Help needed adding attributes to a C-coded class Message-ID: Hi folks, How can I add an attribute to a C-coded class (..using PyClass_New()...) in the __init__ method of that class, making it show up in "self.__dict__" on the Python side? IOW, when I have a class called "Screen" in a C-extension that has an __init__ method that takes a single argument called "name" (apart from "self" of course), how can I add this as an attribute to the class so that it equals a "self.name = name" assigment in a pure Python class? So far my "__init__" method looks something like: static PyObject * ex_Screen__init__(PyObject *self, PyObject *args) { char *name; PyObject *selfObject; if (!PyArg_ParseTuple(args, "Os", &selfObject, &name)) return NULL; /*now "name" becomes one of the instances attributes exposed as instance.__dict__ on Python side..... but how?*/ Py_INCREF(Py_None); return Py_None; } Any pointers much appreciated! Regards, Vincent Wehren From kamuelaf at verizon.net Thu Dec 25 06:01:37 2003 From: kamuelaf at verizon.net (Kamuela Franco) Date: Thu, 25 Dec 2003 11:01:37 GMT Subject: Socket Programming References: <3FEAC35F.C26A14B1@alcyone.com> Message-ID: Sounds quite fun then. Now onto tutorials, got any? Kamuela Franco From theller at python.net Tue Dec 2 14:16:03 2003 From: theller at python.net (Thomas Heller) Date: Tue, 02 Dec 2003 20:16:03 +0100 Subject: Shared Memory Modules References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> <3fcbd6b8$1@nntp0.pdx.net> <3fcbd24f$0$1502$e4fe514c@news.xs4all.nl> <3fcc5a0b$0$1491$e4fe514c@news.xs4all.nl> <8ylv1r5g.fsf@python.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > On Tue, 02 Dec 2003 10:54:19 +0100, Thomas Heller wrote: > >>Irmen de Jong writes: >> >>> Bengt Richter wrote: >>>> What's that first zero argument? >>> [...] >>>> Does that mean you are trying to use stdin as the open file handle? >>> >>> No it doesn't, according to Thomas Heller's post in this thread. >>> Thomas said 0 means "not associated with a file" on windows... >> >>mmapmodule.c internally uses INVALID_HANDLE_VALUE of a file handle of 0 >>is used. > Wouldn't passing None be more pythonic for a python interface? > >> >>As I said, read the source (and MSDN). And then submit a documentation >>patch . >> > How does one do that? (being lazy, I guess I could find out via www.python.org) Finding out how to do this is the easier part ;-) Ok, to get you started: Thomas From bokr at oz.net Fri Dec 5 03:25:18 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 08:25:18 GMT Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 04 Dec 2003 21:45:23 -0800, David Eppstein wrote: >In article <7x7k1b4yqn.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >> Try this with a list: >> >> a = [1, 2, 3, 4, 5] >> a[3] = 27 >> print a >> >> Then try it with a tuple. > >That's true, but another answer is: you should use tuples for short >sequences of diverse items (like the arguments to a function). You >should use lists for longer sequences of similar items. > I'm curious what you're getting at. I.e., what does diversity or similarity have to do with the choice? Is that an aesthetic thing? (In which case 'should' should be qualified a bit, IWT ;-) Or what am I missing? Regards, Bengt Richter From amk at amk.ca Wed Dec 10 12:05:13 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 10 Dec 2003 11:05:13 -0600 Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: On Wed, 10 Dec 2003 10:10:44 -0500, Istvan Albert wrote: >> The xsdb package is implemented in Python, and the server mode requires >> stackless python. > Why? Probably because Stackless made it easier to write the server without having to wrestle an async socket library such as Medusa or Twisted. > IMHO this sort of limitations severely reduce any > project's potential. Yeah, but it's his code, so he can do whatever he likes. Sheesh, Aaron announces a database system that looks really spiffy from the examples, like ZODB without the pain of ExtensionClass, and the first two responses are griping about one aspect of it. Sometimes folks don't know when they're well-off. (Now if only he'd released it before I wrote the PyCon proposal tracker using PostgreSQL...) --amk From jzgoda at gazeta.usun.pl Wed Dec 10 14:50:29 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 10 Dec 2003 19:50:29 +0000 (UTC) Subject: ANN: Twisted 1.1.1 References: Message-ID: Itamar Shtull-Trauring pisze: > Twisted is an event-driven networking framework for server and client > applications. > > For more information, visit http://www.twistedmatrix.com, join the list > http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python or > visit us on #twisted at irc.freenode.net. > > The Twisted from Scratch tutorial is a good starting point for learning > Twisted: http://twistedmatrix.com/documents/howto/tutorial I am really angry that I cann't write Twisted-based applications on daily basis since I think it's really coolest network framework I could ever dream of! Writing one more asyncore/asynchat application pisses me off. Hate it. Love it. Thanks God, it's Python, not Rexx, even not Java. NP: The Cure - The Loudest Song -- Jarek Zgoda Unregistered Linux User #-1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From http Sun Dec 7 16:21:27 2003 From: http (Paul Rubin) Date: 07 Dec 2003 13:21:27 -0800 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> Message-ID: <7xk758iaso.fsf@ruckus.brouhaha.com> Douglas Alan writes: > You will notice that CamelCase was extremely uncommon (if used at all) > before the advent of case-sensitive languages, and there is good > reason for this. It didn't make sense then, and it doesn't make sense > now! (In a case-insensitive language.) The convention always annoyed me, but I think it was customary in the old days of Smalltalk. When object-oriented programming became a fad in the 80's, it spread into other languages from there. From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 26 17:06:44 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 26 Dec 2003 23:06:44 +0100 Subject: Project dream References: Message-ID: Will Stuyvesant: >Suppose you have the time and the money to start a new project in >Python. What would you like to do? I was thinking of an open source personal information management application, to store notes, knowledge, hyperlinks, snippets, documents and such in one flexible integrated information structure. All the things that now end up in unrelated documents in different folder hierarchies. Something with the flexibility and visualisation of the Brain (www.thebrain.com), the structuring capabilities of InfoHandler (www.mdesoft.com/english.htm) and a Googleish search engine. -- Ren? Pijlman From tzot at sil-tec.gr Fri Dec 12 09:33:38 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 12 Dec 2003 16:33:38 +0200 Subject: problems on GUI editor~ References: Message-ID: On Thu, 11 Dec 2003 19:08:02 -0800 (PST), rumours say that black might have written: >Howdy~ > I am trying to code with a text editor, during that i got some problems and i hope anyone could supply any clue, they are laied right below: >1 how can we undo and redo action ? This command can be commonly located at Edit-Undo and Edit-Redo for most of editors. Are you trying to code WITH a text editor or are you trying to CODE a text editor? >2 can we communicate with clipboard of current system ? Yes, but the code is specific for every system (cause I haven't read anything about a clipboard abstraction in Tkinter) >3 i build a textfield by Text class of Tkinter module. i found some shortcut keys are automatically activated but they did not act as what i expected, how can i config or disable them ? Try using the .bind method of the Text widget to make them do what you want. >4 how can we customize a right-clicking menu ? i searched whole Tkinter but found no menu be available for right-clicking Hm, I can't remember something about this. Have you checked: http://www.python.org/cgi-bin/moinmoin/GuiBooks http://www.python.org/topics/tkinter/ ? >one million thanx for any suggestion~ I don't have 999999 thanx in change :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From mwh at python.net Mon Dec 29 09:11:15 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Dec 2003 14:11:15 GMT Subject: Quicktime in python References: Message-ID: Wesley Fraser writes: > Hey everyone. > > Does anyone know if there has been a basic, ornot so basic > implimentation of quicktime in python? If not, is there a reasonably > straight forward way of accessing quicktime from python? I believe MacPython has a wrapper (and if you use PyObjC you should be able to use the Cocoa movie classes). If you're on Windows, does it have a COM interface? If you just want an easy way of playing a movie, pygame can do that, but probably with less codec support. Actually *implementing* QT in Python would seem to be a bit of a fool's errand. Cheers, mwh -- The ultimate laziness is not using Perl. That saves you so much work you wouldn't believe it if you had never tried it. -- Erik Naggum, comp.lang.lisp From pinard at iro.umontreal.ca Mon Dec 22 21:16:42 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 22 Dec 2003 21:16:42 -0500 Subject: Naming conventions for iterator methods? In-Reply-To: <87fzfch0bu.fsf@pobox.com> References: <87fzfch0bu.fsf@pobox.com> Message-ID: <20031223021642.GA15171@titan.progiciels-bpi.ca> [John J. Lee] > How do people name their iterator methods / functions? > eg. .iter_foo(), .foo_iter(), .iterfoo(), .fooiter(), .foos(), ...? I took the habit of naming such methods and functions with names starting with `all_', so I can write: for name in all_names(): do something or maybe: tokens = all_tokens() ... token = tokens.next() ... I find this more legible than forcing the string `iter' here and there, and leaves a bit more freedom to change the code later -- let's say, if I ever want to substitute a solid list for the iterator. I can keep the `all_' prefix, while I would feel uncomfortable it were some `iter' in the names. Granted, if I want to use `.next()', I'll have to plunk one more `iter()' in the code. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From peter at engcorp.com Tue Dec 23 13:30:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Dec 2003 13:30:43 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <3FE8652D.2E8F21A8@engcorp.com> Message-ID: <3FE889D3.368E3AF5@engcorp.com> Aahz wrote: > > In article <3FE8652D.2E8F21A8 at engcorp.com>, > Peter Hansen wrote: > > > >P.S. My heartfelt thanks to whomever it was who posted the Lewis Carroll > >reference lately... I'm _still_ trying to find my old copy of Through the > >Looking Glass to find that section! > > Forgotten the Power Of Google? > > http://www.literature.org/authors/carroll-lewis/through-the-looking-glass/chapter-08.html Thanks, but I shouldn't have implied as I did that I was interested only in that one section. As I don't recall the passage at all, I'm now quite eager to read the entire book again. I think it's been twenty years since I read it last. -Peter From tzot at sil-tec.gr Tue Dec 30 23:11:49 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 31 Dec 2003 06:11:49 +0200 Subject: Test if IDLE is a mature program References: Message-ID: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> On Tue, 30 Dec 2003 21:20:09 -0500, rumours say that "Aubrey Hutchison" might have written: >### this will test if your version of IDLE on windows is a MATURE program >design ### > >print "Hello world, If Python IDLE is a mature program design it will >output this" > >Save this simple single line program as "select.py" and try to run it. > >Then exit IDLE and try to restart IDLE. You might try renaming your module to something that is not a standard library module imported by IDLE itself... ;-) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From lutz at rmi.net Wed Dec 31 12:07:22 2003 From: lutz at rmi.net (Mark Lutz) Date: 31 Dec 2003 09:07:22 -0800 Subject: ANN: Learning Python 2nd Ed Message-ID: I'm told that the 2nd Edition of the book Learning Python began shipping earlier this week. It's currently listed on O'Reilly's home page, and described here: http://www.oreilly.com/catalog/lpython2/ http://www.rmi.net/~lutz/about-lp2e.html Amazon shipped a copy to me yesterday (despite the fact that their web page still said "ships within 1-2 months" as of this morning :-). Happy 2004, --Mark Lutz (http://www.rmi.net/~lutz) From adsl5lcq at tpg.com.au Sat Dec 20 03:25:34 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Sat, 20 Dec 2003 19:25:34 +1100 Subject: How to use a 5 or 6 bit integer in Python? References: <3FE2FB4C.5020909@users.ch> Message-ID: On Fri, 19 Dec 2003 14:21:16 +0100, Borcis wrote: >Glen Wheeler wrote: > >> I'm using one dictionary to store all of the data, with tuples of >> ints as keys and a tuple as the data associated with each key. The >> data tuples contain a few ints and two more dictionaries. >> Can you think of a way to reduce the memory used here? > >What's the length of the key tuples, and are there bounds on the >component ints ? Component ints will either be 0-63 or 0-31. In a single run of the program, this will not change throughout. The key tuples range in length from 1-64, depending on at what stage the program is currently at. Every tuple will have the same length at some point; the greatest possible distance in length from any two tuples is 1. > Is the number of ints in the data tuples fixed ? Yes, there are always two ints, and another tuple of ints. One int is arbitrary, and can be in the thousands but not much higher. Another int is from 0-5. The tuple of ints is less than 6 long and will contain either 0-63 or 0-31, depending on the parameters given to the program at run time. > What's in the subdictionnaries, typically ? "millions of 5 bit integers" hints >of the possibility of a radical change of representation, but a radical >change of representation can only be devised if we know what's stable >- the task. Well, the subdictionaries contents are described in another reply written by me in this same thread. There are indeed many millions of integers beign stored at any one time, or at least many millions of references to these integers. You are saying that to save any amount of memory something in the large dictionary must be constant? I am sure everything in there is dynamic in nature, i.e. will change with each iteration over the keys in the large dictionary. -- Glen From rlogan at hmc.edu Fri Dec 12 12:56:48 2003 From: rlogan at hmc.edu (=?iso-8859-1?B?UmVuZek=?=) Date: Fri, 12 Dec 2003 09:56:48 -0800 Subject: Implicit Conversions Message-ID: I wanted to know the order of implicit conversions and which sort of values allow them. From searching around in books and the archive of this mailing list, it seems to be that only numbers are implicitly converted within each other and bools can be implicitly converted to ints? However, I'm unable to find any other implicit conversions and the order of the implicit conversions (something like int->float->long). Any help would be greatly apprectiated. Also, I'm not on the mailing list so can everyone please cc me in the replies? Rene? From fowlertrainer at anonym.hu Tue Dec 9 08:21:34 2003 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 9 Dec 2003 14:21:34 +0100 Subject: sys.traceback + thread Message-ID: <151106659328.20031209142134@anonym.hu> Hello python-list, This is a thread's run method. def run(self): try: page=urllib.urlopen(base) src=page.read() page=None self.ResultCode=0 self.ResultSrc=src except: self.ResultSrc="An error occured"+ the exception's errormessage !!! self.ResultCode=1 I use the traceback module in one threaded application. But I don't use it in multiple threaded app. What can I use/how can I do in except section to get the exception's message ? Please help me. Thx. -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From r.wieseler at t-online.de Thu Dec 25 05:23:01 2003 From: r.wieseler at t-online.de (Ralf Wieseler) Date: Thu, 25 Dec 2003 11:23:01 +0100 Subject: Python on Max osx and tkinter Message-ID: Hello! I'm quite new to Python. I wrote some little scripts using the "import from tkinter" Statemant that work well on Windows and Linux. but if i try to execute them in my Powerbook with Mac OSX 10.2.8 i get only Errors. I imorted the TKinter Module with the Package Manager of MacPython 2.3 but it doesn't work. My Macphython has no idea of TKinter. Whats wrong? Thanks for any help! Greetz Ralf From francisgavila at yahoo.com Sun Dec 7 15:45:41 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 7 Dec 2003 15:45:41 -0500 Subject: Base conversion method or module References: <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc@4ax.com> Message-ID: Jeff Wagner wrote in message <0bu6tvsde8jqvjlu09itnuq6et04tmk9dc at 4ax.com>... >Is there a Python module or method that can convert between numeric bases? Specifically, I need to >convert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b. > >I searched many places but couldn't find a Python specific one. > >Thanks, Jeff There was a Python cookbook recipe that did these kinds of conversions, IIRC. Look around at http://aspn.activestate.com/ASPN/Cookbook/Python. Numeric might do this sort of thing, too, but I don't know. Python itself can get you pretty far; the problem is that it's a bit spotty in making conversions communicable. For example, int() and long() both accept a string with a base argument, so you can convert just about any base (2 <= base <= 36) to a Python int or long. Python can also go the other way around, taking a number and converting to a string representation of the bases you want. The problem? There's only a function to do this for hex and oct, not for bin or any of the other bases int can handle. Ideally, there's be a do-it-all function that is the inverse of int(): take a number and spit out a string representation in any base (2-36) you want. But the binary case is pretty simple: def bin(number): """bin(number) -> string Return the binary representation of an integer or long integer. """ if number == 0: return '0b0' binrep = [] while number >0: binrep.append(number&1) number >>= 1 binrep.reverse() return '0b'+''.join(map(str,binrep)) Dealing with negative ints is an exercise for the reader.... Remember also that Python has hex and octal literals. -- Francis Avila From no at spam.invalid Tue Dec 23 19:47:38 2003 From: no at spam.invalid (Russell E. Owen) Date: Tue, 23 Dec 2003 16:47:38 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: In article , rstephens at vectron.com (Ron Stephens) wrote: >I'm sorry to hear about those problems, Russell. I am using Tkinter on >Aqua, and I guess now that I think about it, I've noticed a few >non-perfect looking dialogs or widgets, but they didnt really bother >me. > >I'm still using the Ptyhon 2.3 that came installed on Panther, I >believe, and I hadn't hear about the diffiulties upgrading to a new >Python version; it almost makes me want to try it to find out what >troubels lurk. Maybe I will and report back... Well, I'm not sure how serious the problem actually is. I may have overstated it. Hoping to hear soon. In any case, the file dialog problem somehow went away when I went to Panther, so I only see those cosmetic problems I mentioned (some of which are helped by careful choice of fonts). I'm not sure what's up with the file dialog, but I'm not about to complain. One minor warning when building Python for X11: python *may* pick up the framework tcl/tk in /Library/Frameworks instead of the X11 version in /usr/local. The symptom I had was Tkinter running in aqua (and not coming to the front) and I'm not entirely sure it was a bad build (it may have simply been tcsh caching info). I am sure I finally got x11 python to build correctly after I trashed my /Library/Frameworks tcl and tk (restoring them after the build). Summary: both aqua and X11 versions of Python are working well for me. Panther's X11 is significantly nicer, too. A problem I had with windows that were too tall is gone, and one can quit without getting a confirmation dialog box! -- Russell From fredrik at pythonware.com Mon Dec 8 08:23:15 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 14:23:15 +0100 Subject: Quantify over all functions of a module References: Message-ID: Joerg Schuster wrote: > The following code comes closest to what I am trying to do. > It does not work, because dir() does not return functions, but > function names as strings. > > ##### test2.py ##### > def plus_2(_int): > return _int + 2 > > def plus_3(_int): > return _int + 3 > > > #### test.py ##### > #!/usr/bin/env python > > import re > import test2 > > func_list = [] > > for func in dir(test2): > test = re.search("^__", func) > if not test: > func_list.append(func) > > for func in func_list: > print apply(func, (2,)) > > > I failed to find a solution by searching the net, probably because I > didn't know the right keywords. And I suppose that searching > would not be necessary, if I knew the right keywords. if you look up "dir" in the documentation, you'll find related functions including: getattr(module, name) => object and vars(module) => dictionary mapping names to objects something like this might work: for name, func in vars(test2): if not name.startswith("__") and callable(func): func_list.append(func) From bokr at oz.net Wed Dec 24 17:26:50 2003 From: bokr at oz.net (Bengt Richter) Date: 24 Dec 2003 22:26:50 GMT Subject: "literal" objects References: <%QbGb.2109$1f6.732@newssvr25.news.prodigy.com> Message-ID: On Wed, 24 Dec 2003 09:23:23 -0800, Donn Cave wrote: >In article <%QbGb.2109$1f6.732 at newssvr25.news.prodigy.com>, > "Moosebumps" wrote: [...] > >> A thought that occured to me is that classes are implemented as dictionaries >> (correct?). So you could have a dictionary like this: >> >> x = {'a': 3, 'b': 5} >> y = {'a': 5, 'b': 15} >> >> This would be the __dict__ attribute of an object I suppose. But I don't >> see anyway to assign it to a variable so you could access them like x.a and >> y.a. I don't know if this would be a "nice" way to do it or not. > >class A: > def __init__(self): > self.__dict__.update({'a': 3, 'b': 5}) >x = A() >print x.a, x.b > >Would it be nice? No, it would be horrible, unless you had some >very compelling reason to do this, in which case it would be fine. This form of the above can be useful, though: class A: def __init__(self, **kw): self.__dict__.update(kw) x = A(a=3, b=5) print x.a, x.b Since you can then also continue with y = A(a='Happy', b='Holidays') print y.a, y.b ;-) Regards, Bengt Richter From bhoel at web.de Sun Dec 28 14:16:58 2003 From: bhoel at web.de (Berthold Hoellmann) Date: Sun, 28 Dec 2003 20:16:58 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: Michael Hudson writes: > bhoel at web.de (Berthold Hoellmann) writes: > >> Hello, >> >> When I use >> >> ./configure --with-thread --with-fpectl --with-signal-module \ >> --with-pymalloc --enable-shared --with-cxx=g++ >> >> make test > > What platform, compiler, and versions thereof? Sorry, of course: SuSE Linux 9.0, gcc (GCC) 3.3.1 (SuSE Linux) I always forget about my *FLAGS: CXXFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ -ffast-math -fno-math-errno -funsafe-math-optimizations \ -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow CFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ -ffast-math -fno-math-errno -funsafe-math-optimizations \ -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow (My Processor is a AMD Athlon(tm) XP 2000+, 512MB RAM) > ... > Well, there's a test in tes_sre that uses quite a lot of C stack. I > guess it's possible that something about shared library code uses more > stack. Can you run 'ulimit -s ' and try again? > Well, stacksize is unlimited (somehow) >limit cputime unlimited filesize unlimited datasize unlimited stacksize unlimited coredumpsize unlimited memoryuse unlimited vmemoryuse unlimited descriptors 1024 memorylocked unlimited maxproc 4095 Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From Jack.Jansen at cwi.nl Tue Dec 16 16:04:40 2003 From: Jack.Jansen at cwi.nl (Jack Jansen) Date: Tue, 16 Dec 2003 22:04:40 +0100 Subject: [Python-Dev] Re: rexec.py unuseable In-Reply-To: <20031216161603.GG17021@lkcl.net> References: <1071587601.3fdf2111afc59@mcherm.com> <20031216161603.GG17021@lkcl.net> Message-ID: <76A3670A-300B-11D8-B3E2-000A27B19B96@cwi.nl> On 16-dec-03, at 17:16, Luke Kenneth Casson Leighton wrote: >> Luke replied: >>> capabilities, acls, schmapabilities, same thiiing :) >> >> No... they're not. Read the thread I mentioned above, or read this, >> and some of the other documentation for the language E: >> >> http://www.erights.org/elib/capability/ode/ode-capabilities.html > > no offense intended: i'll read that later, i'm running out of time. > > without going into too many definitions, consider what i am advocating > to be _like_ an access control list but instead to be a capabilities > control list, instead. The distinction between capabilities and ACLs is really important, because they are almost each others opposite. With capabilities you have an (unforgable) right to do something and no-one cares about your identity, with ACLs you have an unforgable identity which is checked against the ACL. -- Jack Jansen, , http://www.cwi.nl/~jack If I can't dance I don't want to be part of your revolution -- Emma Goldman From martin at v.loewis.de Wed Dec 10 12:09:00 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 10 Dec 2003 18:09:00 +0100 Subject: loading new unicode language encoders into lib/encodings References: Message-ID: "Posadas, Dennis" writes: > Once you load the necessary language encoder into > lib/encodings, is that all there is to using it ? I loaded the > encoder eucgb2312_cn.py and pyc into lib/encodings but am still > getting the error below... You need to quit and restart Python, as it performs negative caching. Regards, Martin From bokr at oz.net Fri Dec 5 11:10:05 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 16:10:05 GMT Subject: Yet another newbie question - standard or built-in methods References: Message-ID: On Fri, 05 Dec 2003 13:51:14 +0100, Peter Otten <__peter__ at web.de> wrote: >Kamus of Kadizhar wrote: > >> OK, I've been playing with the snippets of code posted earlier. >> >> Among them are things like >> >> allmovies[movie] = allmovies.get(movie, 0) + 1 >> >> From reading the docs, I've gathered that the '.get(xxx,yyy)' part is a >> method that operates on the dictonary allmovies. (Sorry if I have the >> terminology wrong). >> >> But nowhere can I find a list of 'standard' or 'built-in' methods, or >> methods that can be used with various variable classes. What exactly >> does 'get' do? This seems to be so basic to python that it's not >> explained anywhere, but that's no help to me.... Is there a list with >> explanations somewhere? I've been through the tutorials and guides, and >> all just start using these with no explanation of what they do and how >> they work. >> >> Maybe I've missed it somewhere; just point me to the right FM, so I can >> RTFM. >> >> help is no help: >> >> help> get >> no Python documentation found for 'get' >> >> So what's a newbie to do? > >Raymond Hettinger has already pointed you to the relevant part of the >documentation. I will add that help *is* helpful. You just need to provide >some context: > >>>> allmovies = {} >>>> help(allmovies.get) > >will show you a short explanation of the dict.get() method. >Unfortunately help({}) does not come up with the help for dictionaries, but >it does mention the class (dict), so that the next step should work to your >satisfaction: > >>>> help(allmovies) # not very informative > >>>> help(dict) # nice > >help() has the additional benefit of working for third party (or your own) >code that provides docstrings: > >>>> def foo(bar): >... "Reliably foo any bar you care to mention" >... >>>> help(foo) > >Or, more likely: > >>>> import otten.statistics >>>> help(otten.statistics) # and old module, hope I threw in some doc :-) > There is also the interactive help, but it seems not as useful in one way, i.e., it does not seem to recognize dotted subjects: >>> help() Welcome to Python 2.3! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> get no Python documentation found for 'get' help> dict.get no Python documentation found for 'dict.get' help> ^Z You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. whereas >>> help(dict.get) Help on method_descriptor: get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. NB: Before you run interactive help on a totally unknown source, remember that it is not a passive inspection of the text -- it imports, and thus executes code: >>> print """ ... ====< unsafe.py >==== ... %s====================="""%file('unsafe.py').read() ====< unsafe.py >==== # unsafe.py """Show unsafe execution by interactive help through import""" def boxit(s): """Return string with ascii box around it""" width =max(map(len, s.splitlines())); bar = ['+-%s-+'%('-'*width)] def padded(s, w=width): return s + (len(s)>> help('unsafe') +--------------------+ | This could be | | any unsafe action! | +--------------------+ Help on module unsafe: NAME unsafe - Show unsafe execution by interactive help through import FILE c:\pywk\clp\unsafe.py FUNCTIONS boxit(s) Return string with ascii box around it Also note that in the same session, repeated help will not re-execute module texts, since import accesses previously imported modules when available. Regards, Bengt Richter From dave at pythonapocrypha.com Wed Dec 17 15:58:00 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 17 Dec 2003 13:58:00 -0700 Subject: tuples and cartesian coordinates References: <20031217201815.GA5831@nl.linux.org> Message-ID: <025501c3c4e0$75066e60$6401fea9@YODA> Gerrit wrote: > the FAQ says: > > > For example, a Cartesian coordinate is appropriately represented as a > > tuple of two or three numbers. > > I find it strange to use tuples for a coordinate. After all, a > coordinate represents a position of an object. Suppose I have a game > where the player has a position: isn't it stupid to use tuples rather > than lists or another type (maybe complex numbers?), because I want to > be able to change the position? > > Shouldn't coordinates be mutable? I _guess_ you could consider a coordinate to be a distinct entity. By moving you're not changing that entity, simply referring to a new one. So if your position were instead the name of the country the player is in, then by moving you wouldn't mutate (edit) the name of the country but would instead reference a different name. Hmm... this explanation might be a bit of a stretch, but that's what popped into my mind at least. The counter-argument would include (among other things), that it's wasteful to have to create a new tuple just to move the player. The counter-counter-argument is that the tuple vs list entry in the FAQ is one of those guidelinish things, and principles and guidelines are always the first to go when you get bit by the optimization bug. :) -Dave From remco at localhost Mon Dec 15 08:25:38 2003 From: remco at localhost (remco) Date: Mon, 15 Dec 2003 14:25:38 +0100 Subject: cPickle from 2.2 to 2.1 References: <3fdd9fa4$0$210$e4fe514c@news.xs4all.nl> <7xekv6l00f.fsf@ruckus.brouhaha.com> Message-ID: <3fddb65f$0$216$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > >"remco" writes: >> These drawbacks (backward/forward incompatibilities) occur nearly >> everywhere. I've used the Berkley db module, when it got updated, i had to >> deinstall Python, reinstall an old version, check out all my data to >> another format, deinstall the older python, and reinstall the latest >> version. Next i had to create a new Berkley database and put the data back >> in. > >That one got me too and it's a peeve of mine. I think the Python lib >should include a dbm implementation that it sticks to unless the user >specifically requests a different one. Using a newer library if it exists is always the prefered choice, i believe. But i would prefer an easy update of my databases as well ;) Maybe it would have been better if the newer berkley would have been renamed to something else, or be configurable in an ini/conf file anywhere. Because i can also see the advantage: if you run your application with a newer python release (and it doesn't break), you're using a faster and more stable library, i guess. So no pachting needs to be done. Cheers! Remco From aahz at pythoncraft.com Tue Dec 30 23:29:58 2003 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2003 23:29:58 -0500 Subject: Storing objects required by functions. References: Message-ID: In article , Jp Calderone wrote: > >It's a PGP signature. If the mail client you're using can't extricate the >plaintext part, I'd say it isn't a very good mail client. (Even mailman's >archiver deals with them the right way these days ;) I'm using netnews, not e-mail. PGP doesn't belong in netnews posts, IMO. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From adsl5lcq at tpg.com.au Thu Dec 18 19:42:49 2003 From: adsl5lcq at tpg.com.au (Glen Wheeler) Date: Fri, 19 Dec 2003 11:42:49 +1100 Subject: How to use a 5 or 6 bit integer in Python? Message-ID: Hello all, My program uses many millions of integers, and Python is allocating way too much memory for these. I can't have the performance hit by using disk, so I figured I'd write a C extension to define a new type. Problem is, my C knowledge is years old and regardless of my attempts distutils will not recognise my installation of the MS compiler. I am thinking, is there any easier way to use a 5 or 6 bit integer in python? Even a regular 8-bit would be fine. I only need to represent either 32 or 64 distinct numbers. thanks, Glen From mir4uu at yahoo.com Mon Dec 8 11:15:34 2003 From: mir4uu at yahoo.com (mir nazim) Date: 8 Dec 2003 08:15:34 -0800 Subject: small, fast and cross-platform flat-file database for python References: <3FC26BB2.6090800@wi.mit.edu> Message-ID: <425cc8d1.0312080815.6c893892@posting.google.com> Thanks guys for all ur concern well actually the project for which i needed this got delayed. anyway thanks i have noted all the ooptions here and will surely try thm bless-n-luck bye From ptmcg at austin.rr.com Mon Dec 8 09:04:55 2003 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 08 Dec 2003 14:04:55 GMT Subject: ANN: pythonfs - create linux filesystems in python References: Message-ID: Here's another idea, piggybacking on the /proc filesystem: Use this pseudo-filesystem to create a query front-end to a database, using a file directory application metaphor. The database could contain information on say patients in a hospital, or lots or equipment in a factory, or active claims in an insurance office. Then under the main directory, each claim could have a directory of its own, with sub-files containing a summary text description, a subdirectory of claim event "files," and so on. You could also have directories that organize claims by category or status, with "links" to the actual claim directories in the associated category directories. All of this with the GUI of a simple file browser (or a real browser!), and very flexible. If you find out that users often want to know about claims over a certain amount, or that have remained uncleared longer than a certain threshold period, just add another "directory." In a directory tree, it might look like: /claims /claimsByStatus /active /pendingEstimates /pendingMedical /pendingAdjuster /pendingLegal /closed /contested /claimsByAge /claimsByAmount /allClaimsByClaimant /A_G /H_M ... and so on. In reality there are no "files" or "directories," but this filesystem utility makes it look like there are. Or maybe just use this as a flexible rapid prototyping or requirements gathering technique - then once the structure stabilizes, build into an application GUI with menus (maybe leave the filesystem around for "expert" mode). -- Paul "Rene Pijlman" wrote in message news:fmt8tvcqgmduhj5e6c46fukbtihkvrjtg8 at 4ax.com... > David McNab: > >a framework which allows mountable linux filesystems to be > >implemented in pure python. > > Serious question: why? > > -- > Ren? Pijlman From fredrik at pythonware.com Tue Dec 16 05:08:51 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Dec 2003 11:08:51 +0100 Subject: Is there a lib which support .jpeg file with "RGBA" mode? References: <3FDDC8FE.AED055CB@engcorp.com> Message-ID: Peter Hansen wrote: > google12 wrote: > > > > Ann... I had tried to use Photoshop 7 to save a .png file with transparency > > as a .jpg file, and the transparency will be kept in the .jpg file. > > If JPEG doesn't support transparency, then clearly that couldn't have happened, > or Photoshop uses a non-standard JPEG format. > > Perhaps Photoshop "transparently" (no pun intended) saves the alpha data > to some other location, but magically restores it when you reload the .jpg? JPEG supports application-defined data segments ("app markers"), so Photoshop may simply pack the alpha layer using a suitable lossless compression (predictor plus zip?) and embed it inside the JPEG stream. or they may ignore that fact that using lossy compression for alpha layers isn't really a good idea... if anyone can mail me a sample (or better, post a sample somewhere, and mail me an URL), I can look into it. From __peter__ at web.de Thu Dec 4 07:55:53 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Dec 2003 13:55:53 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Jimmy Retzlaff wrote: > Peter Otten wrote: [...] >> However, I did not succeed in turning the old os.path.walk(), i. e. a >> function taking a callback, into a generator. Is there a general way > to do >> it without having to store all intermediate results first? >> >> >> Peter >> >> PS. No, I don't have a use case. Threads welcome if all else fails :-) > > I do have a use case. I've wrapped a C library for extracting files from > compressed archives (http://www.averdevelopment.com/python/). The C > library uses a callback, but exposing a generator in Python is much more > natural in my case. Of course, if you can change the code making the > callbacks you can typically just replace the call to the callback > function with a yield statement, but that doesn't work if you don't have > access to the source (or don't want the source changed). > > The reason I created my library is that my Python program reads in, > line-by-line, 100GB of data that has been compressed into a 2GB archive. > So, obviously I can't read it all in and then start yielding and I > really don't want to expand it to a disk file and then read it in, I > want to work on it as it is decompressed. > > My solution used threads. I'd love to know if someone comes up with a > solution not involving threads. Here's a simple example of my > thread-based approach: [Nice example of a thread-based generator, thanks] So far, no one has come up with a solution that avoids threads - short of Bengt Richter's ideas on changing the language that is. Below is my attempt on generalizing your code to turn any visit(callback) into a generator (not tested beyond the __main__ stuff): import Queue import threading # mark the position of the callback function in the argument list of visit() CALLBACK = object() def cbwrapper(visit, queuesize, *args, **kwd): """Wrap visit(..., callback, ...) as a generator using threads""" queue = Queue.Queue(maxsize=queuesize) sentinel = object() # XXX should keyword args be allowed? # XXX should the len(args) == 1 case be tweaked to # return args[0] instead of a tuple? def callback(*args): queue.put(args) # replace the CALLBACK placeholder with the actual callback function args = list(args) try: args[args.index(CALLBACK)] = callback except ValueError: for key, value in kwd.iteritems(): if value is CALLBACK: kwd[key] = callback break else: # XXX raise Exception("Don't know where to put callback") # default to last positional for now args.append(callback) def launcher(): # XXX what if visit throws an exception? try: visit(*args, **kwd) except Exception, e: queue.put(e) else: queue.put(sentinel) threading.Thread(target=launcher).start() while True: value = queue.get() if value is sentinel: break elif isinstance(value, Exception): raise value yield value if __name__ == "__main__": def counter(length, callback): for i in range(length): callback(i) def multiply(first, callback, second): for i in first: for k in second: callback(i, k, i*k) def divide(first, second, callback): for i in first: for k in second: callback(i, k, i/k) for i, in cbwrapper(counter, 1, 10): print i, print for i, k, ik in cbwrapper(multiply, 1, range(3), CALLBACK, range(2)): print "%d * %d = %d" % (i, k, ik) for i, k, ik in cbwrapper(divide, 1, range(3), range(2)[::-1]): print "%d / %d = %d" % (i, k, ik) The question that has come up writing the above, how you would handle exceptions in the thread? I put them in the queue and reraise them in the main thread, but I'm not feeling very confident about it... Peter From nessus at mit.edu Mon Dec 8 00:57:07 2003 From: nessus at mit.edu (Douglas Alan) Date: Mon, 08 Dec 2003 00:57:07 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: "Greg Ewing (using news.cis.dfn.de)" writes: > Douglas Alan wrote: >> You'll be fine. The only thing you have to watch out for is that >> some rude folks here might call you names. > That would add some spice to Python's error messages... > Python 3.7 (#1, Sep 31 2007, 14:19:37) > [GCC 5.6.7] on slartibartfast > Type "help", "copyright", "credits" or "license" for more information. > >>> t = (1, 3, 77, 654, 8) > Traceback (most recent call last): > File "", line 1, in ? > HumiliationError: The programmer is a pink-faced baboon (tuple used where > list would be more appropriate) Hmmm, could I catch the exception and then continue on anyway? Kind of like casting away const in C++? |>oug From __peter__ at web.de Tue Dec 30 18:12:28 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Dec 2003 00:12:28 +0100 Subject: Coding an extendable class References: Message-ID: Tobias Pfeiffer wrote: > I want to write a package of modules that deal with mathematical > graphs. So my plan is to have a main.py file where the basic operations > are done, like reading the file and creating an adjacence list and all > that. In this main.py file, there is created a Graph class with several > methods, such as deg(v) or delvertex(v). > And then, for all of the other things one can do with a graph, I want > to code other modules, e.g. a file euler.py for finding an Euler way > through the graph, that extends the class by the method eulerway(). I > know that I can do something like > > # graphtools/euler.py > import main > class Graph(main.Graph): > def eulerway(self): > [...] > > and then the Graph class imported from euler.py will have both the old > and the new methods. But what can I do if I want the end user to be > able to combine several modules and I don't know in which order he will > do? For example, by > import graphtools.main, graphtools.hamilton > I can do the thingy described above, but what is with something like > import graphtools.hamilton, graphtools.euler > ? In that case I want the class to have all of the methods defined in > the modules. How do I realize that in the best way? #__init__.py class Graph(object): def deg(self, v): # your code #euler.py class EulerMixin(object): def eulerway(self): # your code #hamilton.py class HamiltonMixin(object): def whatever(self): # your code The above are all in the graphtools package directory. Now a sample usage: #application.py import graphtools from graphtools import euler, hamilton class Graph(graphtools.Graph, euler.EulerMixin, hamilton.HamiltonMixin): pass The XXXMixin classes are not for standalone use, they should only call but not override the Graph methods. As long as the different mixins are orthogonal, i. e. do not affect each other all should be fine. Alternatively you can derive the hamilton/euler variants from graphtools.Graph. You must then design the different classes with cooperation in mind, as demonstrated below with three initialization routines which are assumed to be run only once: #__init__.py class Graph(object): def __init__(self): self.init() def init(self): print "init main" def deg(self, v): print "deg" #euler.py import graphtools class EulerGraph(graphtools.Graph): def eulerway(self): print "eulerway" def init(self): print "init euler" super(EulerGraph, self).init() #hamilton.py import graphtools class HamiltonGraph(graphtools.Graph): def whatever(self): print "whatever" def init(self): print "init hamilton" super(HamiltonGraph, self).init() #usegraphtools.py import graphtools from graphtools import euler, hamilton class Graph(euler.EulerGraph, hamilton.HamiltonGraph): pass g = Graph() g.eulerway() g.whatever() g.deg(1) Output: init euler init hamilton init main eulerway whatever deg Peter From andrew-pythonlist at puzzling.org Wed Dec 3 21:56:02 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 4 Dec 2003 13:56:02 +1100 Subject: newbie: suppressing return values In-Reply-To: References: Message-ID: <20031204025602.GC28006@frobozz> On Wed, Dec 03, 2003 at 07:41:13PM -0700, Jim Benson wrote: [...] > > In mathematica one can put a ; at the end of > a function call and the output is suppressed. > In this example if python behaved like mathematica in > this case one would see: > > >>> makeList(); > >>> > >>> makeList() > [1, 2, 3] > >>> > > Is there a simple way (other than the a = makeList()) > to do this "suppression" in python? You could do: import sys sys.displayhook = lambda x: None But that will turn it off indefinitely, rather than on a line-by-line basis, which seems to be what you're after... -Andrew. From newsgroups at jhrothjr.com Tue Dec 30 10:58:13 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Dec 2003 10:58:13 -0500 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: "Aahz" wrote in message news:bss5t7$1tf$1 at panix1.panix.com... > In article <99dce321.0312300655.14c5a8db at posting.google.com>, > David M. Wilson wrote: > > > >g = re.compile('...') > > > >def uses_global_yuck(x): > > global g > > pass > > Why not just use the global? Without the ``global`` statement, that is. > Don't like that? How's it any different from using a class instance? You can't parameterize it. You've got one global, while you can put different parameters in different class instances. He isn't doing that here, but that's the major place where the Function Object design pattern shines. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ From __peter__ at web.de Fri Dec 19 14:39:36 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2003 20:39:36 +0100 Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: MetalOne wrote: > I am trying to write a generator function that yields the index position > of each set bit in a mask. > e.g. > for x in bitIndexGenerator(0x16): #10110 > print x > --> 1 2 4 > > > This is what I have, but it does not work. > Changing yield to print, shows that the recursion works correctly. > > def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) > > What am I missing? The bitIndexGenerator(mask>>1, index+1) just returns a new generator which is immediately discarded. For a generator to do anything, you must invoke its next() method, and one way to do it is a for loop, e. g (not mask<0 proof): >>> def big(mask, index=0): ... if mask != 0: ... if mask & 1: ... yield index ... for result in big(mask>>1, index+1): ... yield result ... >>> for x in big(0x16): ... print x, ... 1 2 4 Peter From theller at python.net Mon Dec 29 17:20:52 2003 From: theller at python.net (Thomas Heller) Date: Mon, 29 Dec 2003 23:20:52 +0100 Subject: "Bad file descriptor" after py2exe or Installer References: <3FD8B25A.7080103@gmx.net> <3FD97E83.2000703@gmx.net> <3FDDCE47.2000708@gmx.net> Message-ID: [posted and mailed] Luc Saffre writes: > On 12.12.2003 15:41, Thomas Heller wrote: > >> py2exe seems to pick up cygwin binaries. The reason could be that >> either you have cygwin extensions somewhere in your pythonpath, or parts >> of the PATH env variable points into the cygwin directories, or >> something like that. You should look at the output above carefully, and >> make sure that it is what one would expect. > > That's it! Thank you, Thomas, your hint helped. > > I had the Cygwin tcltk package installed. After removing this package > (using cygwin's setup.exe), I can use again the original PIL/Image.py > and everything works fine. > > My PATH contains the cygwin bin directories: > PATH=u:\CYGWIN\BIN; > c:\python23\Scripts;c:\python23; > ... > u:\CYGWIN\USR\BIN;u:\CYGWIN\USR\LOCAL\BIN;... > > Another workaround is to remove the cygwin directories from PATH: > I reinstalled the cygwin tcltk and the problem reappeared, > moving the first cygwin directory to come after the python directory > did not help. Then I removed those directories completely from PATH > (during the build) and the problem disappeared again. > > I would consider this as a bug (in both py2exe and Installer) since > they decide to pick some cygwin tcl/tk dll's who happen to hang around > while the Python runtime won't... This is part of the code (in build_exe.py). def find_dependend_dlls(self, use_runw, dlls, pypath, dll_excludes): import py2exe_util sysdir = py2exe_util.get_sysdir() windir = py2exe_util.get_windir() # This is the tail of the path windows uses when looking for dlls # XXX On Windows NT, the SYSTEM directory is also searched exedir = os.path.dirname(sys.executable) syspath = os.environ['PATH'] loadpath = ';'.join([exedir, sysdir, windir, syspath]) # Found by Duncan Booth: # It may be possible that bin_depends needs extension modules, # so the loadpath must be extended by our python path. loadpath = loadpath + ';' + ';'.join(pypath) Can you try to change the last line into loadpath = ';'.join(pypath) + ';' + loadpath and report if this helps? Thanks, Thomas From missive at frontiernet.net Fri Dec 19 17:22:17 2003 From: missive at frontiernet.net (Lee Harr) Date: Fri, 19 Dec 2003 22:22:17 GMT Subject: control-c and threads References: Message-ID: On 2003-12-19, Srikanth Mandava wrote: > When a signal handler is registered in the main thread and > "control-c" is entered, the child thread is getting the > KeyboardInterrupt exception(The documentation says the main thread > MUST receive the signal handler function call if handler is > registered). > > In python 2.2.1 the main thread was always called with > the sigint signal handler which was registered. In my case the > child thread is waiting on stdin using "raw_input" function. This > seems to be causing all sorts of strange behavior in the program > once the child thread gets the keyboardinterrupt exception and > eventually leading to seg fault on a sys exit . > > Any idea why this is happening in 2.3.1? This scenario worked in > 2.2.1. Is this fixed in 2.3.2?. > > Do you have a minimal example that shows this behavior? I'd be happy to run it with 2.3.2 and test it out... PS> please post only plain text to the list. From newsgroups at jhrothjr.com Sat Dec 20 06:38:20 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Dec 2003 06:38:20 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Bengt Richter" wrote in message news:bs0amc$hsl$0 at 216.39.172.122... > On Fri, 19 Dec 2003 20:22:38 -0500, "John Roth" wrote: > > > > >"Steve Lamb" wrote in message > >news:slrnbu77jp.nh8.grey at dmiyu.org... > >> On 2003-12-20, John Roth wrote: > >> > a third is the ability to forget the empty parenthesis after > >> > a function/method call that doesn't require parameters. > >> > >> class ThisIs: > >> avariable = 'a' > >> def amethod(self): > >> return 'b' > >> > >> thisis = ThisIs() > >> print thisis.avariable > >> print thisis.amethod() > >> import this > >> print "Read line 2." > > > >I'm not sure what your point is. Your example isn't going > >to produce the expected result if you say: > > > >print thisis.amethod > > > >instead of > > > >print thisis.amethod() > > > >That is the place where I find Ruby syntax to be > >helpful: the amount of time where I want the method / > >function object is *far* lower than the amount of > >time I want to call it. It's one of those conundrums > >that doesn't seem to have a clean answer, though. > > > Ok, for line 2, run this ;-) > > class ThisIs: > avariable = 'a' > def amethod(self): > return 'b' > def silly(self): > return 'heh' > silly = property(silly) > > thisis = ThisIs() > print thisis.avariable > print thisis.amethod() > print thisis.silly > import sys > class L2(list): > def write(self, s): self.append(s) > sys.stdout = L2() > import this > L2 = ''.join(sys.stdout).splitlines()[2] > sys.stdout = sys.__stdout__ > print "Read line 2." > print '... which is:', L2 > > Regards, > Bengt Richter I think you're missing the point I was trying to make. Sure, you can use a property to not have to put in the explicit function call, but then you can't put in the explicit function call *anywhere* you use that property. Ruby syntax makes it *optional*. That's what is missing here. John Roth From tim.golden at viacom-outdoor.co.uk Thu Dec 11 04:32:46 2003 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 11 Dec 2003 01:32:46 -0800 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> <3fd728e3$0$213$e4fe514c@news.xs4all.nl> <3fd7471f@news.mt.net.mk> <3fd7ca1c_3@news.unc.edu> Message-ID: <8360efcd.0312110132.52fd8daa@posting.google.com> "Gary Bishop" wrote in message news:<3fd7ca1c_3 at news.unc.edu>... > ?????? ?. wrote: > > # ~/.pythonrc > > # enable syntax completion > > try: > > import readline > > except ImportError: > > print "Module readline not available." > > else: > > import rlcompleter > > readline.parse_and_bind("tab: complete") > > This will work on win32 as well if you download ctypes and then my > python implementation of gnu readline from > > http://prdownloads.sourceforge.net/uncpythontools/readline-1.1.zip?download Brilliant! Thank you very much indeed. I would add a warning for those Windows users who aren't also Linux users: by default you'll need to use Ctrl-D to exit the interpreter rather than Ctrl-Z. (I imagine this could be changed; I've given the source no more than a cursory glance). TJG From niemeyer at conectiva.com Sat Dec 13 08:55:12 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 13 Dec 2003 11:55:12 -0200 Subject: ANN: lunatic-python 0.1 In-Reply-To: <5iiltv4pf107ubuck3kqk6ob2d1jj3kvn4@4ax.com> References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> <5iiltv4pf107ubuck3kqk6ob2d1jj3kvn4@4ax.com> Message-ID: <20031213135512.GA2262@burma.localdomain> > But you left out the most important question: WHY? That's *exactly* the second topic in the web page, but since you obviously haven't looked at it, why do you care? Keep your arrogance for yourself please. -- Gustavo Niemeyer http://niemeyer.net From fredrik at pythonware.com Wed Dec 17 16:37:41 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Dec 2003 22:37:41 +0100 Subject: Stop popup cmd window References: <93f5c5e9.0312151328.1dbbd585@posting.google.com><93f5c5e9.0312160510.4354814e@posting.google.com> Message-ID: Derrick 'dman' Hudson wrote: > > Thanks for the tip... that did it. I need to read up on the difference > > between python.exe and pythonw.exe. Same program, linked in different ways. See below. > The difference is a Microsoft one. The former has stdin, stdout and > is a normal program. Microsoft dictates that on Windows such programs > must have a black window appear for the life of the program. Programs linked for the "console" subsystem (aka "character-mode applications") have to be connected to a console window. If they're not, Windows creates one for them. (I'm pretty sure this is done by the loader and not the C runtime). > The latter is an "MFC" (or whatever the proper term is) The "windows" subsystem. > The difference is the specific functions the C runtime calls to notify > Windows of which sort of app it is during startup. A linker option, usually (/subsystem) A console program may use the Windows API to disconnect from the console, or create a window, and a window program may use the API to create a console if it needs one (a version of pythonw that did this if/when the application prints to sys.stderr would be quite useful, btw) From bogdanal at b.astral.ro Fri Dec 19 13:07:32 2003 From: bogdanal at b.astral.ro (Bogdan Marinescu) Date: Fri, 19 Dec 2003 20:07:32 +0200 Subject: Parsing environment variables in ConfigParser files References: <3a8e83d2.0312190936.1746d659@posting.google.com> Message-ID: <017301c3c65a$fe3c8040$a3e3a4d5@darkore> Good idea, but since you want to do this, why stop here? I would really like to have the possibility to expand some previous defined variables in the file: [sect1] var1 = ... ............. expansion=${var1} Of course this should merely complete the environment variable replacement feature. ----- Original Message ----- From: "Matthew Barnes" Newsgroups: comp.lang.python To: Sent: Friday, December 19, 2003 7:36 PM Subject: Parsing environment variables in ConfigParser files > I'm considering submitting a patch for Python 2.4 to allow environment > variable expansion in ConfigParser files. The use cases for this > should be obvious. I'd like to be able to specify something like the > following in a configuration file: > > [section_name] > data_file=${HOME}/mydata.dat > > ...(where HOME=/home/matt) and have ConfigParser automatically expand > it to: > > [section_name] > data_file=/home/matt/mydata.dat > > The change is pretty straight-forward, but I'm interested in feedback > on whether this is a good idea, what the syntax for environment > variable references should look like (currently I'm thinking > ${varname}), or whether there are any hidden complexities or > backward-compatibility concerns. > > Matthew Barnes > -- > http://mail.python.org/mailman/listinfo/python-list From usenet03q2 at hczim.de Thu Dec 11 17:10:13 2003 From: usenet03q2 at hczim.de (Heike C. Zimmerer) Date: Thu, 11 Dec 2003 23:10:13 +0100 Subject: sys.argv with quoted strings as option argument References: <3FD818D9.40109@ttck.keio.ac.jp> Message-ID: Satya Arjunan writes: [args are re-parsed by sh:] > satya at kona printargs $ cat sh-python > #!/bin/sh > echo /usr/bin/python $* > exec /usr/bin/python $* > > satya at kona printargs $ ./printargs.py --libdir="/usr/lib /usr/local/lib" > /usr/bin/python ./printargs.py --libdir=/usr/lib /usr/local/lib > ['./printargs.py', '--libdir=/usr/lib', '/usr/local/lib'] You might want to use "$@" (including the double quotes) instead of $* to avoid splitting of the arguments at the intervening white space. - Heike From ben at adversary.org Sat Dec 20 05:14:41 2003 From: ben at adversary.org (Ben McGinnes) Date: Sat, 20 Dec 2003 21:14:41 +1100 Subject: semi-OT: DNS issues for python.org In-Reply-To: ; from aahz@pythoncraft.com on Sat, Dec 20, 2003 at 12:22:30AM -0500 References: Message-ID: <20031220211441.P749@devious.adversary.org> Aahz(aahz at pythoncraft.com)@Sat, Dec 20, 2003 at 12:22:30AM -0500: > > Yalumba is wrong. python.org has just been transferred, and xs4all is > now correct. Tell Yalumba to do a DNS reload and everything will be > fine. Cool, Yalumba reloads each night (in about an hour and a half actually) and should lose that data soon. Though not sure why my server couldn't get NS records, when I could get them directly from UltraDNS. Still, I can get them now, so it's all good. Regards, Ben -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 181 bytes Desc: not available URL: From mrfaro at libero.it Tue Dec 9 03:22:23 2003 From: mrfaro at libero.it (Gabriele Farina) Date: Tue, 09 Dec 2003 08:22:23 GMT Subject: [wxPython] Managing Skin engines References: Message-ID: <3DfBb.176468$hV.6692741@news2.tin.it> > The WMP's skins are in XML. It's perhaps more easy to look in XML side ? Ok, but hiow they can be displayed using wxPython?? I don't think I can use only XUL to manage something like that ... From reply.in.the.newsgroup at my.address.is.invalid Wed Dec 31 11:04:36 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 31 Dec 2003 17:04:36 +0100 Subject: dropping priveledges References: Message-ID: Kamus of Kadizhar: >Any way to get a python script to run with a specified user priveledges? http://groups.google.nl/groups?q=setuid+wrapper+python -- Ren? Pijlman From mike at nospam.com Wed Dec 10 15:45:21 2003 From: mike at nospam.com (Mike Rovner) Date: Wed, 10 Dec 2003 12:45:21 -0800 Subject: ANN: pythonfs - create linux filesystems in python References: <23891c90.0312100352.73db003c@posting.google.com> Message-ID: Paul Boddie wrote: > "Mike Rovner" wrote in message > news:... >> >> It reminds me of Microsoft's promise to combine RDBMS and file >> system in a new Longhorn OS. Several years ago that idea was highly >> popular but nothing came out. You misquoted me a bit ;) I ment (expanding the previous author) it can be used to provide "different views to the same data" (database) in contrast to the "same view on the different data" aka filesystem. > Longhorn isn't supposed to be out before 2006, unless you live in > Malaysia (apparently). Is this a message from the future? ;-) I red 2005. So I live on the same planet at least. :) > Actually, I can imagine that it isn't quite equivalent to the > much-hyped Longhorn features and the GNOME Storage stuff, since a > filesystem typically provides a fairly rigid naming interface, No. The whole idea was to invert that. You use familiar approach (and api) to get to dynamic data (as in /proc). >> That approach may be very interesting to allow user to use some >> plug-ins for the file system (access, security, notification, etc.). > > course)? Python lets you do HTTP, FTP and loads of other protocols > fairly trivially - imagine hooking that up to a filesystem interface. Right, the whole universe. Don't fix up on my list. Mike From charles at steinkuehler.net Thu Dec 18 10:13:49 2003 From: charles at steinkuehler.net (Charles Steinkuehler) Date: Thu, 18 Dec 2003 09:13:49 -0600 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> Message-ID: <3FE1C42D.6050505@steinkuehler.net> Stephen J. Bevan wrote: > Charles Steinkuehler writes: >> Using a forth-based solution to create the root ramdisk image would >> drastically reduce the footprint of the initial ramdisk image, remove >> reliance on a particular C runtime library (allowing folks to build >> runtime root images based on uClibc, glibc, or whatever), and provide a >> *VERY* powerful yet tiny runtime scripting/programming language for >> extending the system. > > IMHO what drastically reduces the footprint is not using glibc at all. Which is why I think that a small Forth kernel talking directly to the linux kernel is the best solution. -- Charles Steinkuehler charles at steinkuehler.net From exarkun at intarweb.us Sun Dec 21 19:50:28 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sun, 21 Dec 2003 19:50:28 -0500 Subject: How do I really delete an imported module? In-Reply-To: <20031221142407.3044616b.wtrenker@shaw.ca> References: <20031221142407.3044616b.wtrenker@shaw.ca> Message-ID: <20031222005028.GA19462@intarweb.us> On Sun, Dec 21, 2003 at 02:24:07PM +0000, William Trenker wrote: > I've been googling around trying to figure out how to delete an imported module and free up the memory it was using. One point of confusion, for me, is that if I "del" a module the virtual memory used by the process doesn't decrease. Using Python 2.3.2 on Linux, here is a simple test program that prints out the virtual memory size and the relative contents of the sys.modules dict at various points: > > import sys,os,pprint,sets > def vmem(text): > print '%s: VmSize=%skB'%(text,os.popen('ps h o vsize %s'%os.getpid()).read().strip()) > def mods(): > pprint.pprint(sets.Set(sys.modules.keys()) - baseModules) > baseModules = sets.Set(sys.modules.keys()) > vmem('begin') > import re > vmem('after import re') > mods() > del re > vmem('after del re') > mods() > > Here is the output: > > begin: VmSize=3348kB > after import re: VmSize=3408kB > Set(['strop', 'sre', '_sre', 'sre_constants', 're', 'sre_compile', 'sre_parse', 'string']) > after del re: VmSize=3408kB > Set(['strop', 'sre', '_sre', 'sre_constants', 're', 'sre_compile', 'sre_parse', 'string']) > > The sys.modules items related to the "re" library module are still showing up after "del re". And the virtual memory for the process has not been reduced. One important thing to realize is that "import re" does not just create one reference to the "re" module. It also creates a reference at sys.modules['re'], and possibly in many other places as well. Each of the modules listed in the output above also is referenced from sys.modules, so there is no possibility of them being garbage collected until that reference is removed. > > What is the pythonic way to completely delete a module and get it's memory garbage collected? > Another important thing to realize is that some modules may be implemented as extensions. The _sre module is one such module. This means that to import it, Python first calls dlopen() (or whatever the platform's equivalent is) on the file containing the object code. While it could later call dlclose() if it knows the module is no longer referenced, it does not. Even if it did, there is no guarantee that the underlying platform would then release the memory associated with it (Most platforms do, but not all). Python has no control over this. Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From bokr at oz.net Fri Dec 5 21:30:32 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Dec 2003 02:30:32 GMT Subject: Newbie question: Any way to improve this code? References: Message-ID: On Sat, 6 Dec 2003 00:06:16 -0000, "Duncan Smith" wrote: [...] > >Or you could replace the whole thing with, > >try: > f = open("firmas.txt",'r') > texto = f.read() > frases = texto.split('\n')[:-1] If you split on something, you don't have to eliminate it, but you may split off a trailing null string, to satisfy the logic that you should be able to join the list with the splitter and get back your original. Splitlines does what you want: >>> 'abc\ndef\n'.split('\n') ['abc', 'def', ''] >>> 'abc\ndef\n'.splitlines() ['abc', 'def'] >>> 'abc\ndef\n'.split('\n') ['abc', 'def', ''] >>> '\n'.join('abc\ndef\n'.split('\n')) 'abc\ndef\n' But the result of splitlines gives you the same last line whether it ends with \n or not, so you can't guarantee reconstruction: >>> '\n'.join('abc\ndef\n'.splitlines()) 'abc\ndef' More: >>> 'abc\ndef\n'.splitlines() ['abc', 'def'] >>> 'abc\ndef'.splitlines() ['abc', 'def'] >>> 'abc\ndef\n\n'.splitlines() ['abc', 'def', ''] >>> '\n'.splitlines() [''] >>> ''.splitlines() [] >>> 'a'.splitlines() ['a'] >finally: > f.close() > I think you forgot (oh, just realized the explanation for my amazement--you're not the other Duncan ;-) (maybe you didn't forget) that if the open doesn't succeed in the above, f will not be (re)bound, so f.close() will be problematical either way. I guess you could fix it (untested) by try: f = file("firmas.txt") try: frases = f.read().splitlines() finally: f.close() except Exception, e: print '%s: %s' %( e.__class__.__name__, e) Regards, Bengt Richter From fortepianissimo at yahoo.com.tw Mon Dec 22 00:38:49 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 21 Dec 2003 21:38:49 -0800 Subject: Singleton process Message-ID: Here is the situation: I have multiple processes of same Python script fired, but I want *only one* of them to continue and all the others to quit immediately. I can use a lock file, and the first process will get the necessary lock. But if I do open(lockfile) all the other subsequent processes will just wait there - instead I want them to quit immediately. Can someone give a simple outline of how to achieve this? Thanks a lot. From antonmuhin at rambler.ru Fri Dec 5 06:05:43 2003 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 05 Dec 2003 14:05:43 +0300 Subject: Thank you Message-ID: I'd like to thank people who responded to my question on different Python parser modules. I beg your pardon for a delay & for posting off topic. best regards, anton. From fredrik at pythonware.com Fri Dec 12 07:31:21 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Dec 2003 13:31:21 +0100 Subject: java.awt.Robot equivalent? References: Message-ID: Christopher Koppler wrote: > Is this capability available in any of the GUI toolkits (searching > Tkinter docs brought up nothing)? Is there a C library that I could > wrap? Or maybe I just need to use the Windows extensions. But if so, > how - I don't have the slightest idea how that would work. > > Anyone have any pointers? win32api's PostMessage might be useful. random google link: http://mail.python.org/pipermail/python-win32/2002-December/000635.html From oren-py-l at hishome.net Thu Dec 11 14:09:54 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 11 Dec 2003 14:09:54 -0500 Subject: What GUI toolkit looks the best? In-Reply-To: References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <20031211190954.GA54939@hishome.net> On Thu, Dec 11, 2003 at 06:46:49PM +0100, Carl wrote: > Paul Rubin wrote: > > > I've been approached about writing a Windows app which will need a > > really professional looking GUI. Forget TKinter, this has to actually > > look good (real artists will be available to get the visual stuff > > right). Assuming I write in Python, what's the best toolkit to use? > > Some cost in implementation pain is tolerable if the finished > > interface looks better as a result. It would be nice if the toolkit > > runs on multiple platforms rather than being Windows-only. > > > > I'm thinking Glade. Is that reasonable? I don't know squat about > > Windows and haven't done much fancy GUI programming since the early X > > days. > > > > Thanks. > > What's wrong with Jython? I haven't used it myself, but have always wondered > why it's not mentioned when different Python GUI:s are discussed. Jython + SWT is a pretty cool combination. SWT is a well-designed, high performance portable toolkit using native widgets. Python is our favorite language. If they could be married without Java it would be even better. Oren From p at trick.lu Thu Dec 18 16:02:59 2003 From: p at trick.lu (Patrick Useldinger) Date: Thu, 18 Dec 2003 22:02:59 +0100 Subject: urllib: http error codes References: Message-ID: Ok, found it myself... class MyURLopener(urllib.FancyURLopener): def http_error_default(self, url, fp, errcode, errmsg, headers): void = fp.read() fp.close() raise IOError, ('http error', errcode, errmsg, headers) urllib._urlopener = MyURLopener() -- http://www.homepages.lu/pu/ From __peter__ at web.de Tue Dec 16 08:01:43 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Dec 2003 14:01:43 +0100 Subject: Build classes/packages dinamicaly References: Message-ID: Paulo Pinto wrote: > Thanks it is want I was looking for. > However I still have a problem. > > I want to make the module available to the > caller as if he did an import. > > For example, if I make the following call > > some_module.generate_module('dummy') > > Where some_module is the module that generates > modules dinamicaly, and dummy is the name of the > new module. > > I would like to be able to do > > dummy.something() > > after that call. > > I've discovered that if I do something like this > > globals()['dummy'] = module_instance_returned_by_new.module() > > > It works, but it must be done at the same level I want to > call dummy.something() and not from inside some_module. Because > if I do it inside the module, globals() will be refering to the > module globals and not to parent scope. > > Basically I would like to import the generated module to the > module that is invoking generate_module() like an uplevel in > Tcl. > > Is this possible? Don't know, but rebinding in the calling scope from inside a function call looks like fighting the language to me. Maybe redefining __import__() would be better: import __builtin__ import types, sys originalimport = __builtin__.__import__ def myimport(name, *args): print "importing", name try: return originalimport(name, *args) except ImportError: print "generating", name module = types.ModuleType(name) exec "def demo(*args):\n\tprint 'demo%r' % (args,)\n" in module.__dict__ sys.modules[name] = module # put it into the cache return module __builtin__.__import__ = myimport I simply generate any module that cannot successfully be imported, but you could change this to meet your needs. Now a usage example: import myimport # put it first, because it messes with the built-ins print "first import" import os import generated print print "second import" import os, generated generated.demo("hi", "there") However, this is just a smoother variant of the module = generate("modulename") pattern. Peter From http Wed Dec 24 05:28:51 2003 From: http (Paul Rubin) Date: 24 Dec 2003 02:28:51 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> <7xr7yvjle5.fsf@ruckus.brouhaha.com> <21bb8d55.0312240144.4eb9caab@posting.google.com> Message-ID: <7xk74mik64.fsf@ruckus.brouhaha.com> andreif at mail.dntis.ro (Stormbringer) writes: > Sounds like a poorly designed system the one you messed with. The system I messed with wasn't designed for high volumes of updates. > Even if it was limited i/o traffic I am not sure how to do profiling > to find out if this is the case (although I do have doubts about this) > - any suggesions how ? A crude but maybe useful thing you can do is just observe the CPU load while the program is running. If the CPU load is low but you hear the disk banging around, you're i/o bound. As for profiling, there's a Python profiler documented in the Python library manual, that's the first thing to try. There's a good article series on full text indexing at tbray.com which might interest you, by the way. It was linked from Slashdot a couple days ago. From exarkun at intarweb.us Sat Dec 20 16:09:20 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 20 Dec 2003 16:09:20 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: <20031220210920.GA15680@intarweb.us> On Sat, Dec 20, 2003 at 08:01:05PM +0000, Jarek Zgoda wrote: > David M. Wilson pisze: > > > Unless you design some silly rules to determine when empty parenthesis > > should be allowed - did a get assigned the return value of sys.exit()? > > (yes I know it doesn't have one) > > It has. The returned value is None. A function must return to have a return value. When does sys.exit() return? Jp > > -- > Jarek Zgoda > Unregistered Linux User # -1 > http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Mon Dec 15 07:01:10 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Dec 2003 13:01:10 +0100 Subject: cPickle from 2.2 to 2.1 References: <3fdd9fa4$0$210$e4fe514c@news.xs4all.nl> Message-ID: "Unknown" wrote: > If this doesn't matter: why not UUencode any unicode string > when writing it to the xml? eh? XML is based on Unicode, so why not just use a real text encoding? From tjreedy at udel.edu Wed Dec 10 10:38:35 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Dec 2003 10:38:35 -0500 Subject: cell object dereferencing References: <3FD5FD4A.9060406@jandecaluwe.com> <3FD6EA60.2000905@jandecaluwe.com> Message-ID: "Jan Decaluwe" wrote in message news:3FD6EA60.2000905 at jandecaluwe.com... > Jan Decaluwe wrote: > > Is there a way to dereference a cell object (that is, get > > the object that it references to) in Python? > > I got the following response from Samuele Pedroni.: > well you can ... use this hack (it's a huge hack but it is safe and does the trick): > def proto_acc(v=None): > def acc(): > return v > return acc > acc0 = proto_acc() > import new > make_acc = lambda cell: (new.function (acc0.func_code,acc0.func_globals,'#cell_acc',acc0.func_defaults,(cell,))) > def cell_deref(cell): > return make_acc(cell)() Cute, Samuele. If function.func_closure were writable (which it is not) then I believe the last four lines could be condensed as the more readable def cell_deref(cell): acc0.func_closure = (cell,) return acc0() but since it is not, you instead make a new function that is a near copy of acc0 but with (cell,) substituted as *its* func_closure. Terry J. Reedy From guettli at thomas-guettler.de Thu Dec 18 06:44:37 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 18 Dec 2003 12:44:37 +0100 Subject: Standalone client database for Python? References: Message-ID: Am Wed, 17 Dec 2003 12:07:01 -0300 schrieb Gustavo Campanelli: > What are our options for a standalone (that is one that's not > client/server) easily accesible from Python? > I'm not going to ask for special features as this is only to see what is > avaiable and used (most used most probably meaning well maintained > project). If you don't need a relational database (SQL) you can look at ZODB. It is easy accesible from python since it is coded in python. thomas From skip at pobox.com Fri Dec 5 15:24:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Dec 2003 14:24:01 -0600 Subject: Lists and Tuples In-Reply-To: References: Message-ID: <16336.59745.195972.24309@montanaro.dyndns.org> Roy> That's a good example, because it makes for a nice segue. If you Roy> were holding data from a form that looked like: Roy> Street: ___________________________ Roy> City: ___________________________ Roy> State: ___________________________ Roy> Zip: ___________________________ Roy> Then I agree you're looking at a 4-tuple (assuming you didn't want Roy> to go whole-hog and define an Address class). But, imagine a Roy> somewhat more generic form that looked like: Roy> Address line 1: ________________________ Roy> Address line 2: ________________________ Roy> Address line 3: ________________________ Roy> Address line 4: ________________________ Roy> You might fill in exactly the same data, but now if feels like it Roy> should be a list. I think you're thinking too hard. ;-) What about: Street 1: ___________________________ Street 2: ___________________________ Street 3: ___________________________ City: ___________________________ State: ___________________________ Zip: ___________________________ ? I might use a tuple containing a list. Of course, in some situations, the "natural form" your data takes has other external influences. If I was storing addresses in a SQL table I might use a tuple of five strings (one per column in the database) and just suffer with the fact that I couldn't have more than three street elements. If addresses were stored in a pickle file, I'd might go with a tuple containing a list and three strings. have-we-completely-snowed-the-OP-yet?-ly, y'rs, Skip From http Sun Dec 14 08:34:35 2003 From: http (Paul Rubin) Date: 14 Dec 2003 05:34:35 -0800 Subject: intro to python books References: Message-ID: <7xbrqbldzo.fsf@ruckus.brouhaha.com> Kamus of Kadizhar writes: > I'm looking for a good intro to python book. I'm very familiar with > programming, but know nothing of OOP or systems (OS type) > programming. All of my programming experience is in number crunching > and generic graphics engines (read: gobs and gobs of matrix > manipulations and super-efficient sorts), all of it in C. You should do fine starting with the online tutorial at www.python.org. It's not terribly complete and it's a little bit dated, but it will help you get the hang of Python. From hwlgw at hotmail.com Sat Dec 6 15:40:43 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 6 Dec 2003 12:40:43 -0800 Subject: Help: Uploading .zip to Python CGI Message-ID: I am uploading a .zip file to a Python CGI program, using a form on a HTML page with ... In the Python CGI program I do: import cgi fStorage = cgi.FieldStorage() zipdata = fStorage['yourfile'].value print "Content-type: text/plain" print print len(zipdata) Now the length of the zipdata is 100, where it should be about 2635...and unzipping it with zipfile of course gives the "not a zip file" error. The last part of the data that is received by the CGI script is: \xf2\xf1!0\xdbS\xa9 and the next one *should* be \x1a It seems that the .zip data is being truncated, but I don't know where in my tool chain. The strange thing is that the Python CGI script *does* work on a Apache 1.3.27 server at work (unix), but gives the error above when run on my laptop with Windows XP and Apache 1.3.27 and also with the Apache version 2.0.48 I tried later. Does anybody have a clue what is going on? Maybe the error is with the Windows version of Apache? Or is it a Python problem (the unix server has Python 2.1.1). From garys at ihug.com.au Mon Dec 8 16:21:16 2003 From: garys at ihug.com.au (Gary Stephenson) Date: Tue, 9 Dec 2003 08:21:16 +1100 Subject: Pyrex problem - Py_NoneStruct Message-ID: I'm getting a clean generate, compile and link from my .pyx script, but when I attempt to run the resultant .exe, I get: "The procedure entry point Py_NoneStruct could not be located in the dynamic link library python23.dll" Can anybody provide me with a clue here? I've already cut down my script to remove all references to None, Py_None, NULLs, etc, but to no avail. fwiw I'm using latest Pyrex and ActiveState build 232. many tias, gary From pecora at anvil.nrl.navy.mil Wed Dec 17 10:06:59 2003 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Wed, 17 Dec 2003 10:06:59 -0500 Subject: Python as a numerical prototyping language. References: Message-ID: In article , Oren Tirosh wrote: > > Where is Python heading? Will it be a viable replacement for traditional > > number-crunching languages in the near-term future? > > It already is. When dealing with large vectors Numerical Python is your > friend. The overhead of the interpreter is negligible since most of the > time is spent in highly optimized vector operations. > > When operations are done on individual objects Python is significantly > slower than compiled languages but psyco is making great progress in this > area. It already approaches the performance of C for simple code using > only integers and floats. > > Oren This is good news. I, too, use Python preferentially for numerics, especially exploration of algorithms and numerical techniques. I gave up on Mathematica long ago (powerful, but awful for programming) and I've avoided MatLab so far (good, but not as nice as Python to program and expensive). Only problem ocassionally is that many engineers were raised on MatLAB and expect to be handed MatLab files/scripts to just run on their data. I'll have to check Psyco. If it does what you say, that would be a BIG step. -- -- Lou Pecora My views are my own. From grey at despair.dmiyu.org Sun Dec 21 16:22:00 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sun, 21 Dec 2003 21:22:00 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: On 2003-12-21, Jarek Zgoda wrote: > Jp Calderone pisze: >> A function must return to have a return value. When does sys.exit() >> return? > Something, that is of type NoneType. He didn't say what, he said when. Can anyone show a program that will evaluate the return of sys.exit() and successfully parse it? =D -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From bokr at oz.net Sun Dec 7 22:36:57 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Dec 2003 03:36:57 GMT Subject: Efficient MD5 (or similar) hashes References: <3FD3D200.FBE1FD47@alcyone.com> Message-ID: On Sun, 07 Dec 2003 17:21:04 -0800, Erik Max Francis wrote: >Kamus of Kadizhar wrote: > >> I want to check the integrity of the files after transfer. I can >> check >> the obvious - date, file size - quickly, but what if I want an MD5 >> hash? >> >> From reading the python docs, md5 reads the entire file as a string. >> That's not practical on a 1 GB file that's network mounted. > >Python's md5 module just accepts updating strings; the driving code >certainly doesn't have to read the file all in at once. Just read it in >a chunk at a time: > PMJI, but don't forget to open the file in binary, e.g., theFile = file(thePath, 'rb'), if you're on windows. > hasher = md5.new() > while True: > chunk = theFile.read(CHUNK_SIZE) > if not chunk: > break > hasher.update(chunk) > theHash = hasher.hexdigest() > Regards, Bengt Richter From http Sat Dec 13 06:41:21 2003 From: http (Paul Rubin) Date: 13 Dec 2003 03:41:21 -0800 Subject: Style question References: Message-ID: <7xr7z9kkri.fsf@ruckus.brouhaha.com> Kamus of Kadizhar writes: > remoteKD5hash = string.strip(Socket.recv(256)) ? > > Or something better? I think the preferred syntax these days is Socket.recv(256).strip() but either way works. From gduzan at bbn.com Wed Dec 31 12:47:33 2003 From: gduzan at bbn.com (Gary D. Duzan) Date: Wed, 31 Dec 2003 17:47:33 GMT Subject: GO AHEAD -MAKE ME LOOK DUMB- Please References: <2_ednbq16ZkVg2-iRVn-iQ@comcast.com> Message-ID: In article <2_ednbq16ZkVg2-iRVn-iQ at comcast.com>, Aubrey Hutchison wrote: >I have exhausted places to look for where "PYTHONPATH" is located.. > >In windows (using the DOS command) no such thing exist but path does. >I find no file with that name. >I have yet to find a config file that I would think might work as >PYTHONPATH. > >What am I missing? Run regedit.exe . Look at HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\[version]\PythonPath . Be enlightened. :-) Gary Duzan BBN Technologies A Verizon Company From skip at pobox.com Fri Dec 26 15:38:25 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Dec 2003 14:38:25 -0600 Subject: dynamic typing question In-Reply-To: <8ef9bea6.0312261227.56ade9a9@posting.google.com> References: <8ef9bea6.0312261227.56ade9a9@posting.google.com> Message-ID: <16364.40001.660677.87503@montanaro.dyndns.org> HJL> One static typing advantage I've run into: HJL> When you change the name of a variable in a class, and re-compile HJL> the program, the compiler shows you ALL places where compilation HJL> fails. These could be hundreds of places in dozens of files. ... HJL> I am sure Python people have come up with strategies to deal with HJL> this problem. That's what I'd like to hear. (Unit test is one As others have pointed out, pychecker is good at catching these sorts of problems. HJL> I would like to hear more real-life experience rather than academic HJL> conjectures. I've used pychecker in real-life to detect these sorts of problems, in other peoples' code no less, even though I have a (non-academic) position at Northwestern University. ;-) Skip From tungwaiyip at yahoo.com Tue Dec 30 16:11:15 2003 From: tungwaiyip at yahoo.com (Tung Wai Yip) Date: Tue, 30 Dec 2003 13:11:15 -0800 Subject: twisted mail server - SMTP AUTH extension not supported References: Message-ID: Hello, I have no experience in Twisted. However I'm looking for a sendmail replacement after my exim died for no apparent reason. I bet a python based MTA would be more easy to configure and manage. Do you have any recommendation? Is there a lot of work to setup twisted as a MTA? tung On 30 Dec 2003 11:05:53 -0800, cartermark46 at ukmail.com (Mark Carter) wrote: >I'm trying to create a mail server in Twisted. > >I either get >SMTPSenderRefused >or >SMTPException: SMTP AUTH extension not supported by server. > >What do I need to do to get it to work? > > >--- Here is the server: > >from twisted.internet import reactor > >from twisted import mail >import twisted.mail.mail >import twisted.mail.maildir > >service = mail.mail.MailService('ExampleMail') >smtp = service.getSMTPFactory() >pop3 = service.getPOP3Factory() > >domain = mail.maildir.MaildirDirdbmDomain(service, '/temp') >domain.addUser('salvador', 'gala') >service.addDomain('dali', domain) > >reactor.listenTCP(25, smtp , interface='dali') >reactor.listenTCP(110, pop3 , interface='dali') > >reactor.run() > >--- Here is the client that tries to send an email: > >import smtplib >from email.MIMEText import MIMEText >addr = 'salvador at dali' > >msg = MIMEText('Body of message') >msg['From'] = addr >msg['Subject'] = 'Note to myself' >msg['To'] = addr > >server = smtplib.SMTP('dali') >server.login('salvador', 'gala') # see note 1 >server.sendmail(addr, addr ,msg.as_string()) >server.quit() > >--- Notes: > >1. If I keep in the line: >server.login('salvador', 'gala') # see note 1 >the client complains: > server.login('salvador', 'gala') > File "C:\Python23\lib\smtplib.py", line 546, in login > raise SMTPException("SMTP AUTH extension not supported by >server.") >SMTPException: SMTP AUTH extension not supported by server. > >If I comment it out, the client complains: >SMTPSenderRefused: (451, 'Requested action aborted: error in >processing', 'salvador at dali') >and the server prints the message: >Failure: twisted.cred.error.UnhandledCredentials: No checker for >twisted.cred.credentials.IAnonymous, >twisted.cred.credentials.ICredentials >... smtp.py:553: DeprecationWarning: > Returning None from validateFrom is deprecated. Raise >smtp.SMTPBadSender >instead > "Raise smtp.SMTPBadSender instead", DeprecationWarning" From fredrik at pythonware.com Wed Dec 10 05:38:07 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Dec 2003 11:38:07 +0100 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> Message-ID: Stuart Bishop wrote: > That is scary - you need to treat anything arriving from the client > as an attack. I hope you mean "potential attack", right? or are you calling in local law enforcement everytime anyone asks for a web page from your server? ;-) From fumanchu at amor.org Mon Dec 8 13:27:54 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 8 Dec 2003 10:27:54 -0800 Subject: Class problem Message-ID: Let's hope your home version had double underscores surrounding "init". ;) class ImagePyramid: def __init__(self, parameters): do stuff :-) Robert Brewer MIS Amor Ministries fumanchu at amor.og > -----Original Message----- > From: Daniel Pryde [mailto:dpryde+usenet at cis.strath.ac.uk] > Sent: Monday, December 08, 2003 10:02 AM > To: python-list at python.org > Subject: Re: Class problem > > > Rene Pijlman wrote: > > > Daniel Pryde: > > > >>when I import it and try to make an instance of it, it returns with > >>the error that 'module' is not callable. > > > > > > My guess is you should do: > > > > import spam > > eggs = spam.spam() > > > > instead of: > > > > import spam > > eggs = spam() > > > > If not, please post the source code and exact text of the > error message. > > > > Thanks. Sorry everyone for not posting the problem code with > it. I only > have internet access at university and unfortunately the code's on my > home hard drive, however it was something like: > =========== > import Image > > class ImagePyramid: > def _init_(self, parameters): > do stuff :-) > =========== > > And I would use it as such: > =========== > import ImagePyramid > pyramid = ImagePyramid(parameters) > =========== > > I'l try out the above solution and hopefully that'll fix > things. Thanks.:-) > > Daniel > > -- > http://mail.python.org/mailman/listinfo/python-list > From loic at yermat.net1.nerim.net Tue Dec 30 16:12:05 2003 From: loic at yermat.net1.nerim.net (Yermat) Date: Tue, 30 Dec 2003 22:12:05 +0100 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: or even shorter >>> d = {'key1' : ('value1','value2'), 'key2': ('value3',) } >>> dict([(v,k) for k in d.iterkeys() for v in d[k]]) {'value3': 'key2', 'value2': 'key1', 'value1': 'key1'} "anton muhin" a ?crit dans le message de news:bssgf2$10nt3$1 at ID-217427.news.uni-berlin.de > Irmen de Jong wrote: >> Hi >> I have this dict that maps a name to a sequence of other names. >> I want to have it reversed, i.e., map the other names each to >> the key they belong to (yes, the other names are unique and >> they only occur once). Like this: >> >> { "key1": ("value1", "value2"), "key2": ("value3,) } >> >> --> >> >> { "value1": "key1", "value2": "key1", "value3": "key2" } >> >> What I'm doing is using a nested loop: >> >> dict2={} >> for (key,value) in dict1.items(): >> for name in value: >> dict2[name] = key >> >> which is simple enough, but I'm hearing this little voice in >> the back of my head saying "there's a simpler solution". >> Is there? What is it? ;-) >> >> Thanks >> --Irmen. >> > > It's seems like rather nice Python for me ;). Two more variants: > > inverted = {} > for k, vs in d.iteritems(): > inverted.update(dict([(v, k) for v in vs])) > > map( > lambda (k, vs): inverted.update(dict([(v, k) for v in vs])), > d.iteritems() > ) > > happy new year, > anton. From donn at drizzle.com Tue Dec 16 00:30:22 2003 From: donn at drizzle.com (Donn Cave) Date: Tue, 16 Dec 2003 05:30:22 -0000 Subject: Terminal "hang up" problem References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: <1071552620.841508@yasure> Quoth JD : ... | Control-c or control-d has NO effect, so it's hung up somewhere, but | we have no idea | where. One way to look at it might be ktrace. Somewhere in there, you're stuck in one of those damned kernel mediated services like NFS, and some ioctl to the offending device will be the last syscall reported for the process. lsof might be good enough. Donn Cave, donn at drizzle.com From robin at jessikat.fsnet.co.uk Mon Dec 1 03:49:47 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 1 Dec 2003 08:49:47 +0000 Subject: medusa as win32 service References: Message-ID: In article , Mark Hammond writes >Robin Becker wrote: > >> I wonder if this is the right way to write a medusa(asyncore) server >> with the win32all framework. Other example services seem to create an >> event to pass the stop signal from SvcStop into a separate termination >> method, but I'm unsure how that would mix with the polling loop. >> >> This simple framework seems to start and stop OK, but I wonder if I'm >> missing some obvious race or something. > >SvcStop will be called on a different thread. I don't know enough about >socket semantics to know if this is an issue. > >When I've tried to play with async based services, IIRC there were a few >problems if a connection existed at shutdown time. If "close" could >ever block, then Windows would get quite upset. If a "close()" ever >fails, then I guess there is a risk that the main loop will not >terminate, again making Windows upset. But as above, I don't know >enough about the framework to comment on the risks here. > >So really, the issues are all Python related - the win32 interactions >appear OK, assuming close could never block. > >For the SpamBayes project, our framework needed a "clean shutdown" to >save our databases etc, so we ended up using urlopen to connect to a >special "shutdown" URL. I didn't write that part, so I don't understand >if there was a better option. > >Hope this helps a little :) > it does indeed as I'm then into ensuring that the close methods are reasonable. So I guess the problem reduces to whether the simple medusa services ftp/http are cleanly terminatable. As a matter of interest how does one get rid of LEGACY services? Whilst getting the above going I seem to have created a LEGACY_MEDUSASERVICE in the registry. All attempts at deletion fail. >Mark. > -- Robin Becker From halloleo at noospaam.myrealbox.com Sun Dec 21 23:25:04 2003 From: halloleo at noospaam.myrealbox.com (leo) Date: Mon, 22 Dec 2003 15:25:04 +1100 Subject: manpage of python 2.3? References: <3fe63429$0$242$e4fe514c@news.xs4all.nl> Message-ID: "Irmen de Jong" wrote in message news:3fe63429$0$242$e4fe514c at news.xs4all.nl... > leo wrote: > > > but i couldn't find a manpage (i use cygwin) nor a general documentation > > which commandline switches python recognizes. > > > > any idea? > > Try python -h from a dos prompt? thanks for your hint, but that's still not a real manpage, processable by man; - with all its conviniece: - viewing in emacs - printing with mapga e print, etc. so, is there a real manpage for python2.3. around? thanks, leo From tjreedy at udel.edu Wed Dec 17 23:36:27 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Dec 2003 23:36:27 -0500 Subject: filter and map / deprecated? References: Message-ID: "Logan" wrote in message news:pan.2003.12.17.18.35.25.713854 at phreaker.nospam... > I read in PEP 279 the following comment by GvR: > > "filter and map should die and be subsumed into list > comprehensions, not grow more variants." > > Actually, I am using 'filter' and 'map' a lot in my scripts > (not really because they are necessary, but more because I > like them). Should I avoid the usage of 'filter' and 'map' > in the future? The above comment by GvR makes me a little > bit afraid that they will become deprecated one day and that > I will have to change many of my scripts then. Removing filter, map, etc, totally would be a contentious and controversial move and would make many people unhappy. I do not anticipate it. It has been proposed on PyDev that they be moved to a 'functional' module (name not yet decided), perhaps with other stuff added, and I believe that Guido said he would be amenable to that. This I do anticipate. The threshhold for being in a module is much lower than the threshhold for being added to and eventually for remaining in the builtins. So I would continue with your preference with the expectation that some years from now you would have to run 2.x scripts through a search and replace script to run them with Python 3. But I expect that will be true anyway to cope with other changes. I also expect that people will use 2.final for years after the arrival of 3.0 (Just as 1.5.2 is still in use today.) Terry J. Reedy From eli at elipollak.com Wed Dec 24 02:36:30 2003 From: eli at elipollak.com (Eli Pollak) Date: Wed, 24 Dec 2003 18:36:30 +1100 Subject: help, function to get variable type References: <11012698219.20031224142514@chead.org> Message-ID: if isinstance(var,str): print 'string' elif isisnstance(var,int): print 'int' elif isinstance(var,list): print 'list' elif isinstance(var,someobject) # where someobject is a class that has been defined print 'someobject' ----- Original Message ----- From: "iip" To: Sent: Wednesday, December 24, 2003 6:25 PM Subject: help, function to get variable type > Hi All, > > What is the function to check the varible type, for example, below is like > in my clipper language: > > x = valtype(m) > > x will be "N", "C", "A", etc... > > thanks, > > -iip- > > > -- > http://mail.python.org/mailman/listinfo/python-list > From daniels at dsl-only.net Mon Dec 1 16:44:57 2003 From: daniels at dsl-only.net (sdd) Date: Mon, 01 Dec 2003 13:44:57 -0800 Subject: un-tuple (newbie) In-Reply-To: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> References: <035msv4u319mhl80hhd6i3j9ife38n3sms@4ax.com> Message-ID: <3fcbc37c$1@nntp0.pdx.net> Martin Doering wrote: > I want to use Jython to fetch exactly one value from a database query, > like here: > > # execute a query > def query(db, sql): > c = db.cursor() > c.execute(sql) > for line in c.fetchall(): > val = line val, = line # one way (val,) = line # same as above (perhaps more readable?) val = line[0] # another way > print val > c.close() > return val Personally, I'd call it "cursor", not "c". Also my DB predeliction leads me to prefer calling it a "row", not a "line". If you know (and don't care to check) that a single row is returned, with a single value, I might try something like this: def single_value_query(db, sql): cursor = db.cursor() try: cursor.execute(sql) return cursor.fetchone()[0] finally: cursor.close() From mir4uu at yahoo.com Fri Dec 19 02:17:46 2003 From: mir4uu at yahoo.com (mir nazim) Date: 18 Dec 2003 23:17:46 -0800 Subject: Standalone client database for Python? References: Message-ID: <425cc8d1.0312182317.10fd5cce@posting.google.com> Gustavo Campanelli wrote in message news:... > What are our options for a standalone (that is one that's not > client/server) easily accesible from Python? > I'm not going to ask for special features as this is only to see what is > avaiable and used (most used most probably meaning well maintained > project). > > Thanks in advance > > Gedece hi, well if u don't want SQL based database there is one called KirbyBase. it is written in python. it is a single file. sample multiuser server is included.i have not used it but may be helpful for u. u can find it here. www.netpromi.com/kirbybase.html From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sat Dec 27 08:24:18 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 27 Dec 2003 14:24:18 +0100 Subject: Project dream In-Reply-To: References: <3fecb9f1$0$326$e4fe514c@news.xs4all.nl> Message-ID: <3fed8801$0$330$e4fe514c@news.xs4all.nl> Will Stuyvesant wrote: >>[Irmen de Jong] >>While not written *in* Python, it's scriptable with Python: >>http://www.thangorodrim.net/pangband.html (PAngband). >> >>waaay back someone even created an Amiga version of this >>game based upon Amiga Angband and my AmigaPython port :) > > > You did an AmigaPython port? Fun! How long does something like that > take? Yeah, I did, years ago :-) See: http://www.aminet.net/aminet.cgi?string=python+language How long it took to port Python to the Amiga? A few weeks work in my spare time... I used a totally different compiler and had to adapt and extend the code to AmigaDOS. How long it took to create a PAngband version on the Amiga? I have no idea, I wasn't involved in that :-) > How long do you think a new roguelike from scratch would take in > Python and where the most time is spent? I am afraid of a lot of work > on options like magic and +ToHit etc., while I am more interested in a > smaller set of options but with a really smart AI. If you're creating a game from scratch, most time will be spent in game rules, combat rules, and balancing (!). Creating a good balanced game is hard, I've been told. Depending on what you want to do the actual programming can take a lot of time too, if you want 'really smart' AI... If you want to do a single player experience you'll need that, if you go for a (massive?)multiplayer experience you don't really need smart AI because the other characters are also played by humans :-) But that's not 'roguelike', is it? --Irmen From has.temp at virgin.net Wed Dec 3 05:33:45 2003 From: has.temp at virgin.net (has) Date: 3 Dec 2003 02:33:45 -0800 Subject: Separation of content and code for web (was Re: Python for web?) References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> Message-ID: <73c38014.0312030233.1c051da5@posting.google.com> Peter Hansen wrote in message news:<3FCC9A98.193ED480 at engcorp.com>... > Apparently all you PyMeld types like to lie in wait and then reply in > groups. ;-) > > Thanks Richie! (and Paul and Hamish, for the same answer) This looks > promising. Au-contraire: I was shamelessly whoring my own solution, HTMLTemplate.:) Same basic idea: munch an XHTML template into objects according to tag attributes, but the implementation and API are quite different. Give it a go, I'd be interested to know what you think. > I'm looking forward to a more extensive look at it. (I was about to say > I'd be happy to contribute improvements, but we (a company) were planning > to release our own under a BSD license at some point, whereas I see yours > has the more restrictive SleepyCat license (commercial use for a fee only), > so I'm afraid I might do nothing more than pick over the best ideas from > your API rather than look into the code itself.) FWIW, HTMLTemplate is LGPL. HTH has From jacek.generowicz at cern.ch Wed Dec 10 04:32:26 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 10:32:26 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: "Francis Avila" writes: > It is probably possible to custom-build a code object which makes _cache a > local reference to the outer cache, and play with the bytecode to make the > LOAD_DEREF into a LOAD_FAST, but it's not worth the effort. I'm tempted to agree. > Jacek, I think this is as fast as pure Python will get you with this > approach. That's pretty much what I thought ... which is why I was (reluctantly) investigating the C approach. > If the speed is simply not acceptable, there are some things you > need to consider, Is this the *real* bottleneck? Well, when I profile the code, proxy comes out at the top in terms of total time. Yes, there are other functions that are hotspots too. Yes, maybe I'm being completely stupid, and 99% of those calls are unnecessary. However, I simply thought that if I can increase the speed of "proxy" by a factor of 3 or 7 or something, without too much pain, by recoding it in C, then I'd get a noticeable speed gain overall. If it involves re-hacking the interpreter, then I won't bother. > Consider this before you delve into C solutions, which greatly increase > headaches. You don't need to tell me that :-) > An easy way to check is to cut out the map and memoization and > just use a dictionary preloaded with known argument:value pairs for a given > set of test data. > > e.g., > > def func(...): > ... > > data = [foo, bar, ....] > cache = dict([(i, func(i)) for i in data]) > > def timetrial(_data=data, _cache=cache): > return map(_cache.__getitem__, _data) > # [operator.getitem(_cache, i) for i in _data] *might* be faster. > > then timeit.py -s"import ttrial" "ttrial.timetrial()" I tried something similar, namely inlining the try: return cache[args] except KeyError: return cache.setdefault(args, callable(*args)) rather than using proxy. This gives a little over a factor of 3 speedup, but it's not something I can use everywhere, as often the proxy is called inside map(...) > If it's still too slow, then either Python simply isn't for this task, or > you need to optimize your functions. > > If this isn't the real bottleneck: > - Perhaps the functions I'm memoizing need optimization themselves? But, to a pretty good approximation, they _never_ get called (the value is (almost) always looked up). How would optimizing a function that doesn't get called, help ? > - Are there any modules out there which implement these in C > already? Other than the competing C++ implementation, no. > - How does the competing C++ code do it? Does it get its speed from some > wicked data structure for the memoizing, or are the individual functions > faster, or what? I have about 10 functions, written in Python, which the profiler highlights as taking up most of the time, between them (of which "proxy" is the main culprit). The C++ version doesn't have _any_ Python in its inner loops. I think it's as simple as that. (Admittedly, a group of 4 of my functions was initially written with development ease in mind, and should be replaced by a single mean and lean C(++) function. That's probably where the real bottleneck is.) > If this *is* the only significant bottleneck, No, it's not the _only_ bottleneck. Yes, I am pursuing other paths too. But I feel more confident that I know what I am doing in the other cases, so I won't bother the list with those. If you remember, my original question was about what I could expect in terms of speedup when recoding a Python function in C, which will make many calls to the Python C API. It's not that I'm determined to fix my whole speed problem just in this one area, but I would like to understand a bit more about what to expect when going to C. > but you want to try harder to speed it up, you can pursue the C > closure path you were mentioning. Yes, I think that this could be edifying. It's also likely to be a huge pain, so I'm not that determined to pursue it, as I do have more productive things to be getting on with. > However, comparing your Python to a C++ version on the basis of speed is > most certainly the wrong way to go. If the C++ is well designed with good > algorithms, its going to be faster than Python. Period. Not if my inner loops are C. (BTW, I don't believe that the C++ version is all that wonderfully designed, but enough about that :-) > But if you need maximum speed at all costs, the best Python can do > for you is act as a glue language to bits and pieces of hand-crafted > C. I think that it's the other way around, in this case. I build up a whole structure in Python ... and just need C(++) to call a very small subset of the functionality I provide, very efficiently. > Do you really *need* the speed, or are you just bothered that it's not as > fast as the C++ version? Politically speaking, yes, I need the speed. If a silly benchmark (one which completely misrepresents reality, BTW), shows that the Python version is slower than the C++ one, then the Python one is terminated. However, as you point out: > The advantage of Python is that it's much faster and easier to > *write* (and less likely to introduce bugs), easier to *read* and > maintain, and can model your problem more intuitively and flexibly. ... and for these reasons I am very keen to ensure that the Python version survives ... which, ironically enough, means that it must be fast, even though I personally don't care that much about the speed. From martin at v.loewis.de Thu Dec 4 15:40:21 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Dec 2003 21:40:21 +0100 Subject: weakrefs References: Message-ID: William Trenker writes: > Can anyone point me to tutorials or examples that illustrate where > and why one would use a proxy instead of a ref? It's very easy: If you want the weakref to be used transparently in place of the original object, you use a proxy - it tries to emulate, by delegation, all attributes to the underlying objects. If you can accept an explicit dereference operation throughout, you use a ref. Regards, Martin From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Dec 30 05:01:52 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Dec 2003 11:01:52 +0100 Subject: Programming language from python In-Reply-To: References: Message-ID: <3ff14d10$0$317$e4fe514c@news.xs4all.nl> Alejandro Lombardo wrote: > Dear sirs: > > I need to create a programming language. Can this be done with the > latest version of python? Yes, sure! > Is python the best computer programming > language development tool in the entire universe? If it isn?t could you > please tell me the name of the best computer programming language > development tool in the entire universe? While Python approaches this almost, I believe the Sqiwrnsyivstblz++ toolkit, available on the third rock circling Betelgeuse, is highly superior at the moment. > So that I can download it from > the Internet for free? I would apreciate it if you could answer these > questions as soon as posible. I'm sorry, the inhabitants of the Betelgeuse system have discarded the Internet long ago in favor of a much better communication system based on tachyons, and bad news (because, as you know, there are only two things in the universe that travel faster than light: tachyons and bad news). Have fun with Python instead. ;-) --Irmen de Jong From aahz at pythoncraft.com Tue Dec 2 21:19:35 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2003 21:19:35 -0500 Subject: Using and Implementing iterators with classes such as linked lists References: Message-ID: In article , Duncan Booth wrote: > >def __iter__(self): > def iterate(current): > while current.next is not None: > next = current.next > yield current > current = next > return iterate(self) Huh? Why the extra function and complexity? def __iter__(self): current = self while current is not None: yield current current = current.next -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From paul at fxtech.com Mon Dec 15 17:59:32 2003 From: paul at fxtech.com (Paul Miller) Date: Mon, 15 Dec 2003 16:59:32 -0600 Subject: PyThreadState_Swap difference in 2.3.2? References: Message-ID: >The same thing stumped me too a couple of days ago (s. >http://groups.google.nl/groups?q=PyNew_Interpreter&hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=braiu1%243r3%241%40news4.tilbu1.nb.home.nl&rnum=1 ) >with 2.3.3c1 (same applies 2.4a0 for that matter). Interesting. Unfortunately, there isn't a whole lot of information out there on what we're trying to do. I went ahead and commented out that check, but then I came across another problem. In object.c, it hit an assertion: assert(mro != NULL); This was for a custom Python type I had created in C. It was assuming this mro field was initialized, which it wasn't. It must be something new, because this all used to work in 2.2 I will have to keep looking at the release notes. I wish there was a "upgrading from 2.2 to 2.3" document for people who are writing custom Python extensions, and doing embedding and such. From jacek.generowicz at cern.ch Mon Dec 8 09:45:42 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 08 Dec 2003 15:45:42 +0100 Subject: Speed: bytecode vz C API calls References: Message-ID: Jacek Generowicz writes: > I was expecting C-extensions which make lots of calls to Python C API > functions, not to be spectacularly fast, but I'm still a little > disapponited with what I've got. Does this sort of speedup (or rather, > lack of it) seem right, to those of you experienced with this sort of > thing? or does it look like I'm doing it wrong? > static int > memoize_init(memoizeObject* self, PyObject* args, PyObject* kwds) { > PyArg_ParseTuple(args, "O", &(self->fn)); Obvious bug: &(self->cache) !! > Py_INCREF(self->fn); > self->cache = PyDict_New(); > return 0; > } Fixing the bug gives me a factor of 3 speedup over the class-based version. That's a bit more like what I was expecting. From jdhunter at ace.bsd.uchicago.edu Mon Dec 1 10:03:45 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 01 Dec 2003 09:03:45 -0600 Subject: Changing the contents of a displaying gtk window thorough the command line In-Reply-To: <3FCB0711.9020600@yahoo.com> (suresh j's message of "Mon, 01 Dec 2003 14:47:05 +0530") References: <3FCB0711.9020600@yahoo.com> Message-ID: >>>>> "suresh" == suresh j writes: suresh> Hi, I am using gtk module. With that after creating the suresh> window, I call the "gtk main loop()" function, after which suresh> the window is displayed. I want to change the contents of suresh> this window while it is being displayed, througth the suresh> python interpreter . Is there a way to do that. Attached below is Py_Shell (by Pier Carteri based upon code by Jon Anderson) , which enables interactive control of GTK windows. -------------- next part -------------- A non-text attachment was scrubbed... Name: Py_Shell.py Type: application/octet-stream Size: 22114 bytes Desc: not available URL: -------------- next part -------------- There is another interactive shell which uses threading in the Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109 John Hunter From pedrosch at gazeta.pl Sun Dec 14 06:33:31 2003 From: pedrosch at gazeta.pl (Przemo Drochomirecki) Date: Sun, 14 Dec 2003 03:33:31 -0800 Subject: connection to samba server References: <3fdbc954$0$218$e4fe514c@news.xs4all.nl> Message-ID: very funny, ok, so now it sounds like this: (damn smart way) I used Google to try to find "connecting to samba server"" on the Web, but I got no useful hits. Does anyone know where I can find programming information on this problem? - Przemo From just at xs4all.nl Sat Dec 20 04:50:46 2003 From: just at xs4all.nl (Just) Date: Sat, 20 Dec 2003 10:50:46 +0100 Subject: PNG to EPS with Python? References: Message-ID: In article , hwlgw at hotmail.com (Will Stuyvesant) wrote: > I have .PNG image I would like to convert to .EPS (Enhanced > PostScript), "Encapsulated PostScript", actually. > for inclusing in LaTeX documents. I feel that a portable > tool for this would be very welcome in the scientific community, where > they still LaTeX a lot! There is a png2eps tool for linux/unix, but I > can't find something that works on Windows. Perhaps somebody with > Cygwin can produce an .exe (I don't use Cygwin anymore myself)? I > wonder if this would be possible to do with Python, or maybe somebody > already did this? Instead of PNG also JPG, GIF, TIFF, etc. would be > welcome, as it is easy to convert PNG back and forth to those, even on > Windows :-) Have you looked at PIL yet? Just From noemail at noemail4u.com Thu Dec 11 07:16:03 2003 From: noemail at noemail4u.com (Dang Griffith) Date: Thu, 11 Dec 2003 12:16:03 GMT Subject: Python progamming certification References: <87fzfuszsq.fsf@pobox.com> <3FD7C8ED.3000501@_._> <7x3cbsw1kj.fsf@ruckus.brouhaha.com> Message-ID: On 10 Dec 2003 18:06:04 -0800, Paul Rubin wrote: >Apollo <_ at _._> writes: >> But how can I convince employers that I know Python I have not >> programmed using Python in career before? > >Why that's the simplest of all. Write an interesting program and >release it as free software. And/or contribute to an already-existing project that needs assistance. That would have the added benefit of supporting any claims you may make regarding teamwork. And, if the team is distributed, you could simultaneously gain support for any claims you may make regarding the ability to work independently. Hmmm... now I'm starting to feel like such a louse. Guess I'll have to start contributing more than occasional newbian answers and weak, pithy witicisms. --dang From bhoel at web.de Sun Dec 28 05:50:44 2003 From: bhoel at web.de (Berthold Hoellmann) Date: Sun, 28 Dec 2003 11:50:44 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: bhoel at web.de (Berthold Hoellmann) writes: > Hello, > > When I use > > ./configure --with-thread --with-fpectl --with-signal-module \ > --with-pymalloc --enable-shared --with-cxx=g++ > > make test > > on 2.3.3 I get > > ... > test_queue > test_quopri > test_random > test_re > make: *** [test] Speicherzugriffsfehler (Speicherauszug erstellt) Everything works fine if I remove the "--enable-shared" flag from configure. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From http Sat Dec 13 16:12:09 2003 From: http (Paul Rubin) Date: 13 Dec 2003 13:12:09 -0800 Subject: "Do this, and come back when you're done" References: <1071338254.885587@yasure> Message-ID: <7xsmjojuc6.fsf@ruckus.brouhaha.com> "Donn Cave" writes: > Yes. I may be missing something here, because the followups > I have seen strike me as somewhat misguided, if they're not > just fooling with you. You already have two independent threads > or processes here, one on each machine. All you need to do is > take the results from the remote machine AFTER the local computation. > Move the line that says "remoteMD5hash = Socket.recv(256)" to > after the block that ends with "localMD5hash = hasher.hexdigest()". > No? Can the remote process time out if the local side takes too long to read from the socket? That could happen if the two machines aren't the same speed. From max at alcyone.com Wed Dec 3 06:34:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 03 Dec 2003 03:34:20 -0800 Subject: redirecting Stdin References: <3FCDB2C3.B87DE2BE@alcyone.com> Message-ID: <3FCDCA3C.48765245@alcyone.com> Jon Arter wrote: > after redirection sys.stdin = file('newinput') This isn't after redirection, it causes it. > line=sys.stdin:readline() > exec line This contains at least two errors: You meant a period instead of a colon, and the exec statement makes no sense. > This results in a parsing error when the file reading reaches the > def detectip(): > sentence . > You can execute the command line as long as it is a single line > command > > How to Get arround this ? Since you're not showing precisely the code that's executing and precisely the error you're getting, I can't even understand what you're talking about. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ \__/ Do not stand in a place of danger trusting in miracles. -- (an Arab proverb) From tomas.bouda at systinet.com Wed Dec 3 07:32:03 2003 From: tomas.bouda at systinet.com (tomas.bouda at systinet.com) Date: Wed, 03 Dec 2003 13:32:03 +0100 Subject: Python mem leaks? Message-ID: <20031203123203.6188.qmail@mailcz.in.systinet.com> Hi, I'm facing a problem which seems to be a Python bug... I've got an application written in C and having Python embedded inside. The situation is the following: 1) C object is wrapped by PyCObject and put into Python function 2) The PyCObject has given a finalizer which frees the C object inside 3) The Python function "do_smth(panel)" is called from C Having the two methods: def do_smth1(panel): pass def do_smth2(panel): raise Exception() Calling do_smth1() will cause returning of Py_None, the PyCObject is freed and the C finalizer (mentioned in no.2) is called. Calling do_smth2() will case returning NULL a is not freed nor finalizer is called. At this point I get a leak! Is it my fault? I didn't find anywhere in Python doc what should C app to do if such memory isn't freed. Seems more likely to be the Python leaking bug! Any comments or proposals? Thanks a lot, Tobbi From gagenellina at softlab.com.ar Fri Dec 26 21:49:55 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Fri, 26 Dec 2003 23:49:55 -0300 Subject: sys.path[0] in IDLE In-Reply-To: Message-ID: <5.2.1.1.0.20031226232737.01e8c0b0@192.168.0.115> At 26/12/2003 22:25, you wrote: >Am I reading this correctly? > >http://python.org/doc/current/lib/module-sys.html > >""" >As initialized upon program startup, the first item of this list, >path[0], is the directory containing the script that was used to >invoke the Python interpreter. >""" > > >So, sys.path[0] should be the directory that my script is in? > >Even if running the script from IDLE? > >Has anyone else had problems with this? Especially on windows? (Read the remaining of the paragraph too) When using IDLE, the "script" is really idle.py. If you start IDLE with another script as an argument, its dir is prepended in sys.path Gabriel Genellina Softlab SRL From theller at python.net Thu Dec 11 04:07:50 2003 From: theller at python.net (Thomas Heller) Date: Thu, 11 Dec 2003 10:07:50 +0100 Subject: Looking for ELF/PE library for Python References: <20031211082652.14128.qmail@web21205.mail.yahoo.com> Message-ID: <8ylj90yh.fsf@python.net> Bogdan Marinescu writes: > Hello, > > Is there a Python library for working with ELF > and/or PE(Portable Executable) formats? By "working" I > mean handling file structure, dumping structure > information, extracting specific parts of the file and > even creating "by hand" new sections/relocations. I > already searched some locations for such a library, > but I couldn't find anything suitable. > Thank you for your time. I once started such a thing for PE, and posted it to the ctypes-users mailing list. http://article.gmane.org/gmane.comp.python.ctypes/432 Thomas From aahz at pythoncraft.com Wed Dec 10 10:33:47 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Dec 2003 10:33:47 -0500 Subject: Function unrolling (was Re: Speed: bytecode vz C API calls) References: Message-ID: [Too busy to snip, sorry] In article , Jacek Generowicz wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> Jacek Generowicz wrote: >>>aahz at pythoncraft.com (Aahz) writes: >>>> >>>> I think you're going to need to write a solution that doesn't call >>>> functions (function unrolling, so to speak). Instead of returning a >>>> memoizer function, just use a dict of dicts. > ^^^^^^^^ > >(Maybe this is where we are misunderstanding eachother. On first >reading, I thought that "memoizer" was just a typo. I don't return a >memoizer function, I return a memoized function.) > >>>Sounds interesting. But how do I get the dictionary to use the >>>function which it is memoizing, to calculate values which haven't been >>>cached yet? >> >> Same way you decide which function to call currently. > >The way I decide which function to call currently is to type its name >directly into the source at the call site. Deciding which function to >call is not the problem: calling any function at all, once I've >reduced myself to having _just_ a dictionary, is the problem. > >Maybe I didn't make the use of "memoize" clear enough. > >You use it thus: > > def foo(): > ... > > foo = memoize(foo) > >And from now on foo is a lot faster than it was before[*]. That's why I changed the Subject: to "Function unrolling"; you're going to need to change your code to avoid function calls in inner loops. One technique you might try is to create a generalized inner loop function: def innerloop(iterable, func, cache): l = [] for args in iterable: try: l.append(cache[args]) except KeyError: l.append(cache.setdefault(args, func(args)) return l Yes, it's a performance hack, but I bet it's a lot clearer than C++ code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From gh at ghaering.de Wed Dec 17 11:15:39 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 17 Dec 2003 17:15:39 +0100 Subject: Standalone client database for Python? In-Reply-To: References: Message-ID: <3FE0812B.9040007@ghaering.de> Gustavo Campanelli wrote: > What are our options for a standalone (that is one that's not > client/server) easily accesible from Python? [...] If you need a "real" query language (read: SQL), then I can recommend PySQLite (http://pysqlite.sourceforge.net/). -- Gerhard From francisgavila at yahoo.com Sun Dec 21 00:29:46 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Sun, 21 Dec 2003 00:29:46 -0500 Subject: Unicode from Web to MySQL References: <3FE47726.90504@rfa.org> <3FE4796D.1010609@rfa.org><16356.44377.466955.783810@montanaro.dyndns.org> Message-ID: Francis Avila wrote in message ... > Rereading that message of mine, I think I sounded far more heavy-handed and condescending than I intended, so I want to apologise ahead of time. The distinctions between unicode, unicode encodings, and the byte streams that embody them can be subtle and elusive, and the terminology doesn't help matters. However, once you "get" it, it's hard to understand why everyone else is so muddled about it. ;) -- Francis Avila From Padraig at Linux.ie Thu Dec 18 15:11:17 2003 From: Padraig at Linux.ie (Padraig at Linux.ie) Date: Thu, 18 Dec 2003 20:11:17 +0000 Subject: cleanup after exceptions In-Reply-To: References: <0%mEb.1392$HR.4074@news.indigo.ie> Message-ID: Jp Calderone wrote: > On Thu, Dec 18, 2003 at 07:11:12PM +0000, Padraig at Linux.ie wrote: > >>Hi, >> >>I'm a little confused why objects >>are not deleted after they go >>out of scope due to an exception? > > > Because objects don't go out of scope. Only variables do. Objects remain > "alive" as long as there are any references to them. > > >>For e.g. >> >> >>>>>import time >>>>> >>>>>def f(): >>>>> myfile=open("file.test","w") >>>>> myfile.write("not flushed\n") >>>>> exception=throw >>>>> >>>>>f() >>>>>time.sleep(10) >> >> >>The file is not written/closed until >>the python interpreter exits. >>The same thing applies to other objects. > > > In this case, the traceback still holds a reference to the frame from > which the exception was raised OK I can see that, but why doesn't a pass on the exception release it? This is demonstrated with: #!/usr/bin/env python import time class c: def __del__(self): print "del" def f(): C=c() exception=throw try: f() except: pass time.sleep(3) > which itself holds a reference to all the > locales from that function. don't know what you mean by this > > Calling sys.exc_clear() This isn't in version 2.2.2 at least > (possibly followed by gc.collect()) should force > the cleanup you expect. thanks, P?draig. From http Thu Dec 18 09:39:07 2003 From: http (Paul Rubin) Date: 18 Dec 2003 06:39:07 -0800 Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> Message-ID: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Carl Banks writes: > Consider something like this: > > def func(param=((1,2),(3,4),(5,6),(7,8))): > whatever > > Do you really want to be building a big-ass nested tuple every time > the function is called? Come on, the compiler can easily recognize that that list is constant. > Python evaluates default args at time of definition mostly for > performance reasons (and maybe so we could simulate closures before we > had real closures). My gut feeling is, moving the evaluation to call > time would be too much of a performance hit to justify it. Python takes so many other performance hits for the sake of convenience and/or clarity that this particular one would be miniscule by comparison. From pinard at iro.umontreal.ca Wed Dec 31 08:17:50 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 31 Dec 2003 08:17:50 -0500 Subject: RELEASED: allout-vim 031229 In-Reply-To: References: Message-ID: <20031231131750.GA2466@titan.progiciels-bpi.ca> [Samuel Walters] > [Fran?ois Pinard] > > http://fp-etc.progiciels-bpi.ca/archives/allout-vim-031229.tgz > > The Allout file format is (yet another) legible representation of the > > synoptic structure of a textual document. Emacs support for Allout files > > is already standard, as an application of fold editing. This tool eases > > the handling of Allout files from within a Python-enabled Vim. > Is there an descriptive web page for this tarball? Hello, Sam. I'm not sure I understand your question. Do you mean some on-line documentation for allout-vim? Then see: http://fp-etc.progiciels-bpi.ca/showfile.html?name=allout/vim/doc.txt http://fp-etc.progiciels-bpi.ca/showfile.html?name=allout/vim/README The first shows user documentation, the second contains installation instructions. These point to a mirror of my work files, while those in the (tiny) distribution are a bit older. As for a description of the distribution, I thought the little blurb above ("The Allout file format is ...") was sufficient. Is it not? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From http Thu Dec 11 09:41:23 2003 From: http (Paul Rubin) Date: 11 Dec 2003 06:41:23 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xekvb1koc.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > Paul, I certainly can understand your dismissal of Tkinter > as it's commonly employed. Are you aware, though, of http://tcl.projectforum.com/tk/Home > and http://mini.net/tcl/10424 >? Tkinter might, in fact, best > meet your requirements. No I'm not. I wrote one tkinter application just to try it out and while it was nice for putting up a quick and dirty gui, it looked very crude and the API was also quite inflexible. I clicked the first of those two url's and it seems to be an in-progress discussion about how to rework tcl to fix its limitations, but I don't want to rely on something that's not yet already working. Thanks though. From lkcl at lkcl.net Wed Dec 17 14:06:52 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Wed, 17 Dec 2003 19:06:52 +0000 Subject: [Python-Dev] Re: rexec.py unuseable In-Reply-To: <1071669397.3fe06095c9f3c@mcherm.com> References: <1071669397.3fe06095c9f3c@mcherm.com> Message-ID: <20031217190652.GE2117@lkcl.net> On Wed, Dec 17, 2003 at 05:56:37AM -0800, Michael Chermside wrote: > Luke: > > Seeing as you've now had time enough to read what I'd written, yes i have now, except not yet the link you recommended to 'E', which i will get to, soon. > I was going to > respond to some of the points that you made, but then I read Nick Coghlan's > posting[1], and I really don't have anything else to add. > > [1] http://mail.python.org/pipermail/python-dev/2003-December/041105.html am absorbing that: it looks like a good definition of acls and capabilities to me! > Well, that's not quite true... I guess I _do_ have something small to add. > In designing a security policy for file systems, there are very few things > that you can do with the protected items. Separate "read", "write", and > "execute" permissions seem appropriate. yes. it's worth pointing out that NT file systems have a lot more than just rwx (which are covered by "generic read" permission, "generic write" and "generic execute"). if i remember correctly, NT file system access permissions also include separate permissions for directory access and creation that are deliberately distinct from file creation (and maybe even file access, too, but it's been a while so i can't be sure). they also have "change security descriptor" as a permission. ... *click*. darn, it. darn it quite a lot. it's been such a long time that i've been confusing "security descriptor" with "access control list". although... thinking about it some more i don't think it makes much difference... definition of an NT (vax/vms) security descriptor: a security descriptor is a set of "access control lists". there are four ACLs, and they are for different purposes. i can nail down two of them for you: one is a "System" ACL which restricts what the OPERATING SYSTEM can do. another is a "Users" ACL which restricts what _users_ can do (and groups, which also under NT have their own identity just like a user has its own identity.) there is also some additional information on a per-acl basis and it controls the way in which the ACL is used. ... but all that is by-the-by because, i believe, only _one_ ACL is needed for the purposes at hand. anyway, sorry to interrupt the flow, there. :) > Furthermore, there tends to be a > clear idea of a "user", and in many situations we want all access to items > (files) to depend only on who that "user" is (sandboxing an email program > is an exception... are you listening MS?). Finally, we often want to > provide centralized administration of access rights to file systems. > ACLs are a good match for these design specs. fully designed, properly designed ACLs are, imo, way over the top for file systems, which is why POSIX ACLs are just an extension of the standard POSIX filesystem rwx/ugo. for NT (and VAX/VMS), the design of the security system came first, as a "generic thing", which was then applied to file systems as _one_ component, albeit a critical one, of the NT and VMS operating systems. the NT/VMS security model has room for 32-bits of "permissions" on an ACE (access control entry). 16-bit of those are "generic", and 16-bit of them are "application specific". the file-system-specific permissions were created by the writers of the NTFS - nt file system - and they gave them life and meaning, so to speak, but only in the context of an NTFS and access to it. > However, controlling what arbitrary programs may do is a very different > beast. in the context of something like "POSIX ACLs" or in the context of something like "POSIX file permissions", yes, absolutely, i agree with you entirely. in the context of something as flexible as NT/VMS security descriptors, no, i don't agree, because NT SDs are very generic and had to be "specialised" to fit onto the NTFS. which implies that something as flexible as NT/VMS SDs could equally and as easily be adapted to fit controlling what arbitrary programs do. _and_, in the NT operating system and its core [mostly user-space] components, this _has_ already been done [and i presume likewise in VMS]. for example, there is a spoolss (printer service) and there is a SAM (security accounts manager) database service. the authors / designers of these two services created their own set of 16-bit application-specific permissions, gave them life and meaning in the context of their individual services, and made sure that each function _in_ that service double-checked the permissions against the type of operation that that function performed. to give you an example, this is some pseudo-code of the SamrCreateUser function: static SEC_DES[] sec_des_array = { ... ... samr_create_user_security_descriptor, ... }; STATUS32 SamrCreateUser(pHND *context, UNICODE_STRING *username) { USER_TOK *user = GetUserToken(context); if (!check_security_descriptor(user, context, SECDES_SAM_CREATE_USER)) { return NT_STATUS_ACCESS_DENIED; } .... .... } the context handle stores references to quite a bit of state information about the connection (it's a DCE/RPC thing). the SECDES_SAM_CREATE_USER permission is an application-specific bit that is specifically and only used to check access permission to the SamrCreateUser function. > First of all, the kinds of restrictions that we want are HIGHLY > variable. Sometimes we want to prohibit all file access. Sometimes we > want to allow read-only access to a certain file only. Sometimes we > want access only to a certain directory. Sometimes we don't care at > all about file system access, we're concerned instead with providing > an object which can be queried but only in certain ways -- and the > specifics of what is permitted and what isn't are completely dependent > on the particular application. > > On top of that, there's rarely a clear concept of "users" that controls > what actions we want to permit. Instead, we usually want to allow or > deny certain capabilities to particular _sections of code_. (Sometimes > that will be a module, sometimes a plug-in, sometimes a child program.) yes. and i believe that the > All of these things suggest that maintaining a list of who [or rather "what" - i.e. "Entities", yes?] > is permitted > to access what is simply not the best model for providing security in > a programming language. i am curious: how does that logically follow? in my experience (windows nt services and therefore also samba-tng's services), access control lists have been an extremely successful means to provide security in almost every single program in the NT operating system (i don't mean XP i don't mean windows 95) for almost 15 to 20 years. it seems quite logical therefore to propose that such a successful security model be adapted to fit a programming language, or at least to learn from its success (and failings). change of subject ----------------- i believe that it _is_ possible to express what nick coghlan defines capabilities to be _into_ an ACL. how? by creating a security permission called "can you see it and execute it?" let's call it SEE_AND_EXECUTE then, the language (interpreter) does this (following the example of the SamrCreateUser function, above): MakeFunctionCall(Context *stack, CodeObject *code) { char *callee_fn_name = GetCalleeName(stack); SEC_DES *sd = GetSecurityDescriptorForCode(code); /* check the capability to even _see_ this function! */ if (!check_sec_des(sd, callee_fn_name, SEE_AND_EXECUTE)) { return Exception("Function name %s does not exist", code->function_name); } /* okay, they can see it [and execute it] */ .... .... } does that make sense at all? l. From jorgencederberg at hotmail.com Fri Dec 19 03:43:12 2003 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Fri, 19 Dec 2003 09:43:12 +0100 Subject: Hiding console with program compiled in PY2EXE In-Reply-To: <3fe2b5cc$0$65900$e4fe514c@dreader9.news.xs4all.nl> References: <4378fa6f.0312182234.42c4fe73@posting.google.com> <3fe2b5cc$0$65900$e4fe514c@dreader9.news.xs4all.nl> Message-ID: duikboot wrote: > # setup.py > from distutils.core import setup > import py2exe > > setup(name="convertdpi", > scripts=["convertdpi.pyw"], > ) > > > From the dos command prompt: > c:\python23> python.exe setup.py py2exe Hi or instead # setup.py from distutils.core import setup import py2exe setup(name="convertdpi", scripts=["convertdpi.py"], ) c:\python23> python.exe setup.py py2exe -w Which works for me :) All options are described on http://starship.python.net/crew/theller/py2exe/ Regards Jorgen > > This works for me. > > Hope it helps, > > Arjen > "Marc" schreef in bericht > news:4378fa6f.0312182234.42c4fe73 at posting.google.com... > >>Hi all, >> >>I know that to hide a console normally you simply change the extension >>from .py to .pyw. That's simple enough. However I can't seem to >>accomplish the same thing after freezing the program. I've tried >>building the setup file with the python script as a .pyw file, but it >>crashes and doesn't give me a reason. This is of course because the >>debug window doesn't open, so you don't know what happened (ahh, the >>irony). >> >>Does anyone know how to successfully freeze a program with py2exe? >> >>Many thanks, >>Marc > > > From quiteblack at yahoo.com Wed Dec 24 21:56:47 2003 From: quiteblack at yahoo.com (black) Date: Wed, 24 Dec 2003 18:56:47 -0800 (PST) Subject: shortcut event binding~ Message-ID: <20031225025647.89612.qmail@web21326.mail.yahoo.com> Hi all~ I've already binded events for single key pressing but dunno how to bind events for multiple keys, say shorcut ? any example will be welcome. Regards~ --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Fri Dec 5 12:56:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 05 Dec 2003 12:56:27 -0500 Subject: When is bare except: justified? References: <873cbzmbld.fsf@pobox.com> Message-ID: <3FD0C6CB.C446C69B@engcorp.com> "John J. Lee" wrote: > > Bare "except:", with no exception specified, is nasty because it can > easily hide bugs. [snip remainder of excellent comments] I believe the only case where we permit "bare" except statements is when there's a clear intention that we want higher level code to be immune to problems in the lower level code, primarily because the higher level code makes up part of a long-running process. In a nutshell, if we have one of our multi-threaded embedded applications, it's more important that the program as a whole keep running than it is to expose potentially minor problems by crashing the entire system with a nasty traceback message exposed to the user. Since most of the lower level code has decent unit tests, and we have acceptance tests covering the combination of it plus higher level code, we tend to accept that the basic functionality of the system is already guaranteed, and therefore any unhandled exceptions would represent things which it's not worth shutting down over. We do log them in a log file, but we then ignore the error and continue running, or restart the thread, as appropriate. In all other cases, it's an unwritten rule that bare except is a sign of poorly written code. (I may have overlooked a special case or two where we would make an exception, no pun intended... not sure.) -Peter From brian at sweetapp.com Wed Dec 17 18:25:03 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 17 Dec 2003 15:25:03 -0800 Subject: Save the pythons. In-Reply-To: Message-ID: <050601c3c4f5$00070ec0$0000fea9@dell8200> > Python power is in it's syntax, not addons. Let's not copy perl's > experience and one java is already far too much for earth. Your opinion and Guido's differ on this point, see: http://www.python.org/peps/pep-0206.html Here is a relevant quote: "The Python source distribution always maintained the philosophy of "batteries included" -- having a rich and versatile standard library which is immediately available, without making the user download separate packages. This gives the Python language a head start in many projects." Cheers, Brian From steve at ferg.org Sun Dec 7 11:13:19 2003 From: steve at ferg.org (Stephen Ferg) Date: 7 Dec 2003 08:13:19 -0800 Subject: ANN: advocacy article: Why your organization needs Python Message-ID: I have posted an article called "Python: Programming the Way Guido Indented It" at http://www.ferg.org/papers/ferg--why_we_want_python.html This is a lightly edited version of an article that I wrote for my office's technical newsletter. It covers what Python is and why your office needs it (complete with code sample and pictures) in only two pages. (!) It might be useful for your own office if your office has a technical newsletter. Or it might be useful if you need to make the case for Python to a busy manager who doesn't have time to read more than two pages. Feel free to copy and modify it as you see fit to meet your own needs. I hereby place it in the public domain. Please: no e-mail about how something in the article isn't EXACTLY right, or easygui isn't part of the Python standard library, or disagreeing with the assessment of Perl, or failing to boldly assert that Python is much more than a scripting language, and so on. This is an admitted piece of Python advocacy aimed at a non-technical to semi-technical audience that has never heard of Python and possibly never even heard of Perl. For that purpose, I'm pretty happy with it. I hope you'll find it useful. -- Steve Ferg (steve at ferg.org) From bokr at oz.net Thu Dec 18 21:48:42 2003 From: bokr at oz.net (Bengt Richter) Date: 19 Dec 2003 02:48:42 GMT Subject: re troubles References: Message-ID: On Thu, 18 Dec 2003 17:22:54 -0600, Evanda Remington wrote: >I'm trying to filter some rows of an html table out, based on their >contents. For input like: >""" > > > > << want to filter > << this out. > << > >
    Lasers17
    kittens8
    robots8
    >""" >I would like to completely remove the (3 line) table row that makes mention >of kittens. The regexp I have tried to use is: r".*?kittens.*?". >When compiled and used with subs("",data), strangely removes everything >from the first "" to the first "" after kittens. > >That is, the ".*?" notation works in the second half, but not in the first >half. It behaves the same as ".*" should. > >Any advice? > See if this will work for you. I added some more kittens and robots. Otherwise a single instance could be done differently. I used 'XXX' rather than '' for example clarity. ====< evanda.py >==================== import re s = """\ << want to filter << this out. << << want to filter << this out. <<
    Lasers17
    kittens8
    robots8
    more kittens8
    more robots8
    """ rxo = re.compile(r"(?ms)(?:[^<]|<[^t]|])*?kittens.*?") print '==== before ====\n%s==== after sub XXX ====\n%s====' % (s, rxo.sub('XXX', s)) ===================================== Result: [19:02] C:\pywk\clp>evanda.py ==== before ==== << want to filter << this out. << << want to filter << this out. <<
    Lasers17
    kittens8
    robots8
    more kittens8
    more robots8
    ==== after sub XXX ==== XXX << XXX <<
    Lasers17
    robots8
    more robots8
    ==== Regards, Bengt Richter From lkcl at lkcl.net Mon Dec 15 14:10:23 2003 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Mon, 15 Dec 2003 19:10:23 +0000 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <16349.63203.797449.677617@montanaro.dyndns.org> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> Message-ID: <20031215191023.GB26055@lkcl.net> On Mon, Dec 15, 2003 at 12:01:07PM -0600, Skip Montanaro wrote: > > Luke> well, uhm, if [rexec]'s broken, why hasn't it been reverted to the > Luke> 2.0 code? > > My understanding was that in 2.0 it was also broken, but that (relatively) > recent changes to Python made the breakage easier to exploit. the issue is [back-tracking to the 2.0 code], were those "breakages" actually features, or were they definitely "breakages"? i.e. was it 1) was it just unexpected behaviour in that a function _called_ by a rexec'd restricted routine could do, for example writes; was it that an unrestricted function, module or variable imported by a rexec'd restricted routine or module could be accessed. e.g. like this: contents of bypassmodule.py: import open as unrestrictedopen then code run under rexec: from bypassmodule import unrestrictedopen both of these things i would consider to be totally acceptable behaviour of the [2.] rexec.py module!!! i would NOT consider them to be a bug, and in fact are desirable behaviour in order to get my code working. i believe that there exists in [2.0] rexec a mechanism to specify what functions are allowed in a particular module, so i could restrict access to the bypassmodule.unrestrictedopen function, if necessary. OR was it 2) a genuine bug. > As for alternatives, I suggest you post a query on comp.lang.python (aka > python-list at python.org). ta! > Skip -- -- expecting email to be received and understood is a bit like picking up the telephone and immediately dialing without checking for a dial-tone; speaking immediately without listening for either an answer or ring-tone; hanging up immediately and then expecting someone to call you (and to be able to call you). -- every day, people send out email expecting it to be received without being tampered with, read by other people, delayed or simply - without prejudice but lots of incompetence - destroyed. -- please therefore treat email more like you would a CB radio to communicate across the world (via relaying stations): ask and expect people to confirm receipt; send nothing that you don't mind everyone in the world knowing about... From ramen at lackingtalent.com Wed Dec 24 03:33:18 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 24 Dec 2003 08:33:18 -0000 Subject: dynamic typing questions References: Message-ID: In article , John Roth wrote: > > The dogma is that if you're writing more than a dozen lines (and five > or six is average) for a failing test, then you're moving in steps that > are way too big. When I take bigger steps, I find I pay for it. > The time spent debugging is definitely super-linear in the number of > lines written between runs of the test suite. It's more enjoyable all around to keep the tests and implentations small. I've just barely attempted to pull off the TDD thing, but I was impressed at the simple tests and short functions that came out of it. Everything felt very orthogonal, and the code was easier to incorporate into a larger program later on. I'm not totally sold on it yet (probably because I'm lazy) but i'm impressed so far. Part of why I think this happened is that simple tests trigger my laziness; I don't want to have to write a lot of code just to do a little thing, and that raises my standard for the straigtforwardness and ease-of-use I expect in an interface. I become more user-centric. I also think that the "refactor mercilessly" approach pushes a design toward simpler, smaller, and more reusable units of code. BTW, I had a hunch, and just as I expected, you're the guy that tipped me off about TDD back in April. Thanks for that. =) http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&frame=right&rnum=1&thl=0,1086251285,1086234179,1086227258,1086200927,1086219110,1086188445,1086131532,1086085644,1085963652,1086206531,1086172007&seekm=slrnb9orhr.toh.ramen%40lackingtalent.com#link2 Peace, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From gh at ghaering.de Thu Dec 4 02:50:14 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Dec 2003 08:50:14 +0100 Subject: How to share 3rd-party modules between 2.2 and 2.3? In-Reply-To: <3FCE767B.7010603@v.loewis.de> References: <3FCE767B.7010603@v.loewis.de> Message-ID: <3FCEE736.6080109@ghaering.de> Martin v. L?wis wrote: > Matthew Wilson wrote: > >> I want to write some CGI scripts that use pgdb. I want to write the >> python scripts using python2.3, but the pgdb.py file is in >> /usr/lib/python2.2/site-packages >> >> which is not part of sys.path in python2.3. What is the best way of >> sharing these modules? > > Put the code in /usr/lib/site-python. I suppose pgdb.py is from PyGreSQL, which includes a C extension module. Sharing extension modules between different Python minor versions *might* work, but it's best to just install the package in question for both Python 2.2 and 2.3. -- Gerhard From aahz at pythoncraft.com Fri Dec 19 16:49:20 2003 From: aahz at pythoncraft.com (Aahz) Date: 19 Dec 2003 16:49:20 -0500 Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: In article , Michael Hudson wrote: >Gerrit Holl writes: >> >> So the Zen of Python shouldn't *be called* the Zen of Programming. > >No, it should be called "19 Pythonic Theses", which has the advantage >of being vaguely accurate... Actually, it should be called "20 Pythonic Theses", because that was Tim's original title. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From nospam at nowhere.hu Mon Dec 15 22:41:51 2003 From: nospam at nowhere.hu (Miklós) Date: Tue, 16 Dec 2003 04:41:51 +0100 Subject: Leo 4.1 rc1 released References: Message-ID: Edward, I've just downloaded v4.1-rc1 (I was running 4.0) and there's that new vim plugin which talks to vim running as a server.. This will finely do for me now even though the options you suggested are also nice. I will put up with that Vim is not running in the editor pane proper but in a seperate shell window.. That would be possibly even cooler but now I'm really happy with this. :) My Vim shortcuts + my syntax highlights + my Vim macros + power editing capabilities in Vim + Leo outlines to get things organized and managable... Vow! I wish my other wishes were fulfilled in such a timely manner. ;) Leo (and Edward, its father) rulez!!! Thanks a lot! One more question: Where's the Leo file format documented? (say, with a DTD but a semantic description would be possibly better) Have I missed this somewhere? Truly* yours, Mikl?s * and I mean it PS: Hey, people out there, you can't imagine how neat and incredibly useful this outlining editor thing, called Leo, is if you don't try it yourself... Edward K. Ream wrote in message news:vtsjj7rtsc0nb3 at corp.supernews.com... > > While the edit pane is fine I do want my favorite Vim... Is this possible > > somehow? I mean to embed Vim in the window.. > > This is a reasonable thing to want to do. There are several possible > approaches: > > 1. Run Leo from Vim. This is now possible in Leo's batch mode. When > executed from the command line Leo uses a "null gui" so nothing gets put on > the screen. You can optionally turn off all of Leo's log output, which > would otherwise go to the console window. > > 2. Implement scintilla/scite using Leo's experimental wxPython plugin. Not > quite the same as Vim. > > 3. Use something like pymacs to communicate between Emacs and Leo. This is > in the daydream stage. Leo now has a Vim/Scite SIG and I welcome comments, > ideas and code there. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: Literate Editor with Outlines > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- > > From jjl at pobox.com Tue Dec 2 07:34:14 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Dec 2003 12:34:14 +0000 Subject: comparing nan "number" References: <87vfp01muq.fsf@pobox.com> Message-ID: <87znebe6ux.fsf@pobox.com> Alexander Schmolck writes: [...] > possibly be `False` and {x:"some value}[x] might well raise an exception if > `x` is a nan (or indeed one of infinitely many Numeric arrays with [...] Don't you mean SomeMapping((x, "some value"))[x]? A dict lookup doesn't use __eq__. John From evan at 4-am.com Mon Dec 1 14:54:59 2003 From: evan at 4-am.com (Evan Simpson) Date: Mon, 01 Dec 2003 13:54:59 -0600 Subject: Separation of content and code for web (was Re: Python for web ?) In-Reply-To: References: <3FCB8535.F8F89132@engcorp.com> Message-ID: Rene Pijlman wrote: >>Anyone know of a Python-based approach using the same core concept? > > ZPT: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/ZPT.stx Not really the same as what Peter is talking about, since we use embedded element attributes. I *do* plan an extension to ZPT, called TERSE, that will be to TAL as CSS stylesheets are to style attributes. This will allow you to take a pure-HTML/XML document and modify it with external rules such as: // Plug the template's Dublin Core title into the title element title { content: template/dc:title; } // Put data into a table tr#students { repeat: student in students; } tr#students td { search-replace: student delimited '#(' ')#'; } // Attach error text and markup to form fields form .field { // Get the field name from the name attribute fn = [name]; // Get the error text, if any. err = errors/var:fn | nothing; @if(err) { // Add 'error' to the class attribute. [class] += ' error'; // Insert the error message at the end of the field element content-after: structure "$err"; } } Syntax subject to change, probably a lot. Cheers, Evan @ 4-am From andymac at bullseye.apana.org.au Sun Dec 28 18:16:37 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 29 Dec 2003 10:16:37 +1100 (EST) Subject: make test segfaults with "--enable-shared" on Python 2.3.3 In-Reply-To: References: Message-ID: <20031229095810.X27277@bullseye.apana.org.au> On Sun, 28 Dec 2003, Berthold Hoellmann wrote: > > When I use > > > > ./configure --with-thread --with-fpectl --with-signal-module \ > > --with-pymalloc --enable-shared --with-cxx=g++ > > > > make test > > > > on 2.3.3 I get > > > > ... > > test_queue > > test_quopri > > test_random > > test_re > > make: *** [test] Speicherzugriffsfehler (Speicherauszug erstellt) > > Everything works fine if I remove the "--enable-shared" flag from > configure. You don't mention what platform you are seeing this on. The output of a verbose test run (python Lib/test/regrtest.py -v test_re), preferably with error messages translated to English, may help diagnose the issue. I know that there are platforms where the amount of stack space available to a threaded process is not easily controlled, and recent versions of gcc are creating much larger stack frames than earlier versions. The sre module in 2.3.x (and earlier) is recursive and thus sensitive to stack space availability. A core dump is a likely indicator of this. Read the Modules/_sre.c source file for more info. sre in 2.4 will be significantly improved in this regard. FYI, since 2.3 PyMalloc is a default option so you don't need --with-pymalloc, and most recent Linux and BSD systems will default to building with --with-thread and --with-signal-module. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From gagenellina at softlab.com.ar Wed Dec 24 13:48:49 2003 From: gagenellina at softlab.com.ar (Gabriel Genellina) Date: Wed, 24 Dec 2003 15:48:49 -0300 Subject: nonlinear least square In-Reply-To: Message-ID: <5.2.1.1.0.20031224154455.01f9eec0@192.168.0.115> At 23/12/2003 19:23, you wrote: >I am looking for simple and convenient way to do nonlinear least square >fit from within Python. > >I know that there are such a modules in Scientific Python and SciPy has >it. But I would like to have it small and simple. Module with just this >functionality. It can be not very fast, but in pure python for beter >compatibility. See: http://margaretmorgan.com/wesley/python/ http://astrosun.tn.cornell.edu/staff/loredo/statpy/ Gabriel Genellina Softlab SRL From http Tue Dec 23 02:31:03 2003 From: http (Paul Rubin) Date: 22 Dec 2003 23:31:03 -0800 Subject: Flat file database References: Message-ID: <7xy8t4m1mw.fsf@ruckus.brouhaha.com> "Art Decco" writes: > I realize that's a bit vague, but I'm just wondering about the best approach > for creating a little database-backed CGI app using Python on a server with > no real database available. The server belongs to the ISP, and I don't get > to install "real" software, but they do have a cgi-bin directory for me, and > they do have a relatively recent Python, so I've got Python cgi apps working > via "#!/usr/local/bin/python". I can get the apps to write and read plain > text files right in the cgi-bin directory, too, so I can use that as a > simple, flat file database. Most web hosts offer you access to a database, typically MySQL. Use that if you can. Implementing what you're asking is harder than it sounds. What happens if two people connect to your application both try to update the database at the same time? From paul at boddie.net Sat Dec 20 18:39:21 2003 From: paul at boddie.net (Paul Boddie) Date: 20 Dec 2003 15:39:21 -0800 Subject: Is anyone using Python for .NET? References: <23891c90.0312170334.2cee015@posting.google.com> <23891c90.0312180345.6cdda060@posting.google.com> Message-ID: <23891c90.0312201539.59d9c3d8@posting.google.com> "Brandon J. Van Every" wrote in message news:... > > What I decided was, Python has too much community, library, and industry > support behind it, and a lot of these other languages carry major design > risks, i.e. going from imperative to functional programming. So as of > today, Python is winning in practice despite whatever might be better in > theory. Yes, despite the theoretical advantages of many languages, Python has a lot of working code available for it, some well-established approaches for certain kinds of activities, and quite a bit of guidance and support around those activities. Consequently, upon discovering that more legwork is necessary to get up to speed in those other languages in order to implement a given solution, one can be rather dissuaded from pursuing those other languages further. > See any parallels with Java or C# history debates? Really, one can always ask, "Is this language good enough?" I've seen a number of cases where implementation languages being used have been less than appropriate for the applications concerned and where a different language could have been used, not just for reasons of elegance or performance, but mainly for access to much better application frameworks. For example, why use C++ for Internet server applications when Java (or Python) has a lot more framework support in that area? There was some mention of "Worse is Better" on Ian Bicking's weblog which convinced me that one can almost base one's career on such debates, however. ;-) > > Well, I get a fair amount of mileage out of Jython, Apache Axis (SOAP) > > and so on, but I guess that this isn't your point. > > It could be for your problem domain, but it isn't for mine. I suppose that's a good argument for improved across-the-board interoperability. Shouldn't one be able to write Internet server applications in C++ whilst using various Java-based Apache frameworks? > I would hope that there's a replacement strategy for the interop concept. > Aren't the FSF guys doing something like that? DotGNU Portable.NET perhaps: http://www.dotgnu.org/pnet.html Paul From blk at srasys.co.in Wed Dec 10 01:01:06 2003 From: blk at srasys.co.in (bala) Date: Wed, 10 Dec 2003 11:31:06 +0530 Subject: How to use User Defined TestResult Class Message-ID: <008d01c3bee3$004129b0$440210ac@Bala> Hi, I want to store the result in my Own TestResult(ie MyTestResult class).if i run the below testcase,defaultTestResult method not get called..My Requirement is If i run the TestCase, the Result should be stored in MyTestResult Class,i don't want to store in the TestResult class .....Pls give a Solution....With Some UserDefined TestResult class(Not UnitTesting Frame work TestResult Class)import unittest class MyTestCase(unittest.TestCase): def defaultTestResult(self): return MyTestResult() class MyTestResult(unittest.TestResult): def __init__(self): self.errors_tb = [] self.failures_tb = [] def addError(self, test, err): self.errors_tb.append((test, err)) unittest.TestResult.addError(self, test, err) def addFailure(self, test, err): self.failures_tb.append((test, err)) unittest.TestResult.addFailure(self, test, err) Regards,Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 31 08:12:51 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 31 Dec 2003 14:12:51 +0100 Subject: 'inverting' a dict In-Reply-To: References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: <3ff2cb53$0$316$e4fe514c@news.xs4all.nl> Jeff Epler wrote: > Does this listcomp give the right result? > dict([(v, k) for k, vs in original.iteritems() for v in vs]) Yes it does, and it's even more concise than Yermat's solution dict([(v,k) for k in d.iterkeys() for v in d[k]]) because it avoids a dict lookup every loop cycle. Thanks Jeff! --Irmen From jsbenson at bensonsystems.com Wed Dec 3 16:06:02 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 3 Dec 2003 13:06:02 -0800 Subject: reloading modules Message-ID: <022d01c3b9e1$4349dc40$8f0a500a@jsbwxp3> Reload will reload the specified module, but will not recursively reload modules imported by the specified module, sorry. From colliera at nu.ac.za Wed Dec 17 02:02:41 2003 From: colliera at nu.ac.za (Andrew Collier) Date: Wed, 17 Dec 2003 09:02:41 +0200 Subject: c++, swig and mpatrol Message-ID: hello, i am not sure whether this problem relates to swig, python or my c++ compiler. +please forgive me if this is inappropriately posted but i am sure that someone +on this list must have some good ideas. i have also sent i to the swig users list a couple of times but have not got any response so i am casting my net a little wider... i have been struggling with the following problem for a couple of days now. +specifically, i have a logger class within a larger project. this class is coded in c++ but this is all wrapped up in a python interface which i generate with swig. recently i built the project with mpatrol and got some errors like: ERROR: [NOTALL]: free: 0x0806E758 has not been allocated so i trimmed down all the excess stuff until i had the minimum code which still +produced the errors. the header file looks like: -- log.h ----------------------------------------------------------------------- #ifndef _LOG_H #define _LOG_H #include class Logger { public: void debug(const std::string msg) {cerr << msg << endl;} }; extern Logger logger; #endif -------------------------------------------------------------------------------- and this is swig'd via the following simple interface file: -- log.i ----------------------------------------------------------------------- %module log %{ #include "log.h" %} %include std_string.i %include log.h %pythoncode %{ logger = _log.cvar.logger %} -------------------------------------------------------------------------------- the global instance of the Logger class, logger, is the only thing in the source +file log.cc. i build the project with the following: -- Makefile -------------------------------------------------------------------- %.o: %.cc g++ -I/usr/local/include/python2.3 -g -O -c $< _logmodule.so: log.o log_wrap.o g++ -shared -o $@ $^ -lmpatrol -lbfd log_wrap.cc log.py: log.i swig -c++ -python -shadow -o log_wrap.cc $< -------------------------------------------------------------------------------- now, when i run this snippet of python code: import log msg = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" log.logger.debug(msg) the mpatrol.log file has: FREE: free (0x0804BA18) [-|-|-] 0x001280C9 _wrap_Logger_debug+897 0x0017A3C6 PyCFunction_Call+150 0x001543F9 PyObject_Call+45 0x001AF0A2 PyEval_CallObjectWithKeywords+206 0x001A4113 builtin_apply+323 0x0017A3C6 PyCFunction_Call+150 0x001AF1F1 call_function+301 0x001AD864 eval_frame+10576 0x001AE824 PyEval_EvalCodeEx+1848 0x001B0EB9 fast_function+297 0x001AF27A call_function+438 0x001AD864 eval_frame+10576 0x001AE824 PyEval_EvalCodeEx+1848 0x001B0D26 PyEval_EvalCode+50 0x001D1144 run_node+76 0x001D10E7 run_err_node+47 0x001D0DE3 PyRun_FileExFlags+107 0x001CF832 PyRun_SimpleFileExFlags+406 0x001D092F PyRun_AnyFileExFlags+107 0x001D7277 Py_Main+2119 0x08048611 main+33 0x002C717D __libc_start_main+189 0x08048531 _start+33 ERROR: [NOTALL]: free: 0x0804BA18 has not been allocated which seems to indicate that memory is being free'd without be previously +allocated. the odd thing is that if i either: o compile with -O0, o make the msg string ("xxx....xxx") one character shorter then the error goes away. this seems very mysterious to me given that it is a +very simple little module. if i set MPATROL_OPTIONS="CHECKALL USEDEBUG" then there is a little more +information: FREE: free (0x0806F448) +[_wrap_Logger_debug|/usr/lib/gcc-lib/i386-slackware-linux/2.95.3/../../../../in +clude/g++-3/stl_alloc.h|434] 0x001280C9 _wrap_Logger_debug+897 at +/usr/lib/gcc-lib/i386-slackware-linux/2.95.3/../../../../include/g++-3/stl_allo +c.h:434 0x0017A3C6 PyCFunction_Call+150 at +/u2/src/NEW/Python-2.3/Objects/methodobject.c:77 0x001543F9 PyObject_Call+45 at +/u2/src/NEW/Python-2.3/Objects/abstract.c:1756 0x001AF0A2 PyEval_CallObjectWithKeywords+206 at +/u2/src/NEW/Python-2.3/Python/ceval.c:3347 0x001A4113 builtin_apply+323 at +/u2/src/NEW/Python-2.3/Python/bltinmodule.c:106 0x0017A3C6 PyCFunction_Call+150 at +/u2/src/NEW/Python-2.3/Objects/methodobject.c:77 from which i gather that it is choking on something in stl_alloc.h. i was under +the impression that stl was pretty failsafe regarding memory management. i mean +there's nothing fancy in my source files. here are some details of my system: gcc-2.95.3 swig-1.3.19 python-2.3 i would be very grateful if anyone had any ideas what might be causing this +problem. best regards, andrew collier. -- Andrew B. Collier Antarctic Research Fellow tel: +27 31 2601157 Space Physics Research Institute fax: +27 31 2616550 University of Natal, Durban, 4041, South Africa From jepler at unpythonic.net Wed Dec 24 09:54:27 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 24 Dec 2003 08:54:27 -0600 Subject: implementing mv In-Reply-To: References: Message-ID: <20031224145427.GA441@unpythonic.net> You should look at the 'shutil' module. It provides a move() function. $ pydoc shutil.move Help on function move in shutil: shutil.move = move(src, dst) Recursively move a file or directory to another location. If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. (I assume mv.c is the source for the unix "/bin/mv" utility, available in multiple incarnations) Jeff From naesten at myrealbox.com Fri Dec 19 16:00:09 2003 From: naesten at myrealbox.com (Samuel Bronson) Date: 19 Dec 2003 16:00:09 EST Subject: Simple Recursive Generator Question In-Reply-To: <92c59a2c.0312191113.569724ca@posting.google.com> References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: MetalOne wrote: > This is what I have, but it does not work. > Changing yield to print, shows that the recursion works correctly. > > def bitIndexGenerator(mask, index=0): > if mask == 0: return > elif mask & 0x1: yield index > bitIndexGenerator(mask >> 1, index+1) > > What am I missing? Everything needs to be yielded from the outermost generator, like def bitIndexGenerator(mask, index=0): if mask == 0: return elif mask & 0x1: yield index for i in bitIndexGenerator(mask >> 1, index+1): yield i However, this is ugly ;-), and kind of defeats the purpose of generators. Why do you want to use recursion like this? From peter at engcorp.com Mon Dec 1 16:57:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 01 Dec 2003 16:57:34 -0500 Subject: How to delete this file ??? References: Message-ID: <3FCBB94E.A4FFB416@engcorp.com> DCK wrote: > > Hello again > Really sorry for long time between me letters. All problem gone, after i've > used raw string (r"\\path\to\any\file") Really thanks for all answers :) Note that it's almost always better to use forward slashes instead. In this case, "//path/to/any/file" would work wonderfully, and is much more readable. Yes, it does work with Windows. The only time it doesn't is when using command line programs which interpret the forward slash as an option, and insist on backslashes. (An unfortunate additional area is that os.path for Windows normalizes things to use backslashes, and therefore path comparisons can get a little tricky if you use forward slashes but aren't careful about normalizing with os.path.normpath() all the time.) -Peter From jimmy at retzlaff.com Thu Dec 4 20:09:21 2003 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Thu, 4 Dec 2003 17:09:21 -0800 Subject: Turning f(callback) into a generator Message-ID: Peter Otten wrote: [Nice generalization of a thread-based generator, thanks] > The question that has come up writing the above, how you would handle > exceptions in the thread? I put them in the queue and reraise them in the > main thread, but I'm not feeling very confident about it... Perhaps there should be a second queue for an exception and the sentinel. Then the main loop could look something like this (untested): while terminationQueue.empty() or not queue.empty(): # The timeout is needed because we may have arrived here after # the last value was placed in the queue but before the sentinel # or an exception was placed in the terminationQueue. yield queue.get(timeout=0.1) terminationValue = terminationQueue.get() if terminationValue is not sentinel: raise terminationValue In this case the launcher function would put the sentinel in the terminationQueue instead of the data queue. The idea of the loop condition above is to yield everything that came through before the exception/sentinel, then re-raise any exception if that was the reason for terminating. This would hopefully help clarify where the exception occurred (i.e., on which element in the iteration). The separate queue also eliminates the problem of someone somehow finding a way of injecting the sentinel into the data stream. But this does create the need for the timeout (which doesn't work in 2.2). I guess it's a judgment call as to whether the sentinel should be placed in one queue or the other (or both). Your generalization could make a nice Python Cookbook recipe if you feel like putting it together. At least two of us have needed this sort of thing. Jimmy From duncan at NOSPAMrcp.co.uk Wed Dec 10 08:25:12 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Dec 2003 13:25:12 +0000 (UTC) Subject: About the use of **args References: Message-ID: Mark McEahern wrote in news:mailman.27.1071059861.9307.python-list at python.org: > # We can still access the "private" member variable. In Python, > # private is merely a convention. > print s._size Except that in Python the convention for private variables is to begin them with two underscore characters, and then it is more than just a convention: >>> class Shoe2(object): def __init__(self): self.__size = None def getSize(self): print "In getSize..." return self.__size def setSize(self, size): print "In setSize..." self.__size = size size = property(getSize, setSize) >>> s2 = Shoe2() >>> s2.size = 1 In setSize... >>> print s2.size In getSize... 1 >>> print s2.__size Traceback (most recent call last): File "", line 1, in -toplevel- print s2.__size AttributeError: 'Shoe2' object has no attribute '__size' Of course, it doesn't absolutely prevent you accessing the private variable if you know what you are doing, but then neither do C++ or Java: >>> print s2._Shoe2__size 1 -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From richie at entrian.com Mon Dec 8 10:16:19 2003 From: richie at entrian.com (Richie Hindle) Date: Mon, 08 Dec 2003 15:16:19 +0000 Subject: How to graph two columns of x,y numbers? In-Reply-To: <9b849915.0312072230.5cab87b0@posting.google.com> References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: <6v39tvk1gg22sc2t5o0fqi0p0kf3prqpfl@4ax.com> [Todd] > I would like to do 2D and possibly 3D plotting with python. I am > tending toward wxpython because of it's ease of use. I'm in the same boat, so I'm also interested to hear people's opinions. My requirements are exactly the same as Todd's except that I'm also looking for high visual quality - antialiasing of both text and lines, partially-transparent bars and areas, that kind of thing. Something like an Anti-Grain (http://www.antigrain.com/) back end for matplotlib (http://matplotlib.sourceforge.net/) that used freetype (http://www.freetype.org/) for font rendering and provided easy integration into wxPython (http://www.wxpython.org/). Not much to ask. 8-) -- Richie Hindle richie at entrian.com From no at spam.invalid Tue Dec 23 14:16:35 2003 From: no at spam.invalid (Russell E. Owen) Date: Tue, 23 Dec 2003 11:16:35 -0800 Subject: Tkinter and OS X 10.3? References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: >Anyone used Tkinter on 10.3 yet? With X11 or with Aqua? There are some nasty issues with Aqua: - Python 2.3 (the aqua version that comes with Panther) has a bug that prevents some standard Tkinter file dialogs from working. IDLE and a big Tkinter app I am writing both make some use these broken dialogs. - (Catch 22) You cannot easily upgrade MacPython on Panther. Simply installing a later version (in /Library/Frameworks) causes nasty problems when you try to install packages (an issue that has gotten a lot of discussion on the Mac mailing list will apparently be resolved in Python 2.4). You could delete /System/Library/Frameworks/Python, but this is claimed to be a Very Dangerous Thing To Do by some folks in the know. I still haven't gotten an explanation of why this is so bad and I confess I'm still tempted to just do it and to hell with it, but I'm going to wait in hopes of hearing more first. Python with Tkinter is one of my main uses for this Mac, so the problem is a big one for me. - Also, Aqua Tk still has a lot of cosmetic bugs. Menus and checkbuttons show truncated or wrapped text for most choices of fonts. Some buttons don't get displayed at first (but are present and can be pressed). Stuff like that. There are a lot of bug reports on source forge, but there have been several minor releases of tcl/tk with no progress in that area (I don't mean to sound whiney; I realize full well it's folks like you or I that have to volunteer to fix bugs for open source; I do actually put in some work on Tkinter but haven't dared brave the guts of tk). I imagine X11 Tkinter works fine, though I confess I've only just finished building it and haven't actually run my app yet. Still, I can't imagine why it wouldn't unless Apple did something dreadful to X11. -- Russell From ajsiegel at optonline.com Thu Dec 25 18:59:12 2003 From: ajsiegel at optonline.com (Arthur) Date: Thu, 25 Dec 2003 23:59:12 GMT Subject: 2.3 list reverse() bug? References: Message-ID: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> On Thu, 25 Dec 2003 05:17:47 -0600, Bjorn Pettersen wrote: >There is a module called copy that let you get the semantics that you're >looking for. I've never used it in my 6+ years of Python programming, since >it normally indicates the presence of flawed logic . > Why would you mention this in the context here? I remain confused by this oft repeated mantra regrading the use of copy. Are you saying that the need to copy a list indicates flawed logic, or that doing it otherwise than by list[:] is flawed? I have to assume the latter, but am willing to learn otherwise. But if the latter.... Why even mention copy in this context? But once mentioned, I need to ask then why the use of copy(list) is flawed. That is, are there reasons beyond the obvious, of extra keystrokes. And speed optimization, to the extentf it might be considered material in a particular instance. Art From bjorn.pettersen at comcast.net Thu Dec 25 06:22:26 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Thu, 25 Dec 2003 05:22:26 -0600 Subject: 2.3 list reverse() bug? References: Message-ID: Robin Becker wrote in news:Mo0idJAPes6$EwWj at jessikat.fsnet.co.uk: > In article , Mark > Carter writes >>I did this: >> >>Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on >>win32 >> >>>>> d1 = [1,2] >>>>> d2 = d1 >>>>> d2.reverse() >>>>> print d1 #note: d1, not d2 >>[2, 1] >>>>> >> >>Surely that can't be right: d1 should still be [1,2]. If it is >>"right", then I expect that many people are in for a suprise. > Really need to get a life, but anyhow here goes. > > It's right. d1 & d2 both point to the same mutable object and sort is > done in place. > > compare with this > >>>> d1=[1,2] >>>> d2=d1 >>>> d2[0]='a' >>>> d1['a', 2] >>>> that's probably less confusing when adding the hidden newline: >>> d1=[1,2] >>> d2=d1 >>> d2[0]='a' >>> d1 ['a', 2] >>> it's-4:30am-here'ly y'rs -- bjorn From fredrik at pythonware.com Sun Dec 7 07:03:16 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 7 Dec 2003 13:03:16 +0100 Subject: New inited instance of class? References: Message-ID: Francis Avila wrote: > If you're curious, look in the Python Language Reference at the old and new > style classes to see the differences. There's absolutely no advantage to > old style classes except performance: http://www.python.org/~jeremy/weblog/030506.html > it's vital for understanding the still poorly-documented new-style classes. documentation may also be seen as an advantage, of course. From newsgroups at jhrothjr.com Fri Dec 19 19:23:12 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 19 Dec 2003 19:23:12 -0500 Subject: dynamic typing questions References: Message-ID: "Robert Brewer" wrote in message news:mailman.361.1071867283.9307.python-list at python.org... John Roth wrote: > Look into Test Driven Development (see Kent > Beck's book by that title.) As Jason says, unit testing > will pretty much eliminate any advantages of static typing, > leaving only the disadvantages. > > Also, pervasive testing has so many other advantages > that I'm beginning to think that debuggers were the > single worst invention in history. Zuh? Unit testing doesn't replace a good debugger; they work together. Unit testing can only show you THAT a test has failed--it can't show you where, how, or why. Think of exception handling (and especially tracebacks) as a mini-debugger. [JR] However, the reports from people actually using Test First seriously is that they're forgetting how to use the debugger! When you work one test a time, if something breaks you know it's the last five lines you entered. You very seldom need to mess around with the debugger to figure out what you did, and if you do, you need to refactor whatever it was - it's too complicated. John Roth [/JR] FuManChu From exarkun at intarweb.us Mon Dec 15 23:39:26 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 15 Dec 2003 23:39:26 -0500 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031215233639.GE26055@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> Message-ID: <20031216043926.GA30498@intarweb.us> [python-dev un-CC'd] On Mon, Dec 15, 2003 at 11:36:39PM +0000, Luke Kenneth Casson Leighton wrote: > On Mon, Dec 15, 2003 at 04:36:35PM -0500, Jeremy Hylton wrote: > > [snip - problems with rexec] > > okay. > > i think the only really sensible way forward is to begin from a > sound basis - one that is going to be a big job to add retrospectively, > but a simple beginning can be made. > > proposal: how about building ACLs into the python codebase? > I would be very strongly against that. Python references much more closely parallel capabilities-based security, and capabilities-based security is much more flexible and expressive. Whether through ACLs or caps, a lot of the work is probably going to fall to you, since few others have expressed sufficient interest (that is to say, interest enough to actually do the work) in this feature for CPython. It may be more productive to examine an alternate Python implementation for this functionality. A little googling should take you a long way on this. > [snip - strange ACL protocol definition] Jp From dck at NOSPAM.gazeta.pl Tue Dec 2 00:53:36 2003 From: dck at NOSPAM.gazeta.pl (DCK) Date: Tue, 2 Dec 2003 06:53:36 +0100 Subject: pixels -> metrics Message-ID: Hello I wonder, is it possible to draw a line in Python, which one will be 1cm long after print. In groups.google i found something like "[...]1 pixel is 1/97inch[...]" but it ist adequate for GD-Library (Kind of PHP library, i think). Do you have any ideas about it ? -- /===============--------- / Wygenerowal: DCK / dnia: 2003-12-02 06:49:46 /===========--------- From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat Dec 20 10:39:07 2003 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 20 Dec 2003 16:39:07 +0100 Subject: Books on Python for Windows References: <%XOEb.31$Bt7.18@newssvr27.news.prodigy.com> Message-ID: Mark Hammond's best-seller : "Python programming in Win32" - O'Reilly - ISBN 1-56592-621-8 From aahz at pythoncraft.com Wed Dec 3 01:01:33 2003 From: aahz at pythoncraft.com (Aahz) Date: 3 Dec 2003 01:01:33 -0500 Subject: speed of spambayes? References: <7xznedqxyx.fsf_-_@ruckus.brouhaha.com> <7xptf639rd.fsf@ruckus.brouhaha.com> Message-ID: In article <7xptf639rd.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> Maybe I shouldn't tell you this so you're forced to use a Python app, >> but you can either disable the network checks or run spamd. ;-) > >I do use spamc/spamd, but spamd is what's going the network checks. >If I start my own spamd instance I can disable them, so I'll probably >do that. spamd is supposed to cache the network checks; perhaps it's not properly configured. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Weinberg's Second Law: If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization. From a.schmolck at gmx.net Thu Dec 4 09:39:50 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 04 Dec 2003 14:39:50 +0000 Subject: Hopelessly Lost And Desperate Newbie References: <20031204092605.01786.00000161@mb-m20.aol.com> Message-ID: afgncaap5 at aol.com (Afgncaap5) writes: > Hello, there. I'm desperately in need of assistance, because I can't figure > out how to get Python to work. Could someone help me with a program that can > examine textual input in pairs of letters, keep track of how often the letters > occur, and then write a random letter generator based on that input, do you? I'd hope not because by the sounds of it you'd like someone to do your homework assignment for you. Post some actual code (however broken) and ask some specific questions about that code if you want help. 'as From gerrit at nl.linux.org Wed Dec 17 07:24:11 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 17 Dec 2003 13:24:11 +0100 Subject: Zen of ... In-Reply-To: <1071600670.1207.3.camel@emilio> References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: <20031217122411.GA1850@nl.linux.org> Tim Churches wrote about the Zen of Python: > It is entirely possible to do programming in Perl, but the results bear > little resemblance to these desiderata. Ok. So the Zen of Python shouldn't *be called* the Zen of Programming. But shouldn't it *be* the Zen of Programming? ;) Can the Zen be used as a programming-guide, rather than a language-design guide? yours, Gerrit. -- 28. If a chieftain or a man be caught in the misfortune of a king, if his son is able to enter into possession, then the field and garden shall be given to him, he shall take over the fee of his father. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From engsolnom at ipns.com Mon Dec 29 19:44:34 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Mon, 29 Dec 2003 16:44:34 -0800 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> Message-ID: On 29 Dec 2003 15:34:03 -0800, Paul Rubin wrote: >engsolnom at ipns.com writes: >> After looking at the suggestions for a ishexdigit method, (thanks >> again), I decided on the following, partly because I don't have to >> import string, and I believe it's pretty readable by Python newbies, >> which we (including myself) have at work: >> >> def ishexdigit(sx): >> ix = 0 >> for cx in sx: >> ix += 1 >> if not cx in '0123456789abcdefABCDEF': return 0 >> if ix % 2 == 0: return 1 >> else: return 'Extra nibble' > >Some remarks: > >1) I think the name is a misnomer: "ishexdigit" should test just one >digit, not a multi-digit string. This function should be called >"ishexnumber" instead. I used 'isdigit' as a model, since it takes a string also. But ishexnumber works for me too, except I'll usually pass long strings to it..:) > >2) I'm not sure why you return 'extra nibble' if there's an odd number >of digits. Isn't '123' a perfectly good hex number (= 291 decimal)? > >3) Even if you do want to check that the length is odd, you don't > need to count the chars in the loop: > > def ishexnumber(sx): > for cx in sx: > if not cx in '0123456789abcdefABCDEF': return 0 > if len(sx) % 2 == 0: return 1 > return 'Extra nibble' > > (the final 'else' is not needed) Forehead slap! "if len(sx) % 2 == 0:" makes better sense...thanks! > >4) You could also use a regular expression to test for hex digits: > > def ishexnumber(sx): > import re > if not re.match('[0123456789abcdefABCDEF]*$', sx): return 0 > if len(sx) % 2 == 0: return 1 > return 'Extra nibble' If I run this many times, as is likely in our application, does the 'import re' chew up memory? > >5) If you want the number of bytes to be even because the hex string > is supposed to represent a character string, and you're going to > do the conversion next, there's already a library function for that: > > import binascii > s = binascii.unhexlify(sx) > >6) If you want it to be a number but still need the digit count to > be even for some reason, then checking for the special value > 'Extra nibble' is messy. It's usually better to raise an exception > instead: > > def ishexnumber(sx): > for cx in sx: > if not cx in '0123456789abcdefABCDEF': return 0 > if len(sx) % 2 != 0: > raise ValueError, 'Extra nibble in hex string' > return 1 > > The caller then has to catch the exception, of course. I do need to learn more about exceptions. > >7) If you want to just check that the hex string represents an > integer, possibly the most robust way is: > > def ishexnumber(sx): > try: > n = int(sx, 16) > except ValueError: > return 0 > return 1 > > Note this will fail for hex strings are too long to fit in a short int. Our strings will almost always be long ones, and the byte values will range from zero to 255, but I'll tuck this nugget into the archive. Thanks for the comments. Norm From exarkun at intarweb.us Tue Dec 30 14:33:44 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 30 Dec 2003 14:33:44 -0500 Subject: Storing objects required by functions. In-Reply-To: References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: <20031230193344.GA15706@intarweb.us> On Tue, Dec 30, 2003 at 12:43:13PM -0500, Terry Reedy wrote: > > I default args less bothersome than some people. The only problem for me > is that a caller may accidentally give nonesense second param. If this can > silently give a junk answer, this is not very acceptable. In this case, > random objects without a match() method would raise an exception. > > > g = re.compile('...') > > Use _ to indicate 'private' or 'local-use-only' status. > > _hex = re.compile() > Why should it be local-use-only? Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rm at rm.net Thu Dec 4 12:07:57 2003 From: rm at rm.net (Roel Mathys) Date: Thu, 04 Dec 2003 17:07:57 GMT Subject: Remove no-printable characters in string In-Reply-To: References: Message-ID: Pascal wrote: > Hello, > > What's the best way to delete or replace no-printable characters in a string. > i.e.: "\x08toto\x00titi" -> "tototiti" or " toto titi" import string import sets printable = sets.Set( string.printable ) def f1( s ) : return ''.join( [ i for i in s if i in printable or i.isalpha() ] ) def f2( s ) : replace = { '\x00' : ' ' } t = ''.join( [ replace.get(i,i) for i in s if i in printable or i.isalpha() # for non ascii characters or i in replace ] ) s = "\x08toto\x00titi" t1 = f1(s) => 'tototiti' t2 = f2(s) => 'toto titi' works nicely, I think bye, roel From EP at zomething.com Sat Dec 13 23:57:05 2003 From: EP at zomething.com (EP) Date: Sat, 13 Dec 2003 20:57:05 -0800 Subject: Strip HTML tags? In-Reply-To: <7b454334.0312131911.70647953@posting.google.com> Message-ID: <5.2.0.9.0.20031213204420.00b77de8@mail.zomething.com> >Hello, > >I was wondering what would be the easiest way to strip away HTML tags from >a string? > >Or how would I remove everything between < and > also the < , > as well >using regex? I'm a newbie, but here's a way I did it: ## compile regular expressions for HTML tags... I did a separate one for line breaks htmltags=re.compile(r'|

    ||||||
    |||||') linebreaks=re.compile(r'
    |
    ') ## not shown: some lines to input or iterate files go here; then you get the html file as a string: wwwf=open(nextfile, 'r') strng=wwwf.read() wwwf.close() ## execute some regular expression methods ## first one substitutes empty single quotes for known html tags nohtml=htmltags.sub('',strng) ## this one splits the string into lines on
    or
    consuming the html tag in the process textlines=linebreaks.split(nohtml) ## you could then print it to stdout or file for line in textlines: print line OK, on second thought it was probably not the easiest way, which is what you asked; but it wasn't hard and I understood how it worked. :-) From exarkun at intarweb.us Mon Dec 22 09:22:27 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 22 Dec 2003 09:22:27 -0500 Subject: calling the function police In-Reply-To: <5.2.0.9.0.20031221223023.026e9ba8@mail.zomething.com> References: <5.2.0.9.0.20031221223023.026e9ba8@mail.zomething.com> Message-ID: <20031222142227.GA21664@intarweb.us> On Sun, Dec 21, 2003 at 10:32:25PM -0800, EP wrote: > Oops. copied wrong: > > >>>> result=function1(first=parameter, end='noodles','Jim Beam', 'Poker') > > strike that. > > It was actually: > > >>> result=function1('Jim Beam', 'Poker',first=parameter,end='noodles') > > and got this error: > > >TypeError: function1() got multiple values for keyword argument 'first' > 'Jim Beam' is passed as an argument for "first". 'Poker' as an argument for "end". Then, parameter is passed as an argument for "first", and 'noodles' as an argument for "end". No arguments are passed for the *argument (I forget what it was called in your example). In general, the first argument matches up with the first parameter, the second with the second, and so forth. Does this make sense now? Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From roy at panix.com Fri Dec 5 10:29:33 2003 From: roy at panix.com (Roy Smith) Date: Fri, 05 Dec 2003 10:29:33 -0500 Subject: Lists and Tuples References: Message-ID: In article , Jeff Wagner wrote: > I've spent most of the day playing around with lists and tuples to get a > really good grasp on what > you can do with them. I am still left with a question and that is, when > should you choose a list or > a tuple? I understand that a tuple is immutable and a list is mutable but > there has to be more to it > than just that. Everything I tried with a list worked the same with a tuple. > So, what's the > difference and why choose one over the other? > > Jeff The big difference is that tuples (because they are immutable) can be used as dictionary keys. So, if you are going to use it as a key, it's got to be a tuple. If you're going to want to add/delete/change items in it, it's got to be a list. If you will never change it, but have no syntatic constraint forcing it to be immutable, you can pick whichever turns you on. From a stylistic point of view, I tend to think of tuples when I need to bundle up a collection of related items (such as a function returning multiple items). Lists make me think of number of the same kind of item. From joshway_without_spam at myway.com Wed Dec 24 14:02:56 2003 From: joshway_without_spam at myway.com (JCM) Date: Wed, 24 Dec 2003 19:02:56 +0000 (UTC) Subject: ungetch in Python References: Message-ID: anton muhin wrote: ... > First of all I'd rather suggest to use one of parsers for Python---there > are plenty of them and they are really nice. If you go this route, I suggest PLY (http://systems.cs.uchicago.edu/ply). It's worked well for me. From claird at lairds.com Thu Dec 11 09:30:19 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 11 Dec 2003 14:30:19 -0000 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> Message-ID: In article , Brian Kelley wrote: >Paul Rubin wrote: > >> I've been approached about writing a Windows app which will need a >> really professional looking GUI. Forget TKinter, this has to actually >> look good (real artists will be available to get the visual stuff >> right). Assuming I write in Python, what's the best toolkit to use? . . . >Why forget Tkinter? I've seen Tkinter applications that look incredibly >fabulous. A lot depends on what you are trying to do. If you are . . . Paul, I certainly can understand your dismissal of Tkinter as it's commonly employed. Are you aware, though, of and ? Tkinter might, in fact, best meet your requirements. -- Cameron Laird Business: http://www.Phaseit.net From fBechmann at web.de Mon Dec 29 16:09:05 2003 From: fBechmann at web.de (Frank Bechmann) Date: 29 Dec 2003 13:09:05 -0800 Subject: just another default argument value gotcha References: Message-ID: thx for that tip, it worked as predicted. nevertheless it seems to be an error if some function/method uses the 'sys.stdout' default value but *not* the 'print >>out' syntax. and this in turn means that my simple grep error finder doesn't help too much, you still have to look at the code of the matching functions/methods. From cmkleffner at gmx.de Wed Dec 3 06:28:25 2003 From: cmkleffner at gmx.de (cmkl) Date: 3 Dec 2003 03:28:25 -0800 Subject: Can Python be run off of a CD-ROM? References: Message-ID: <3b091a1c.0312030328.68eaabe4@posting.google.com> I've done this with Python-2.3.2-1 on Windows with installing a 'registry free' Python on local network. It should work with a CD-ROM copy as well. First step is to install Python on a machine locally as a non-administrator. You could change this as an option in the Python installer. The non-admin option ensures, that all needed DLLs are packed in the Python directory rather the Windows system directory. Next step are win32all, wxPython, GTK, pyGTK and all other needed packages. This version uses the registry, but the registry wouldn't be readed if you set the enviroment variables %PYTHONHOME% and %PYTHONPATH%. If you want to use pyGTK you have to change the PATH variable too. For some systems with old versions of some MS DLLs you may want to ensure that the DLLs delivered with the Python packages are loaded at runtime. I use a variable called "PY_DEPRECATED_OS". All MS DLLs have to be moved in a dedicated directory, i.e. %PYTHONHOME%DLLs\MS_DLLs . (see example below) All this enviroment tweaking could be done by startup batch files instead of changing the enviroment on every Windows client (except the PY_DEPRECATED_OS variable) See the Pythonwin.bat file below. You can create startup files for python, pythonw, idle as needed. ----- Pythonwin.bat example ------------------------------------- @echo off setlocal if not "x%PYTHONHOME%" == "x" goto _START rem never overwrite PYTHONHOME, PYTHONPATH und PATH rem if PYTHONHOME was still set in enviroment if not "x%OS%" == "xWindows_NT" goto _WINDOWS9X rem Windows NT and Win9x differs set PYTHONHOME=%~dp0 goto _PYTHONPATH :_WINDOWS9X set PYTHONHOME=%0\..\ goto _PYTHONPATH :_PYTHONPATH rem PYTHONPATH for win32all set PYTHONPATH=%PYTHONHOME%lib\site-packages\Pythonwin;%PYTHONHOME%lib\site-packages\win32;%PYTHONHOME%lib\site-packages\win32\lib rem PATH for GTK-2.0 set PATH=%PYTHONHOME%..\GTK\2.0\bin;%PYTHONHOME%..\GTK\2.0\lib;%PATH% rem PATH for MS DLLs if "x%PY_DEPRECATED_OS%" == "xTRUE" set PATH=%PYTHONHOME%DLLs\MS_DLLs;%PATH% :_START start %PYTHONHOME%pythonwin.exe %* endlocal ----- Pythonwin.bat example end --------------------------------- "BJ MacNevin" wrote in message news:... > Hi all, > > I teach middle school and am currently trying to bring some computer science > to the students. Our district has a wonderfully linked network throughout > all our schools... done via MS Windows Network. In order to protect the > network, our district's IT department does not want things installed on the > system (or at least makes it VERY difficult to get it done). SO, I am using > MSW Logo installed onto a CD-ROM... we just stick in the CD-ROMS and run it > off of them. > > BUT, I am learning about Python and think it is TERRIFIC! So I wonder if I > can do the same thing... or something similar? Is there a way to install > Python on a CD-ROM, too, if we don't need it to be accessed from a command > prompt? > > Thanks, > BJ MacNevin From ramen at lackingtalent.com Wed Dec 24 03:40:56 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 24 Dec 2003 08:40:56 -0000 Subject: Email attachments and text References: <3fdd7457$0$217$e4fe514c@news.xs4all.nl> Message-ID: In article <3fdd7457$0$217$e4fe514c at news.xs4all.nl>, Remco Boerma wrote: > --SEPERATORLINEWICHSHOULDNEVEROCCURINREALTEXT ^^^^^^^^^ Sorry to be pedantic, but please, this one just kills me. Remember this; tell a friend: there's *A* *RAT* in sepARATe Thanks in advance. =) PS. ''.join(map('WICH'.__getitem__, [3 * x for x in range(2)] + range(1, 4))) -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From peter at engcorp.com Wed Dec 10 09:26:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Dec 2003 09:26:59 -0500 Subject: multi-threaded app hangs References: Message-ID: <3FD72D33.90FB8D84@engcorp.com> > Sudipto Biswas wrote: > > I have written a multi-threaded (about 8 threads) networking application [snip] > The program runs fine on Python-2.2.2/RH 8.0. > > But when I move to Python-2.2.2/RH-9.0 the program behaves oddly. [snip] I vaguely recall a comment somewhere about the threading model changing in Redhat 9.0. Could this be the cause? Maybe somebody else will have a specific reference, or you could try Google. -Peter From dave at pythonapocrypha.com Tue Dec 2 08:25:21 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 2 Dec 2003 06:25:21 -0700 Subject: python's threading has no "interrupt"? References: Message-ID: <03a501c3b8d7$bc88fec0$6500000a@YODA> Jane wrote: > > >>As far as I know python's threading module models after Java's. > > >>However, I can't find something equivalent to Java's interrupt and > > >>isInterrupted methods, along with InterruptedException. > > >>"somethread.interrupt()" will wake somethread up when it's in > > >>sleeping/waiting state. > > >> > > >>Is there any way of doing this with python's thread? I suppose thread > > >>interrupt is a very primitive functionality for stopping a blocked > > >>thread. > > >> > > >> > > >Well, I haven't got any answer since I posted it. Meanwhile, I have > > >been searching for it myself. Something new has been added in 2.3 in > > >thread module. That's interrupt_main. But, unfortunately, it is the > > >opposite of what I expected; It interrupts the main thread. > > > > > >After all this, I am a bit disappointed about Python. (it's sad) > > > > > > > > Did you try condition objects? threading.Condition [snip] > > Thanks, but it doesn't give a solution. The problem is that there can > be multiple condition variables and I have to interrupt the thread no > matter what condition variable is waiting. What's your actual use case (IOW, what programming problem are you trying to solve)? Maybe there is a Python solution that will work for you, but in order to help you find it, people here will need to better understand what you're trying to do. You've noticed that there isn't an identical construct for what you were doing in Java, so it may be that the Python way will be a completely different approach to the problem rather than just a direct conversion from Java to Python syntax. -Dave From pedrosch at gazeta.pl Sun Dec 14 07:28:20 2003 From: pedrosch at gazeta.pl (Przemo Drochomirecki) Date: Sun, 14 Dec 2003 04:28:20 -0800 Subject: connection to samba server References: <3fdbc954$0$218$e4fe514c@news.xs4all.nl> Message-ID: There's a task: 1) connect to linux samba server from windows application 2) compare files from samba server with files from choosen windows catalog(s) 3) make backup if it's necessary. So my problem is how to make connection with samba server having triple (IP server, login, password) and download/upload files. I'm working on Wk2. I was searching for suitable library but found nothing. Regards Przemek Drochomirecki From jeroen_ at _os3.dot.nl Sat Dec 6 14:53:38 2003 From: jeroen_ at _os3.dot.nl (Jeroen van der Ham) Date: Sat, 06 Dec 2003 20:53:38 +0100 Subject: Reading pipes in Python References: Message-ID: On Sat, 06 Dec 2003 18:42:35 +0100, Rene Pijlman wrote: > >This loop is endless, so don't complain to us that it doesn't end :-) > >>what can be done to make it work? > >f=open('ff','r') >while 1: > li = f.readline() > if not li: break > print li, This works, but only for a single line. The idea is that the pipe takes the place of a log of an application so that the script can do something because something is written to the log. Jeroen. From jcb at iteris.com Fri Dec 19 18:41:23 2003 From: jcb at iteris.com (MetalOne) Date: 19 Dec 2003 15:41:23 -0800 Subject: Simple Recursive Generator Question References: <92c59a2c.0312191113.569724ca@posting.google.com> Message-ID: <92c59a2c.0312191541.7a7bace3@posting.google.com> Thanks. From newsgroups at jhrothjr.com Wed Dec 10 07:48:38 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 10 Dec 2003 07:48:38 -0500 Subject: About the use of **args References: Message-ID: "Zunbeltz Izaola" wrote in message news:m1oeuhqd7k.fsf at lcpxdf.wm.lc.ehu.es... > > Hi > > I'm starting a new proyect and i'm in doubt about diferent interfaces > for my clases. My clases will have a lot of attributes and i'm want to > know what aproach could be the best > > 1) Define one SetAttribute/GetAttribute pair of method for each > attribute. > 2) Define one SetAttribute/GetAttribute which argument is a key=value > format. > > Any advaice? > > Thanks in advance > > Zunbeltz Izaola I presume you're talking about constructing the object, not about state changes after it's been constructed and released into the wild? In that case, the "best" pattern is to never let the object appear half constructed. There are a wide variety of ways of doing this, from passing all the needed parameters into the constructor, to numerous variations on the factory pattern. And I wouldn't be adverse to the other responder's practice of simply plugging values into the instance while it's still in the factory: most real world objects don't contain the logic for their construction, so why should our programming objects? John Roth > From bokr at oz.net Sat Dec 13 20:29:19 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 01:29:19 GMT Subject: ANN: lunatic-python 0.1 References: <_PKdnYhLC60dF0ai4p2dnA@comcast.com> <7xad5wgx4z.fsf@ruckus.brouhaha.com> Message-ID: On 13 Dec 2003 14:39:56 -0800, Paul Rubin wrote: >"Terry Reedy" writes: >> Accessing above with default IE6 brings up Untrusted Certificate >> page. With choices Proceed, Stop, AddCertificate (to root table). >> It seems conectiva issued itself its own certificate. I hope this >> is just silliness rather than a devious attempt to get people to >> accept its self-certification, which I was not about to do. > >There's no way to turn off that dialog in IE except by using a cert >from a recognized CA, which usually costs money. Using a self-signed >cert gives you a private communications channel (unless the DNS is >hijacked by an active attacker) even though it doesn't provide >authentication. Lots of people use self-signed certs instead of >paying for commercial certs. Well, connectiva doesn't use https for their home page ;-) http://www.conectiva.com.br/ But apparently all access to the moin.connectiva.com.br domain is intercepted. If the whole thing is a wiki, I can see the reason to track updaters, but OTOH, if publishing information is the goal, maybe they could provide read-only access via another name, e.g., http://moinro.connectiva.com.br/, if they want to keep things as they are for the original name. Or just show a limited sub-tree of the wiki, which members could avoid if they didn't want their contributions read outside the group. Regards, Bengt Richter From tzot at sil-tec.gr Tue Dec 30 08:39:20 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Dec 2003 15:39:20 +0200 Subject: function-arguments by reference References: <1072788957.24786@news.liwest.at> Message-ID: <79v2vv0ijgdvqu354uh4mh21v4b3liurj0@4ax.com> On Tue, 30 Dec 2003 14:21:46 +0100, rumours say that "EsC" might have written: >Hy! > >is it possible to pass function-arguments by reference? >(for example in PHP you can use the "&" operator ... ) > >thx >iolo > There is no such concept as "pass by value" in python. Only references are passed around, and therefore there is no special syntax for that. What you need to understand is that objects can be mutable (changeable) or immutable. Search for these terms in the python documentation. In other languages, variables are a container: they contain a "value". In python, "variables" are only "names" referring to "objects" and they have no "value". If you assign anything to a name, you just change the object it is pointing to. Presumably you ask this question because you want your function to pass back some more data than its return value. Python handles fine multiple values, check for "tuple" in the docs. An example: (I am not familiar with php, therefore I will write program A in pseudocode, but you will get the point I hope) function f(&a): if (a > 10) then a = 10 return (a*2) var = 20 result = f(var) This function makes sure that the "var" variable stays less than or equal to 10, and then returns the double of the corrected argument. In python you would do this: def f(a): if a > 10: a = 10 return a, a*2 var = 20 var, result = f(var) If not covered, please write back. PS reading this could be helpful too: http://www.effbot.org/zone/python-objects.htm -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From max at cNvOiSsiPoAnMtech.com Mon Dec 15 17:15:44 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Mon, 15 Dec 2003 22:15:44 GMT Subject: python com pre-registration In-Reply-To: References: <_mmDb.422651$pT1.128887@twister.nyc.rr.com> Message-ID: Dave Brueck wrote: >>I have an activex control I want to examine via python before it is >>registered, given only the DLL path.(e.g. I want to get the control's >>GUID for finding (via registry) and uninstalling previous version of the >>control). Can Python help? > > > Yes. Try ctypes and then do in Python the same calls you'd do in C to get the > GUID. > > Thought of that. Was looking for a shortcut ;) (pythoncom.GetFileClass looked promising, but didn't work) From hwlgw at hotmail.com Sat Dec 27 06:22:44 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 27 Dec 2003 03:22:44 -0800 Subject: Project dream References: <3fecb9f1$0$326$e4fe514c@news.xs4all.nl> Message-ID: > [Irmen de Jong] > While not written *in* Python, it's scriptable with Python: > http://www.thangorodrim.net/pangband.html (PAngband). > > waaay back someone even created an Amiga version of this > game based upon Amiga Angband and my AmigaPython port :) You did an AmigaPython port? Fun! How long does something like that take? How long do you think a new roguelike from scratch would take in Python and where the most time is spent? I am afraid of a lot of work on options like magic and +ToHit etc., while I am more interested in a smaller set of options but with a really smart AI. From r.s at XXmindspring.com Sat Dec 6 00:41:16 2003 From: r.s at XXmindspring.com (r.e.s.) Date: Sat, 06 Dec 2003 05:41:16 GMT Subject: min and max id numbers References: Message-ID: <0_dAb.983$_r6.908@newsread1.news.pas.earthlink.net> "Terry Reedy" wrote ... > "r.e.s." wrote ... > > On a given machine, is it possible to create objects LO and HI, > > such that for all objects x, id(LO) <= id(x) <= id(HI) ? > > You have no control over the id of PyObjects. > id's are mostly for internal use of the interpreter. Still, if it were a game played on one machine, surely some of the experts around here could come pretty close to finding a LO and a HI object. No? From oren-py-l at hishome.net Wed Dec 17 20:54:30 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 17 Dec 2003 20:54:30 -0500 Subject: Python as a numerical prototyping language. In-Reply-To: <200312171141.16254.m.dufour@student.tudelft.nl> References: <20031217095358.GA34626@hishome.net> <200312171141.16254.m.dufour@student.tudelft.nl> Message-ID: <20031218015430.GA42162@hishome.net> On Wed, Dec 17, 2003 at 11:41:16AM +0100, Mark Dufour wrote: > > When operations are done on individual objects Python is significantly > > slower than compiled languages but psyco is making great progress in this > > area. It already approaches the performance of C for simple code using > > only integers and floats. > > What are the opinions about Psyco being able to achieve the same great > speedups for non-simple code at some point in the future? Is the looking up > of methods/attributes during run-time the biggest problem here? Object semantics are indeed the issue. I think that there are tricks that could bring it very close to the performance of statically typed languages, though. Something like caching of object attribute accessors using hash tables indexed by the object type and the interned method name, possibly combined with some dynamically generated code. > I would assume that with ever-increasing computer speeds there's no > theoretical limit to what might be possible here.. exciting stuff, this! Improvement in computer speeds will do nothing to the performance gap between Python and a compiled language running on the same computer. It could make them irrelevant because both are fast enough. This is already true for Python on modern processors for all but a handful of compute- intensive applications - the original subject of this thread. Oren From aleax at aleax.it Thu Dec 25 11:50:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Dec 2003 16:50:49 GMT Subject: Operator overloading and __getattr__ References: Message-ID: John Roth wrote: > "Samuel Kleiner" wrote in message > news:slrnbue5dp.72h.sam at h41n2fls31o839.telia.com... >> I'm trying to create methods on method access- but __getattr__ fails >> with operator overloading(below) Any suggestions? EG: > > I haven't a clue what you're trying to do, but > I believe it's not possible to install "magic methods" > after the class is defined. Nor can you install > them in the instance. They'll look like they've It's true that (with newtype classes) special methods can't be usefully "installed in the instance", but it's not true that they can't usefully be "installed after the class is defined" (as long as they ARE installed in the _class_, not in the _instance_). For example: >>> class X(object): pass ... >>> x = X() >>> print x <__main__.X object at 0x402dea8c> >>> x.__str__ = lambda: "I am an X" >>> >>> print x <__main__.X object at 0x402dea8c> >>> X.__str__ = lambda self: "I am an X" >>> print x I am an X >>> Here we see that the first attempt, "installing in the instance" in your terminology, was inoperative; but the second one, "installing in the class" even though well after the class was defined was perfectly operative (on existing instances of the class, too -- of course it also works just fine on any further new instance you may create thereafter). > been installed, but the interpreter will never > execute them because it does not look there > for them. It looks in special places in the C > language structure for the class definition. Yes, but the C code does go to the trouble of updating those special places when you change the _class_ (NOT when you change the instance). If you want to add what amounts to a "per-instance special method" you have, in practice, to make the instance's class unique. There are several ways to do that, including on-the-fly and (better if you do know all instances of a certain class will need such treatment) in a __new__ method on the common baseclass. I'm not sure what, exactly, the OP was trying to do in his example code, but perhaps it can be accomplished by the "give each instance a unique class" (and change that class, when you want to "install special methods") approach. Alex From borcis at users.ch Mon Dec 22 09:46:16 2003 From: borcis at users.ch (Borcis) Date: Mon, 22 Dec 2003 15:46:16 +0100 Subject: Python, Jython, Pypy, etc - and python standard lexemes Message-ID: <3FE703B8.2030108@users.ch> Suppose you want to hook a CPython process and a JPython process together, while minimizing "C2J" impedance. Do we have better than exec statements and eval functions ? Would it not be in the style of py, having failed after years to give life to py's own version of s-expressions, by way of ast modules and such, to devise a lexical format, made to save communicating py processes, better than 50% over transmitting py source ? Will there come an age of "meta-lexical" py ? Should the standard py examples show the unicode machinery put to servicing pure meta-lexical py tasks ? From FBatista at uniFON.com.ar Fri Dec 26 16:30:00 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 26 Dec 2003 18:30:00 -0300 Subject: Help ! newbie problem Message-ID: ferdydurke wrote: #- I am trying to learn python... I can't explain the #- difference beetween these #- two programms, Fibonacci suites : #- #- #- >>> a,b,c = 1,1,1 #- >>> while c<12: #- ... print b, #- ... a,b,c = b,a+b,c+1 #- ... #- 1 2 3 5 8 13 21 34 55 89 144 #- #- and #- #- >>> a,b,c = 1,1,1 #- >>> while c<12: #- ... print b, #- ... a=b #- ... b=a+b #- ... c=c+1 #- ... #- 1 2 4 8 16 32 64 128 256 512 1024 In the first case, the operations at the right side of the "=" are done before rebinding ("changing the value") of the objects at the left of the "=". In the second case, when you do "b=a+b", it's not the original "a", because you already done "a=b". See: >>> a,b,c = 1,1,1 >>> while c<4: print b a,b,c = b,a+b,c+1 print id(a), id(b), id(c) 1 7677952 7676944 7676944 2 7676944 7684064 7684064 3 7684064 7682048 7683056 >>> a,b,c = 1,1,1 >>> while c<4: print b a = b b = a+b c = c+1 print id(a), id(b), id(c) 1 7677952 7676944 7676944 2 7676944 7683056 7684064 4 7683056 7687152 7683056 >>> id(1) 7677952 >>> id(2) 7676944 >>> id(3) 7684064 >>> id(4) 7683056 . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cpl.19.ghum at spamgourmet.com Sun Dec 28 09:48:43 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 28 Dec 2003 15:48:43 +0100 Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: Pjer, I use Python for sth like that. >GUI, printing, registry, RTF For GUI and Printing I use wxpython for registry-work I use win32all rtf is not standardized in any way. It is documented. But you should not expect the dominating word processor to adhere to this documentation. But ... it's only text, so it's possible to deal with it. >installation, Installation: I just create an exe with py2exe and copy the contents of the distribution directory. To do this in a "Microsoft conformant way" there is a great bunch of installers availible; some even generate .MSI foramt. McMillanInstaller provides sth. quite similiar. From imbosol at aerojockey.invalid Mon Dec 15 00:43:17 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Mon, 15 Dec 2003 05:43:17 GMT Subject: Simple question from Python Newbie References: <83eqtvgdadtv80564iiv8t83ubqts4fh7e@4ax.com> Message-ID: Tim Roberts wrote: > "Phil D." wrote: >> >>Hello Python Hackers! >> >>I just started working with Python a few days ago and have a simple >>question that I can't seem to figure out. I am trying to build an >>application to monitor my mouse moving habits while I'm surfing >>the web for a project at MIT and I can't seem to figure out how >>to capture mouse clicks. > > Actually, this is not a particularly simple question. The issue is that it > isn't related to Python at all: this is an operating system issue. An > application is expected to be interested only the events that relate > directly to that application. Doing so on a system wide basis is usually > only interesting for toy apps, such as the one you want to build. > > Fortunately, Windows provides a way to do that: it's called a "hook". In > this case, what you want is the "journal record hook" (WH_JOURNALRECORD), > which gets all key and mouse events in the system. This requires a > callback, which means it needs C help. I don't know if it is implemented > in any of the Win32 extensions; I will have to investigate that (and hope > someone like Mark Hammond posts the canned answer). In Linux, you can open the mouse device file and read to your heart's content. (Or you can configure GPM to open a mouse repeater device, and read from that.) It'll probably need some ioctl calls, but nothing Python can't do wihtout help from C. Figuring out how to read from the device and process the mouse protocol is left as an exercise. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From bkc at Murkworks.com Fri Dec 5 11:23:36 2003 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 5 Dec 2003 11:23:36 -0500 Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: "Rene Olsthoorn" wrote in message news:3fcf581e$0$200$e4fe514c at news.xs4all.nl... > Dear readers, > > py2exe has a problem including libxml2. Not at building time, but at > runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has > the problem? (and can you drop me your setup.py scipt, please). > Perhaps you hit the same problem I did when using libxml2 and libxslt in a service created by p2exe. Here are notes from my project diary (these notes are meant for my client to reconcile my bill vs. what I did) ----- The service builds, I can install it, but get an error when I run it: The instance's SvcRun() method failed File "win32serviceutil.pyo", line 663, in SvcRun File "UMXWIN32SVC.pyo", line 41, in SvcDoRun File "Rose\WebServer\UMXMServer.pyo", line 53, in ? File "Rose\WebServer\umx_handler.pyo", line 16, in ? File "Rose\WebServer\HTTPHandler.pyo", line 95, in ? File "Rose\WebServer\XMLProcessor.pyo", line 34, in ? exceptions.ImportError: dynamic module does not define init function (initlibxslt) This says that the service cannot import the libxslt module for some reason. I built a test script that py2exe runs in console mode, it also fails in the same way. I think libxml is using some kind of dynamic import mechanism, we need to work around. Aha, figured it out. example problem with libxml2. libxml2.py is a module that imports libxml2mod.pyd which imports libxml2.dll But, py2exe creates a default path like this: c:\\temp\\rose, c:\\temp\\rose\\library.zip This means that python tries to import from the directory first, before importing from library.zip. So, python imports libxml2.dll, not libxml2.py My workaround is to reverse the order of the imports in the startup script: zipfile = sys.path[-1] sys.path.insert(0,zipfile) From tjreedy at udel.edu Mon Dec 8 12:13:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Dec 2003 12:13:16 -0500 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: <4redncaHtOe2LEmiRVn-ig@comcast.com> "Duncan Booth" wrote in message news:Xns944B682EF5078duncanrcpcouk at 127.0.0.1... > > The question is whether a Python implementation for .NET would be CLS > > compliant (CLS == Common Language Specification). The existing > > implementation has shown that this is not possible without giving up > > parts of the Python semantics. > > > The main problem is that functions are first class objects in Python, but > not in the CLS. Thank you for this and the persuant explanation. I had been wondering whether a .NET subset would be sensible. Hah! The design principle of 'everything, including funtions, is a (first-class) object' is part of the beauty and ease-of-use of Python. Demotion of functions would point toward 'calculator Python'. > The CLS uses delegates to refer to functions, and a > delegate encapsulates both an object and a pointer to a method. ... > I have been playing around with a variant on the managed Python compiler, > and I think I have figured a way to implement Python which might just get > around this bottleneck. Good luck. Not directly useful to me, but success can only promote the usage of Python. Terry J. Reedy From joconnor at cybermesa.com Wed Dec 3 10:08:24 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Wed, 03 Dec 2003 08:08:24 -0700 Subject: Separation of content and code for web (was Re: Python for web?) In-Reply-To: <73c38014.0312030233.1c051da5@posting.google.com> References: <3FCB8535.F8F89132@engcorp.com> <3FCC9A98.193ED480@engcorp.com> <73c38014.0312030233.1c051da5@posting.google.com> Message-ID: has wrote: >Peter Hansen wrote in message news:<3FCC9A98.193ED480 at engcorp.com>... > > > >>Apparently all you PyMeld types like to lie in wait and then reply in >>groups. ;-) >> >>Thanks Richie! (and Paul and Hamish, for the same answer) This looks >>promising. >> >> > > > Au-contraire: I was shamelessly whoring my own solution, >HTMLTemplate.:) > Frell..I have a class I developed that I use regularly called "HTMLTemplate". I should probably change the name... From skip at pobox.com Sat Dec 6 15:13:08 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 6 Dec 2003 14:13:08 -0600 Subject: Creating a List of Empty Lists In-Reply-To: References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> <30oAb.9577$aw2.4588872@newssrv26.news.prodigy.com> Message-ID: <16338.14420.345478.623421@montanaro.dyndns.org> Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 >>> b = intern('foo bar') >>> a = 'foo bar' >>> a is 'foo bar' False >>> b is 'foo bar' False Emile> That apparent space requirement should really be better documented. The fact that the current implementation of CPython automatically interns strings which look like identifiers is simply an efficiency consideration. It's not part of the language definition, so doesn't bear documenting. The correct way to compare two strings is using '==' (which is independent of CPython's implementation details), not 'is'. Skip From skip at pobox.com Thu Dec 18 14:12:50 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 13:12:50 -0600 Subject: Broken python-model.el In-Reply-To: References: Message-ID: <16353.64562.92991.726030@montanaro.dyndns.org> Brian> I just compiled Python 2.3.2 on my local machine as an upgrade Brian> from 2.2. This appears to have broken my python-mode.el in Brian> emacs. When I try to "Execute Buffer" Ctl-c Ctl-c I get: Brian> Wrong type argument: sequencep, cpython What version of python-mode and Emacs are you using? What is the value of py-default-interpreter? I just tried C-c C-c in a Python buffer with version 4.40 and XEmacs 21.5beta9 and it worked fine for me. Skip From bokr at oz.net Mon Dec 29 04:00:36 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Dec 2003 09:00:36 GMT Subject: why does py_compile.compile() miss some errors in sourcefile? References: Message-ID: On 28 Dec 2003 23:16:18 -0800, fBechmann at web.de (Frank Bechmann) wrote: >where can I find some documentation, which errors will be found by >'py_compile.compile' and which will not be found. > ># t1.py ># ===== > >import os.path >import py_compile > >py_compile.compile(os.path.join(os.path.dirname(__file__), "t2.py"), > doraise=True) > > ># t2.py ># ===== ># following line is found as an error: ># Class C: # <== 'SyntaxError: invalid syntax' > >class C: > pass > >c = CC() # <== not found as an error from py_compile > # but found as an error from python-executable: > # 'NameError: name 'CC' is not defined' > The difference is between compiling and executing. Syntax errors are found during complilation and run-time errors during execution ;-) py_compile apparently does not execute the code it compiles. c = CC() compiles ok. It just says, look up CC in the directory associated with the code excution, call it, and bind the result to c. There is no error until you try to execute it, and actually try to look up CC. With py_compile you don't have a reasonable way to interfere before execution, to supply a CC, but if you compile interactively you can, e.g., >>> code = compile('c = CC()','','single') >>> exec code Traceback (most recent call last): File "", line 1, in ? File "", line 1, in ? NameError: name 'CC' is not defined But we could have done this before executing: >>> def CC(): print 'Hello from CC'; return 'CC result' ... >>> exec code Hello from CC >>> c 'CC result' In general, the compiler can't know if you are going to fix things up before execution. If you import or execfile, you will be executing the code (at least on the first import -- if you're not the first, no re-execution). Import will create it's own global name space to execute in (and thus to look for CC in), so CC won't be there, but with execfile you could specify a directory that already has CC defined in it, and it should succeed. E.g., using your t2.py: print it to make sure: >>> print '===< t2.py >===\n%s======'%file('t2.py').read() ===< t2.py >=== # ===== # following line is found as an error: # Class C: # <== 'SyntaxError: invalid syntax' class C: pass c = CC() # <== not found as an error from py_compile # but found as an error from python-executable: # 'NameError: name 'CC' is not defined' ====== We set up a directory >>> d = {} define a funtion >>> def foo(): print 'This is foo, bound to CC in dict d'; return 'foo/CC result' ... bind it to CC in the directory, which will be the global name space for the execution >>> d['CC']=foo check on it >>> d {'CC': } execute t2.py in it >>> execfile('t2.py', d) This is foo, bound to CC in dict d we note the side effect printed and check on d again (just the names, I know what's coming ;-) >>> d.keys() ['CC', '__builtins__', 'C', 'c'] The __builtins__ key is put there as a side effect of execfile. we can check on that "c = CC()" assignment result: >>> d['c'] 'foo/CC result' HTH Regards, Bengt Richter From duncan at NOSPAMrcp.co.uk Tue Dec 2 04:12:42 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 2 Dec 2003 09:12:42 +0000 (UTC) Subject: split on blank lines References: <807692de.0312010610.4461c0e3@posting.google.com> Message-ID: Hans Nowak wrote in news:mailman.12.1070300390.16879.python-list at python.org: > Duncan Booth wrote: > >> Given that re.compile("^$", >> re.MULTILINE).findall("foo\n\nbar\n\nbaz") returns ['', ''] I would >> agree this looks like a bug. You could submit a bug report on >> Sourceforge. > > I may be wrong, but I would think that the behavior is correct. "^$" > matches an empty line. This is exactly what findall returns... two > empty lines. > Perhaps you trimmed too much of the original context, but you have misunderstood the original poster's intent. The original post said: > can somebody tell me why (using Python 2.3.2) > >>>> import re >>>> re.compile(r"^$", re.MULTILINE).split("foo\n\nbar\n\nbaz") > ['foo\n\nbar\n\nbaz'] Notice that the string they are splitting contains two empty lines. I pointed out that re.findall correctly spots the two empty lines, and therefore you would expect that the split should correctly split the string there, but it doesn't. For the avoidance of doubt: there is an inconsistency of behaviour between re.findall and re.split. It looks to me like a bug in the str.split method. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From reply.in.the.newsgroup at my.address.is.invalid Thu Dec 25 10:29:06 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 25 Dec 2003 16:29:06 +0100 Subject: dynamic typing questions References: <20031219150339.63883.qmail@web60401.mail.yahoo.com> Message-ID: <0g0muv43b199cqml09li7nsn12fl93bpjp@4ax.com> Mark Dufour: >> dynamic typing >There is a nice article about this topic by Bruce Eckel >http://www.mindview.net/WebLog/log-0025 That's a good read, thanks for the link. -- Ren? Pijlman From martin at v.loewis.de Mon Dec 1 14:17:03 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Dec 2003 20:17:03 +0100 Subject: segfault in extension module References: Message-ID: Nathaniel Echols writes: > Okay: > > #0 0x420744fe in _int_free () from /lib/tls/libc.so.6 > #1 0x420734d6 in free () from /lib/tls/libc.so.6 > #2 0x0809dc0d in _PyObject_GC_Del () > #3 0x080ce86f in PyDict_Next () > #4 0x080d191d in _PyModule_Clear () > > I guess this makes sense, but I'm still not sure how to fix it. . . Ah, tls/libc.so.6. I think you lose, being confronted with a buggy C library. Try making it not use /lib/tls. If that does not change the behaviour, you probably have a ref-counting bug somewhere. Try building a debugging version of Python. Regards, Martin From kamuelaf at verizon.net Thu Dec 25 19:17:05 2003 From: kamuelaf at verizon.net (trainee) Date: Fri, 26 Dec 2003 00:17:05 GMT Subject: Socket Programming References: Message-ID: <56LGb.5852$UB3.4119@nwrddc03.gnilink.net> Thanks, everyone. Michael: I am really just fooling around for the moment. Are you telling me that there are modules for specific things like IRC? From toph at laposte.net Wed Dec 3 03:59:58 2003 From: toph at laposte.net (Toph) Date: Wed, 3 Dec 2003 09:59:58 +0100 Subject: [ python-l ] scrolling a frame Message-ID: Hi, I am developing a software in Python using Tkinter. The choice of my team is not to use pyton MegaWidgets. I would like to scroll a frame. This is a peace of my code : # ----------------------------------------------------------------------------- #!/bin/env python from Tkinter import * root = Tk() global_frame = Frame(root, relief = GROOVE, borderwidth=4) canvas = Canvas(global_frame) # scrollbars: vscroll = Scrollbar(global_frame, command=canvas.yview) hscroll = Scrollbar(global_frame, command=canvas.xview, orient=HORIZONTAL) # The frame i want to scroll : frame = Frame(canvas, relief = GROOVE, borderwidth=2) cw = canvas.create_window(0,0, window = frame) global_frame.grid(row = 0, column = 0, sticky=NS) #put the widgets in global_frame canvas.grid(row = 0, column = 0) vscroll.grid(row = 0, column = 1, sticky=NS) hscroll.grid(row = 1, column = 0, sticky=EW) # fill the frame : for item in range(30): Label(frame, text = 'item %d'%item).grid(row = item, column = 0) Entry(frame, text = 'default text %d'%item).grid(row = item, column = 1, sticky=EW) # configure the scollbars to scroll the canvas : hauteur = frame.winfo_height() largeur = frame.winfo_width() canvas.configure(yscrollcommand = vscroll.set, xscrollcommand = hscroll.set, scrollregion = (0,0, largeur, hauteur)) #canvas.coords(cw)) # My problem is that i would like the scrollregion to scroll only the space taken by # the frame but my program does not do it well... root.mainloop() #------------------------------------------------------------------------------ I thank you in advance. Christophe Acc?dez au courrier ?lectronique de La Poste : www.laposte.net ; 3615 LAPOSTENET (0,34?/mn) ; t?l : 08 92 68 13 50 (0,34?/mn) -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsgroups at jhrothjr.com Sun Dec 21 07:55:52 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 07:55:52 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: <279b566d.0312201935.38fb2156@posting.google.com> Message-ID: "Skip Montanaro" wrote in message news:mailman.393.1071981117.9307.python-list at python.org... > > > HV> I think no one even tries to understand the very concept of reducing > HV> sequence to a single object using a rule . Sum is not a replacement > HV> of this *concept*. Just what is so wrong with having such a general > HV> tool available in a programming language ? Doesn't it hurt to > HV> understand how to use it? > > It doesn't hurt to understand the concept of reduce(), but if it's never (or > very rarely) used, it's just extra (nearly dead) code which has to be > maintained. It's easy enough to write reduce() in Python, and if/when PyPy > is a reality shouldn't be any less efficient than the current C version. I'd have to agree that reduce, per se, isn't the world's most useful function, and getting rid of marginally useful C code that has to be maintained is a worthwhile objective. It finally dawned on me last night that I could use the visitor pattern for all cases of reduce, in a form that's probably more understandable for the average programmer. And if it isn't, then he's learned something more globally useful: the visitor pattern. That being the case, I'm going to withdraw whatever objections I had to removing it from the language. John Roth > > Skip > From kamuelaf at verizon.net Thu Dec 25 19:17:54 2003 From: kamuelaf at verizon.net (trainee) Date: Fri, 26 Dec 2003 00:17:54 GMT Subject: Socket Programming References: Message-ID: Do you think you could recommend a book on Python that includes sockets? From graham__fawcett at hotmail.com Wed Dec 17 09:28:57 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 17 Dec 2003 06:28:57 -0800 Subject: Zen of ... References: <3fdf6d4a$0$17132$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote in message news:<3fdf6d4a$0$17132$626a54ce at news.free.fr>... > Gerrit Holl wrote: > > Hi, > > > > shouldn't the Zen of Python really be called the Zen of Programming? > > > I dont know, but since we've already have a Tao of Programming[1], what > is the Tao of Python ?-) Don't bother asking: "The Tao of Python that can be posted on Usenet is not the true Tao." -- Lao Tse ;-) -- G From skip at pobox.com Mon Dec 15 19:57:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Dec 2003 18:57:11 -0600 Subject: Terminal "hang up" problem In-Reply-To: References: <9eabe547.0311131610.4dd7819c@posting.google.com> Message-ID: <16350.22631.709284.198831@montanaro.dyndns.org> JD> What is the best way to debug a Python program if when i run it, it JD> totally hangs up the terminal console. JD> Control-c or control-d has NO effect, so it's hung up somewhere, but JD> we have no idea where. Does it use X? If so, try setting your DISPLAY to another box. (Maybe it's hanging the X server.) If not, try ssh'ing into the box from another machine. Can you run top in another window while it runs? Perhaps it's chewing up gobs of memory (got any monster range() calls in there)? If you give us some more details about how you think it's supposed to interact with the system we might be able to provide some more debugging clues. Skip From tim.one at comcast.net Sat Dec 27 13:50:44 2003 From: tim.one at comcast.net (Tim Peters) Date: Sat, 27 Dec 2003 13:50:44 -0500 Subject: Some optimization tale In-Reply-To: Message-ID: [Stephan Diehl] > ... > Michael Dyck then pointed out that instead of using 'sort', 'min' and > 'max' should be used. While tests suggest that this is true, I have > no idea why that should be, since finding a minimum or maximum uses > some sorting anyway (if we don't have some quantum computer at our > hands), so, my reasoning would be that sorting once should be faster > than computing both, maximum and minimum. Finding a minimal element in a list of length N requires at least N-1 comparisons (you simply can't know its "the smallest" unless it's compared at least once against each of the N-1 other elements), and can also be done using no more than N-1 comparisons. This is really just the obvious way: def min(sequence): smallest_so_far = sequence[0] for candidate in sequence[1:]: if candidate < smallest_so_far: smallest_so_far = candidate return smallest_so_far Finding a maximal element also requires exactly N-1 comparisons. Finding a min and a max in separate steps then requires exactly 2*(N-1) comparisons, or roughly 2*N. If you can look for a min and a max in the same step, it's possible to reduce that. For example, once things get started, take sequence elements two at a time. Compare them to each other, then compare the smaller only to the smallest so far, and the larger only to the largest so far. This requires 3 compares overall per pair of input elements, so takes about 1.5*N total compares to find a min and a max. Sorting (with a theoretically best-possible comparison-based algorithm) requires an average of log_base_2(N!) comparisons, across randomly ordered sequences of length N. That's (very) roughly N * log_base_2(N) comparisons. log_base_2(N) is bigger than 2 most of the time , and that's why doing min() and max() can beat the pants off of sorting. From yan at NsOeSiPnAeMr.com Sat Dec 6 07:42:44 2003 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Sat, 06 Dec 2003 07:42:44 -0500 Subject: newbie list question In-Reply-To: <7xsmjyi25f.fsf@ruckus.brouhaha.com> References: <7xsmjyi25f.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Kamus of Kadizhar writes: > >>I want to remove those elements that are in the sub-lists of fav that >>also appear in the corresponding sub-list of oldfav: >> >>I can hack this up using C-style indexes, but I have to imagine there >>is some neat python way that eliminates indexes altogether. > > > Does this work? > > difffav = [[f for f in new if f not in old] for new,old in zip(fav,oldfav)] Yes it does. But I have no idea how. :-( I think it's going to take me a while to figure out what the above does.... :-) Where do I find that in the FM? -Kamus -- What am I on? I'm on my bike, o__ 6 hours a day, busting my ass. ,>/'_ What are you on? --Lance Armstrong (_)\(_) From duncan at NOSPAMrcp.co.uk Mon Dec 8 04:47:20 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 8 Dec 2003 09:47:20 +0000 (UTC) Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: Robin Becker wrote in news:SWfFiLAYAi0$EwHZ at jessikat.fsnet.co.uk: > In article , Duncan Booth > writes > ...... >> >>The recommended way these days is usually: >> >> a = [ [] for i in range(10) ] >> >>That still has a loop and works by appending empty lists, but at least >>its just a single expression. Also you can incorporate the next stage >>of your initialisation quite easily: >> >> a = [ [b] for b in range(10) ] >> > I seem to remember the fastest way to do this was map(list,n*[[]]) > from a couple of earlier threads, but is that true in 2.3? I think I would prefer to maintain code with the list comprehension rather than the map which, to my eyes, isn't immediately obvious. However, it would appear that the list comprehension is much faster in any case, so in this case I believe the clearest solution is also the fastest. C:\>d:\python23\lib\timeit.py "[ [] for i in range(10) ]" 10000 loops, best of 3: 28.6 usec per loop C:\>d:\python23\lib\timeit.py "map(list,10*[[]])" 10000 loops, best of 3: 102 usec per loop C:\>d:\python23\lib\timeit.py -s ll=list -s mm=map "mm(ll,10*[[]])" 10000 loops, best of 3: 91.9 usec per loop -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From skip at pobox.com Thu Dec 18 16:18:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 15:18:01 -0600 Subject: Broken python-model.el In-Reply-To: <274A369893F5FB4099345F006439D987013876E0@bella.corp.resmed.org> References: <274A369893F5FB4099345F006439D987013876E0@bella.corp.resmed.org> Message-ID: <16354.6537.640394.55297@montanaro.dyndns.org> Peter> Still shows as 4.40 - I'll give it another go in about an hour or Peter> so, there must be a delay between you checking in and what I can Peter> see here. Attached is a context diff between 4.40 and 4.41. Skip -------------- next part -------------- A non-text attachment was scrubbed... Name: py-mode.diff Type: application/octet-stream Size: 1369 bytes Desc: not available URL: From mwh at python.net Thu Dec 4 07:17:16 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Dec 2003 12:17:16 GMT Subject: comparing nan "number" References: <87vfp01muq.fsf@pobox.com> <87znebe6ux.fsf@pobox.com> <87ptf5lqc1.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Michael Hudson writes: > > > jjl at pobox.com (John J. Lee) writes: > > > > > Alexander Schmolck writes: > > > [...] > > > > possibly be `False` and {x:"some value}[x] might well raise an exception if > > > > `x` is a nan (or indeed one of infinitely many Numeric arrays with > > > [...] > > > > > > Don't you mean SomeMapping((x, "some value"))[x]? A dict lookup > > > doesn't use __eq__. > > > > Huh? Yes it does (*after* __hash__, of course, but...). > > Oh, collisions, right? Yes. You can't know a collision has (or has not) happened until after you've tried __eq__... Cheers, mwh -- ARTHUR: Why should a rock hum? FORD: Maybe it feels good about being a rock. -- The Hitch-Hikers Guide to the Galaxy, Episode 8 From peter at engcorp.com Thu Dec 11 14:10:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Dec 2003 14:10:55 -0500 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <3fd8b79f$0$565$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <3FD8C13F.6BC2B2DD@engcorp.com> Brian Kelley wrote: > > I hate wxPython's text widget for most of the reasons you described. > Plus, since we are using python, why isn't there a .write(...) method > for these widgets? Why can't I use a text widget like: > > sys.stdout = TextCtrl(parent) > > I had to make a wrapper around the text widget to make it behave like a > StringIO() class. It internally did all the necessary conversions to > the strings, but now I can use ... Probably the reason the text widget doesn't already do those things is that nobody has taken the time to make it happen *and* release the changes back to the project. Is Robin Dunn supposed to think of and write all these things himself, just for your benefit? -Peter From http Mon Dec 15 21:48:51 2003 From: http (Paul Rubin) Date: 15 Dec 2003 18:48:51 -0800 Subject: 'piping' output References: <3fde6b27$1@clarion.carno.net.au> Message-ID: <7xzndtscj0.fsf@ruckus.brouhaha.com> Steve writes: > I want to know if I can 'pipe' output from a program into a python > script. Is that possible? I need to pipe some output at runtime from a > program written in C and I want to parse it/use it in a python > script. I'm new so please bear with me. thanks Use the C library "popen" function. From alanmk at hotmail.com Fri Dec 5 12:11:45 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 05 Dec 2003 17:11:45 +0000 Subject: Turning f(callback) into a generator References: Message-ID: <3FD0BC51.597C3E95@hotmail.com> [Peter Otten] > So far, no one has come up with a solution that avoids threads - short of > Bengt Richter's ideas on changing the language that is. Sorry I'm late into this thread. Peter, you may find the following message from Stephen Taschuk interesting. It is an approach to the producer/consumer problem, through the use of coroutines. Only the bottom half of his post will be of interest. The top half relates to another question I was asking him at the time. http://groups.google.com/groups?selm=mailman.1054317657.5272.python-list%40python.org&rnum=8 I think it might be something closer to what you're looking for. regards, -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From __peter__ at web.de Thu Dec 4 04:51:07 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Dec 2003 10:51:07 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Diez B. Roggisch wrote: >> This is a strange asymmetry, and I was wondering if I've overlooked a >> simple way to transform a callback into a generator, but I now tend to >> the assumption that you *need* threads: One thread with the callback puts >> names or name lists into the queue until it's full (some arbitrary limit >> that also determines the total memory needed), another thread (the >> generator) consumes names from the queue. > > I also thought about that - its the only thing that allows for real > lazyness - you can wait in the callback until the generator clears a > semaphore. But if the context-changes are worth the effort is > questionable. There is another aspect I forgot to mention. Your approach would only start to yield results after all results are found, i. e. in the example you would have to scan the whole harddisk even when the first visited file might have been the one you want. So I think it is best to either not change the callback approach or use threads as outlined by Jimmy Retzlaff. Peter From matthew.garrish at sympatico.ca Sun Dec 21 11:27:28 2003 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Sun, 21 Dec 2003 11:27:28 -0500 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <7fe97cc4.0312210106.5a72c199@posting.google.com> Message-ID: "Xah Lee" wrote in message news:7fe97cc4.0312210106.5a72c199 at posting.google.com... > > Now there are a slew of perl driviling morons who > has also participated in answering to no avail. Die! > > PS pasted below my sig is some meat about unix. Unix morons please > slurp and spruce it up and place it on wikipedia.org or something. > Since you're obviously in need of an expanded vocabulary, I think you'll find you can use the following to describe yourself nicely: http://en.wikipedia.org/wiki/Script_kiddie Matt From ville.spammehardvainio at spamtut.fi Thu Dec 25 16:52:15 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 25 Dec 2003 23:52:15 +0200 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: Tom Plunket writes: > Brandon, why not heed the advice that one holds back such an > announcement until someone actually has something interesting to > announce? You know how many of these sorts of projects are It's just Usenet - people use the bandwidth for much less interesting stuff anyway. Also, I think mentioning a project one is about to embark on in Usenet is a good idea, for finding the possible prior art or like-minded individuals if nothing else. > Seems like a huge waste of time, starting with the fact that > editing the C codebase to do what you want is likely, at this > point, far easier. Perhaps the eventual results would be less interesting w/ that approach? -- Ville Vainio http://www.students.tut.fi/~vainio24 From hs at bluepacific-technologies.com Mon Dec 15 00:31:00 2003 From: hs at bluepacific-technologies.com (SamX) Date: 14 Dec 2003 21:31:00 -0800 Subject: run Fortran from python Message-ID: <31e18870.0312142131.5cf4d329@posting.google.com> I know Tcl can run Fortran excutables. Can python do the same? Thank you From fredrik at pythonware.com Tue Dec 9 06:50:15 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Dec 2003 12:50:15 +0100 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: Robin Becker wrote: > C:\tmp>\python22\python ttt.py > list () = 3.22 > list [] = 1.33 > lambda z: list(z) = 2.55 > C:\tmp>\python23\python ttt.py > list () = 1.73 > list [] = 3.22 > lambda z: list(z) = 4.77 is this part of the benchmark stable, or was your computer doing something else in the background? I find it a bit disturbing that a 2.3 optimization would slow down a trivial operation that much... From __peter__ at web.de Sat Dec 13 07:15:37 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Dec 2003 13:15:37 +0100 Subject: hex and little endian References: Message-ID: Matteo Memelli wrote: > Hello I'm getting in trouble.... > I'm trying to convert an hex address like 0xbfffe2f1 in little endian > format \xf1\xe2\xff\xbf. Is there any funcion that can make this? > Whe I try to code somethig like this: > "\x%s\x%s\x%s\x%s" % (string1, string2, string3, string4) > I obtain this error: > ValueError: invalid \x escape > > and if I escape the charachter "\" making something like this: > "\\x%s\\x%s\\x%s\\x%s" % (string1, string2, string3, string4) > It works but the resulting string is not an hex representation, I mean: >>>> len('\xaa\xaa\xaa\xaa') > 4 > >>>> len('\\xaa\\xaa\\xaa\\xaa') > 16 > > Can anyone help me? > Thank you very much in advance > > Matte Every replacement of "\xNN" in a string is done by the compiler, so one way would be to feed your string to the compiler via eval(): >>> s = "\\x%s\\x%s" % ("AA", "BB") >>> s '\\xAA\\xBB' >>> eval("'" + s + "'") '\xaa\xbb' >>> However, the cleaner approach is: >>> import struct >>> n = 0x00aa00bb >>> struct.pack("i", n) '\xbb\x00\xaa\x00' >>> struct.pack(">i", n) '\x00\xaa\x00\xbb' >>> struct.pack(">> The > and < flags are used to explicitly specify the byte order. See the documentation http://www.python.org/doc/current/lib/module-struct.html for details. Peter From skip at pobox.com Thu Dec 18 16:42:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Dec 2003 15:42:55 -0600 Subject: Broken python-model.el In-Reply-To: <274A369893F5FB4099345F006439D987013876E1@bella.corp.resmed.org> References: <274A369893F5FB4099345F006439D987013876E1@bella.corp.resmed.org> Message-ID: <16354.8031.748042.727787@montanaro.dyndns.org> Peter> I manually applied the patch to 4.40 - it doesn't seem to be any Peter> different. The "ord" in "swimrecord" (for instance) is still Peter> fontified differently from the rest of the variable name. Did you restart Emacs? Note that the main change is in a (defvar), which won't be reevaluated if all you do is reload python-mode. Skip From matt at killermookie.org Mon Dec 15 21:57:19 2003 From: matt at killermookie.org (Matthew Sims) Date: 15 Dec 2003 18:57:19 -0800 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: <1e963607.0312151857.186adaa8@posting.google.com> "Francis Avila" wrote in message news:... > Matthew Sims wrote in message > <1e963607.0312151408.583221e6 at posting.google.com>... > >Python Newbie here. This is my first time learning object-oriented > >programming and trying to break out of the usual Korn/Perl/PHP style > >of programming. Having some difficulty understand some items. > > > >For lists, I understand this: > >C=["need","some","help"] > >print C[1] > >some > > > >But I can't seem to do this: > >C[3]="here" > > > >I know about C.append("here") but this brings me to my question... > > > >Is there anyway to assign to an element that wasn't defined in the > >beginning? Like if I wanted element 5 assigned but not element 4 > >without using "" or None? > > I assume you tried 'insert'? > >>> C=["need","some","help"] > >>> C.insert(10, 'here') > >>> C > ['need', 'some', 'help', 'here'] > > Ah, well that didn't work. Python has no (builtin) way to do what you want. > The reason isn't technical, but that the list needs *something* in that > intervening space, and Python isn't about to make rash presumptions about > what you want there ("explicit is better than implicit"). In choosing > between two behaviors for inserting to an index beyond the end of a list, > appending was deemed less surprising, less violent, and less likely to > introduce mysterious bugs than filling in the intermediate elements with > who-knows-what. First off...I still have a lot to learn. :) > > I can't even think of why one would want lists to have that sort of > behavior. It seems to me that if we're assigning to arbitrary elements and > we want the list to grow with it, that we should be using a different data > structure, like a dictionary with integer keys. The index of a list > generally has no semantic correlation to the data contained therein--it just > specifies order, and the data doesn't care about its own index. If we want > a semantic correlation, we make that correlation explicit by a dictionary's > key-value pair. > > If you want to do this sort of thing (implicit assignment to intermediate > elements in list insertions), write a function to do it, or subclass list. > You can even modify the slice behavior itself (if you go the subclass > route), so that C[3] will silently act like perl instead of Python, but this > is *quite* unPythonic. (Other Python people reading your code will be > confused.) My guess is that this is what makes OO programming different than modular. > > If this sort of answer surprises you (coming from perl, it might...), do an > "import this" at an interactive prompt and read. :) > The Zen of Python, by Tim Peters...heh > >I'm currently re-writing a Perl script into Python and with Perl I was > >free to assign any element in the array without having to fill in the > >previous elements. I can't seem to do that in Python...unless I'm > >doing it wrong. > > Again, in general, Python has *no* implicit > assignments/declarations/modifications/etc. If you don't *explicitly* ask a > list to fill in its intermediate elements, Python won't do it. This is a > conscious design decision, and a great part of what makes Python Python. > For at least two senses of "great", IMO. > > I could never learn perl (despite many attempts), so I ask, what does perl > do to the intermediate elements? Is a perl array more like a dictionary > with implicit integer keys (so intermediate keys simply don't exist), or > does it fill in the intermediate elements with 0 or something like that? In > what perl idioms is this behavior useful? (I still mean to learn perl one > of these days, for shell scripting.) Here's how the program basically worked. It's for a Tape Library with a robot arm in the middle. There are 40 slots and each is represented as an element in the array. If a tape was in one of the slots, that element # corresponds to the slot # and the tape ID would show in that element. All other elements represented blank slots. This allowed me to control the robot arm to the exact slot a tape resides since all I had to do was look at any elements that had tape IDs assigned. So far the only way I could get this to work in Python was to insert "" to represent an empty slot. But Python counts "" when I want to see how many tapes are currently taking up slots "len(SLOTS)". It would always show 40. So I now know that I need to write code to tell Python not to count "". Not too difficult. I guess I'm realizing how I need to approach Python as my first OO. I'm re-writing the script as sort of a training. The program works flawlessly in Perl, I'm just doing it to learn. So far it has taken less lines of code in Python to perform the same tasks in Perl...up til this point. ;) Anyways, I appreciate the responses. I have a better understand of Python. --Matt From ptmcg at users.sourceforge.net Wed Dec 24 13:08:55 2003 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Wed, 24 Dec 2003 18:08:55 GMT Subject: ANN: pyparsing 1.0.3 - text parsing library module Message-ID: This module has pretty well stabilized. This latest version contains only performance tweaks, plus has a more standard Python distribution (thanks to Dave Kuhlman), including dist archives in both zip and gzip/tar format. Download it from SourceForge at http://sourceforge.net/projects/pyparsing/. I'll also start collecting examples of interesting grammars, if anyone sends them on to me. -- Paul McGuire From gh at ghaering.de Sun Dec 21 07:29:34 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 21 Dec 2003 13:29:34 +0100 Subject: pysql lite transactions question In-Reply-To: <21bb8d55.0312210152.2b1957aa@posting.google.com> References: <21bb8d55.0312210152.2b1957aa@posting.google.com> Message-ID: <3FE5922E.3020203@ghaering.de> Stormbringer wrote: > Hi, > > Could anyone shed some light on transactions using pysqlite when > autocommit is off ? Sure. > I am using Python 2.3 with latest pysqlite and after I do a > m_connection = sqlite.connect(name, autocommit=0) > and > m_cursor = self.m_connection.cursor() > > and then looks like it starts a transaction automaticaly, because if I > issue a > m_cursor.execute('BEGIN TRANSACTION') > it says that nested transactions are not permitted. > > But : if I issue an 'END TRANSACTION' and then a 'BEGIN TRANSACTION' > and do the usual db operations and in the end I do a 'END TRANSACTION' > I get this : If you want to mess with transactions yourself, use autocommit mode. But in normal, transactional mode, please only use .commit() and .rollback() on the connection object. > Exception _sqlite.DatabaseError: 'cannot rollback - no transaction is > active' in instance at 0x0086D288>> ignored I myself would prefer an ElectrificationException instead. Maybe that would reduce such perverted usage :-> > [...] My reasons of trying to use transactions is that it seems to make > sense in what I do, i.e. I try to populate a database and if I get an > error halfway I want to cancel the whole chain of operations. Plus I > noticed the speed is much greater if I put autocommit to off. > > Any ideas ? Yes. DON'T MESS WITH TRANSACTIONS MANUALLY!!! Cough. It's absolutely not needed in 99.99999999 % of all cases. Yet people still think they're smarter than the designers of the DB-API and me ;-) Here's a simple way to achieve what you want: cx = sqlite.connect(...) cu = cx.cursor() try: # Do your INSERTs here cx.commit() except DatabaseError: cx.rollback() Seeing this misuse of transactional commands in .execute() I'll change PySQLite to throw ProgrammingError when they're used in non-autocommit mode. -- Gerhard From http Sat Dec 13 16:22:52 2003 From: http (Paul Rubin) Date: 13 Dec 2003 13:22:52 -0800 Subject: Examples and Tutorials of SocketServer? References: <826b6ec2.0312131313.10769cda@posting.google.com> Message-ID: <7xiskkjtub.fsf@ruckus.brouhaha.com> piffenpauffer at yahoo.com (Milo K. Piffenpauffer) writes: > I've looked on Google for examples of using the SocketServer module, > but I'm not having much luck. The online documentation is pretty > sparse, and PyDoc isn't very clear. Does anyone know where I could > find an example of SocketServer that explains what the various > features of the code do? "Use the source, Luke". I remember having the same problem and finding some better docs around somewhere though. From davidcfox at post.harvard.edu Mon Dec 29 11:35:14 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Mon, 29 Dec 2003 16:35:14 GMT Subject: Special-purpose extension of Python -- new kinds of objects In-Reply-To: <6714766d.0312290821.86b2f64@posting.google.com> References: <6714766d.0312281442.78cd0a4b@posting.google.com> <7xwu8g7eao.fsf@ruckus.brouhaha.com> <6714766d.0312290821.86b2f64@posting.google.com> Message-ID: <6JYHb.688201$Tr4.1718696@attbi_s03> Robert Dodier wrote: > Paul Rubin wrote: > > >>robert_dodier at yahoo.com (Robert Dodier) writes: >> >>> # "dn" == "decision network", an Ephemeral construct; >>> # this part is parsed separately from the python code >>> dn my_example: >>> chance X: >>> cpd: gaussian [mean: 25, std_dev: 75] >>> chance Y: >>> cpd: gaussian [mean: 12, std_dev: 19] >>> chance Z = X + Y >> >>I don't see what good this does. You can do the same thing with >>ordinary Python classes. > > > Thanks for your interest. I want to make it possible to experiment > with notations that don't correspond to Python syntax. For example, > to write "X ~ gaussian(mu,sigma2)", or to write "Y <- (X1, X2, X3)", > say. > > The larger goal is to make the decision model description as > natural as possible for people that work on decision problems. > Development effort should focus on the decision model, which, > in interesting problems, may be much larger and more complex > than the ordinary Python glue code around it. Personally, I would first write all of the code for performing calculations in pure Python, using the usual OO notation. Then you can always add a parser which translates the mathematical syntax into OO. David From PeterM at resmed.com.au Thu Dec 18 15:38:07 2003 From: PeterM at resmed.com.au (Peter Milliken) Date: Fri, 19 Dec 2003 07:38:07 +1100 Subject: Broken python-model.el Message-ID: <274A369893F5FB4099345F006439D987013876D8@bella.corp.resmed.org> G'Day Skip, Sorry mate, I haven't been following the progress of python-mode.el at sourceforge. I have been using 4.6 (warts and all) and just followed up John Lee's reference. So I don't even know what the "trailing builtin" problem is :-) All I know is that I don't like the way python-mode.el (currently) tries to find shadowed builtins. I would hardly call highlighting the "ord" in "swimrecord" as showing a shadowed builtin :-) I found the current mechanism highly annoying to be honest as it distracts rather than enhances. Good luck with your efforts though and I'll certainly keep an eye on the progress there at sourceforge now that I know about it. Peter -----Original Message----- From: Skip Montanaro [mailto:skip at pobox.com] Sent: Friday, December 19, 2003 7:01 AM To: Peter Milliken Cc: python-list at python.org Subject: Re: Broken python-model.el Peter> Initial impressions is that I will re-download the 4.6 version Peter> available from the python web-site. One of the annoying things Peter> that hits you right in the face (and this is terribly unfair to Peter> the sourceforge team working on it! - it hasn't been released Peter> after all :-)) is the "blind" fontification of what are believed Peter> to be Python keywords by the authors. Peter> This list includes words such as "Exception", "ord", "self" plus Peter> a host of others. So variables that I have such as "swimrecord" Peter> has the "ord" portion font coloured differently from the rest of Peter> the string, "ChildException" has the "Exception" differently Peter> coloured than the "Child" portion, "self" is a different colour Peter> from the rest of the variable usage i.e. self.Name has "self" and Peter> "Name" colourised differently - extremely annoying and *not* what Peter> I expect the authors want to achieve! Certainly not what I want Peter> in an edit session! :-) That's a feature I added recently. It's intended to highlight variables which might be shadowing builtins. Eventually, it should be a user-configurable feature. I checked in a fix to the "trailing builtin" problem a couple days ago. Have you tried that yet? Skip Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From steve at ferg.org Fri Dec 19 14:48:38 2003 From: steve at ferg.org (Stephen Ferg) Date: 19 Dec 2003 11:48:38 -0800 Subject: dynamic typing questions References: Message-ID: You can find some useful links at: http://www.ferg.org/projects/python_java_side-by-side.html From jay at jaydorsey.com Sat Dec 6 22:10:56 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sat, 6 Dec 2003 21:10:56 -0600 Subject: finding python modules In-Reply-To: References: Message-ID: <20031207031056.GB22553@gentoo.Earthlink.net> On Sun, Dec 07, 2003 at 12:54:06AM +0000, python newbie wrote: > Guys, > Very beginner question. > I'm importing xml.dom.minidom at the top of my file. > > I'm trying to figure out where the heck this is. According to Quick Python, > there should be folders on my drive > (using XP), under c:\python23, named xml, then underneath: dom, etc. But > there isn't. You missed one folder under the python folder: Lib. Full path should resemble something like: C:\Python23\Lib\xml Sometimes you can also find modules installed in the site-packages directory underneath the lib folder. -- Jay Dorsey jay at jaydorsey dot com From PeterM at resmed.com.au Thu Dec 18 16:11:40 2003 From: PeterM at resmed.com.au (Peter Milliken) Date: Fri, 19 Dec 2003 08:11:40 +1100 Subject: Broken python-model.el Message-ID: <274A369893F5FB4099345F006439D987013876E0@bella.corp.resmed.org> Still shows as 4.40 - I'll give it another go in about an hour or so, there must be a delay between you checking in and what I can see here. Peter -----Original Message----- From: Skip Montanaro [mailto:skip at pobox.com] Sent: Friday, December 19, 2003 8:08 AM To: Peter Milliken Cc: python-list at python.org Subject: RE: Broken python-model.el Peter> Well, I downloaded the python-mode.el just this morning as I was Peter> reading the news group. So it was about 1 - 1.5 hours ago (it's Peter> now 7:50am in Sydney, so I would have tried it probably about Peter> 6:30am) now that I downloaded python-mode.el (4.40) and had that Peter> exact problem. Peter> Do you mean you have changed the code since then? The revision Peter> number in the file doesn't seem to have changed (looking at Peter> sourceforge again now). So I don't think it is fixed :-) Ack! Fixed locally. Didn't check it in... :-( Try 4.41 (just checked in). Skip Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From pinard at iro.umontreal.ca Wed Dec 31 11:25:45 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 31 Dec 2003 11:25:45 -0500 Subject: RELEASED: allout-vim 031229 In-Reply-To: References: Message-ID: <20031231162545.GA8395@titan.progiciels-bpi.ca> [Samuel Walters] > Your blurb ("The Allout file format is ...") is only useful if you > know what a "synoptic structure of a text file" is, especially in > the context of computers. I sometimes use French words that just happen to be English words as well, once done the obvious morphological changes! The word "synoptique" has been part of my early youth: even in elementary school, teachers were bringing us into writing "plans synoptiques" to summarise our learning. There are a few words which are dangerous, as having very different meanings in French and English, this sometimes yield to misunderstandings. For example, English "to deceive" is much, much stronger than French "decevoir". In French, we easily use "formidable" to describe a girl who is wonderfully sympathetic and/or attractive. > I tried googling for the term and some variations, and only turned > up religious sites. I wasn't familiar with the format or the > terminology. Looking up synoptic in the dictionary didn't shed much > light on the situation. It surprises me. I learned English mostly by reading technical texts or messages -- or after being hired for teaching courses in English provinces or United States! :-). Many `man' pages have a `SYNOPSIS' division, which summarises how to lay out the command they describe. > I just wanted to know what it did before I went through the trouble of > downloading it. Of course. I rather hate when messages are merely inviting me to go out for fishing, so I would not want doing such things to others. :-) And all of you, I wish you enjoy These Times! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tjreedy at udel.edu Wed Dec 31 12:41:02 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 Dec 2003 12:41:02 -0500 Subject: Uplevel functionality References: Message-ID: "Maciej Sobczak" wrote in message news:bsu3bu$5rm$1 at nemesis.news.tpi.pl... > Hello, > > I would like to know if there is any possibility in Python to execute > arbitrary scripts in the context higher in the stack frame. An alternate answer from those already posted is to not create the new context that you want to uplevel from. Seriously. > In essence, I would like to have the equivalent of the following Tcl code: > > proc repeat {n script} { > for {set i 0} {$i < $n} {incr i} { > uplevel $script > } > } As I read this, this defines the repeat function as an abbreviation of a 'for' loop. The uplevel is only needed because the abbreviating process creates a nested frame. In Lisp, repeat would be written a text macro which does the substitution in the same frame, and hence the frame problem and need for uplevel would not arise. In Python, we currently live without the pluses and minuses of macros and usually write out the for loops ;-) > This allows me to do: > > repeat 5 {puts "hello"} > > prints: > hello > hello > hello > hello > hello for i in range(5): print 'hello' # does same thing. repeat(5, "print 'hello'") # even if possible, saves all of 5 key strokes repeat(5, lambda: print 'hello') # possible, without uplevel, takes 2 more > Or this: > > set i 10 > repeat 5 {incr i} > puts $i > > prints: > 15 i=10 for n in range(5): i+=1 print i In batch mode, which requires 'print ', 36 instead of 33 keystrokes. You *can* do this in current Python: def repeat(num, func): for i in range(num): func() def inci(): i[0]+=1 # need def since lambda only abbreviates 'return expression' i=[10] repeat(5, inci) >>> print i[0] 15 Python goes for clarity rather than minimal keystrokes. Example: It has been proposed that 'for i in n:' be equivalent to 'for i in range(n):'. Given the set theory definition n == {0, ..., n-1} (==set(range(n))), this is theoretically sensible, but was judged too esoteric for most people. Terry J. Reedy From deets_noospaam at web.de Tue Dec 9 17:22:00 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Tue, 09 Dec 2003 23:22:00 +0100 Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: > Here is the code used to call it from Python: > import os > filename = "C:\Python22\Canyon.mid" > os.system("C:\Python22\playb.exe%s"%filename) > ...this causes a dos box to appear which promptly hangs and does nothing, > at which time Python stops responding. Vartiations on this will cause the > dos box to appear with the message "Bad command or file name". > Looks like there is a space missing - os.system("C:\Python22\playb.exe %s"%filename) ^ Diez From jzgoda at gazeta.usun.pl Sat Dec 20 15:01:05 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 20 Dec 2003 20:01:05 +0000 (UTC) Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: David M. Wilson pisze: > Unless you design some silly rules to determine when empty parenthesis > should be allowed - did a get assigned the return value of sys.exit()? > (yes I know it doesn't have one) It has. The returned value is None. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From rol at post.com Wed Dec 17 04:57:21 2003 From: rol at post.com (Rene Olsthoorn) Date: Wed, 17 Dec 2003 10:57:21 +0100 Subject: py2exe: problem including libxml2 References: <3fcf581e$0$200$e4fe514c@news.xs4all.nl> Message-ID: <3fe02882$0$240$e4fe514c@news.xs4all.nl> Brad, Thomas, Thanks for your help. Brad, you were right. It is a same name problem. The sys.path trick that Brad uses is good. If that does not work try the following: Go to your Python 2.3 site-packages directory. Locate the file libxml2.py and copy it to libxml2py.py In your code use: import libxml2py as libxml2 Then, the exe generated by py2exe correctly runs. Thomas, LibXML is a very fast XML parser. It has python bindings. http://xmlsoft.org/python.html Greets, Rene Olsthoorn. "Thomas Heller" schreef in bericht news:fzfzt4zm.fsf at python.net... > "Brad Clements" writes: > > > "Rene Olsthoorn" wrote in message > > news:3fcf581e$0$200$e4fe514c at news.xs4all.nl... > >> Dear readers, > >> > >> py2exe has a problem including libxml2. Not at building time, but at > >> runtime. The libxml2.dll cannot be loaded... Is there anyone that NOT has > >> the problem? (and can you drop me your setup.py scipt, please). > >> > > > > Perhaps you hit the same problem I did when using libxml2 and libxslt in a > > service created by p2exe. > > > > Here are notes from my project diary (these notes are meant for my client to > > reconcile my bill vs. what I did) > > ----- > > The service builds, I can install it, but get an error when I run it: > > > > The instance's SvcRun() method failed > > File "win32serviceutil.pyo", line 663, in SvcRun > > File "UMXWIN32SVC.pyo", line 41, in SvcDoRun > > File "Rose\WebServer\UMXMServer.pyo", line 53, in ? > > File "Rose\WebServer\umx_handler.pyo", line 16, in ? > > File "Rose\WebServer\HTTPHandler.pyo", line 95, in ? > > File "Rose\WebServer\XMLProcessor.pyo", line 34, in ? > > > > exceptions.ImportError: dynamic module does not define init > > function (initlibxslt) > > > > This says that the service cannot import the libxslt module for some reason. > > > > I built a test script that py2exe runs in console mode, it also fails in the > > same way. > > > > I think libxml is using some kind of dynamic import mechanism, we need to > > work around. > > > > Aha, figured it out. example problem with libxml2. > > > > libxml2.py is a module that imports libxml2mod.pyd which imports libxml2.dll > > > > But, py2exe creates a default path like this: > > > > c:\\temp\\rose, c:\\temp\\rose\\library.zip > > > > This means that python tries to import from the directory first, before > > importing from library.zip. So, python imports libxml2.dll, not libxml2.py > > > > My workaround is to reverse the order of the imports in the startup script: > > > > zipfile = sys.path[-1] > > sys.path.insert(0,zipfile) > > Which version of py2exe are you using, and what is this libxml2? > > IIRC, in the latest version py2exe doesn't put the executable's > directory on the path anymore, but file names like libxml2.py, > libxml2.pyd, and libxml2.dll all at the same time have the potential to > confuse it! > > Thomas From nospam at covad.net Tue Dec 9 13:06:29 2003 From: nospam at covad.net (Douglas Crockford) Date: Tue, 9 Dec 2003 10:06:29 -0800 Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> Message-ID: <80804$3fd60ee5$436596f5$26728@msgid.meganewsservers.com> > >Why is python incompatible with .net? Why can't python be coded in C#? > > It's not. The .net virtual machine is Turing Complete. The subject here is imprecise. The issue is that .net performs very poorly with dynamic languages. So, for example, Microsoft is adding static features to JScript in an attempt to improve its performance. .net is having a homogenizing effect on programming languages. In the end, they may all become the same. And the ultimate .net language will not be Python. From frobozz_electric at hotmail.com Sat Dec 20 12:00:36 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 20 Dec 2003 17:00:36 GMT Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "John Roth" wrote in message news:vu765jfp9esl0f at news.supernews.com... > a third is the ability to forget the empty parenthesis after > a function/method call that doesn't require parameters. > Hi. Every time I see that feature in Ruby I find it appealing - and then I don't (which is kind of how I feel about the language as a whole). I find it appealing because, well, like you've said, the operation doesn't require parameters, so why clutter up the code with unnecessary parenthesis? And if I only ever read my own code, and I was sure I would always know what I had been doing in older code, I might be okay using that feature. But that's not the case. I do have to read other people's code, which means (in this case) I have to decipher, on each occurrence of a whether that is a variable or an implicit operation call (if I care about that sort of thing, which I might). In Python, it's a binding (unless it's a property "obj.a" in which case it's still a binding to a descriptor but that gets invoked during look-up, so ... have I lost my leg to stand on there?). I suppose I just prefer to know, from reading that line of code, without tracking back into other parts of the implementation, or running it to find out, whether a is a variable or an operation. But, then, properties can obscure the issue in Python just as well, so I don't think this argument has much steam (unless I advocate losing properties - which I really don't). So, I'll address a slightly different but wholly related issue. In Python, when I want to pass a function, method, or object as an argument, I do so by name: callable(function, method, obj) The names in the argument list are bindings to the object - in this case to a function, a method and some other type of object. Using the name of a function or method does not invoke it, so I can pass these operations by name without resorting to disambiguatory syntax introduction. Not so in Ruby: because, there, the names function/method would be found (during lookup) to refer to callables that take no parameters, so Ruby would invoke them - which is not what we want. To get around this, Ruby introduces :function, :method - which is not so terrible, I suppose. It's a trade-off imposed, in part, by the desire of the language designer to allow for a cleaner parameter-less method invocation. So, they've cleaned up one thing, only to dirty up another. And Python has done the same thing, only they've cleaned up name referencing rather than parameter-less callable invocations. Which is better? Having to say a() explicitly when you wish to invoke a callable, or having to say :a when you wish only to refer to the object and not invoke it? Well, If we just go by syntax, :a uses one less character than a(), so that could be a plus. And :a is very explicit (once you know what it means) - you know you're using a name reference (correct term?). But, when a and a() can both mean the same thing, or different things, depending on the context ... a = "variable" def a "method" end puts a puts a() # output variable method ... well, for me, that's not such a great thing. Part of language design appears to be about trade-off. And part of language preference appears to be about choosing the language that handles most of those tradeoffs as you would prefer (which can save you from having to write your own). I think I prefer that callable invocation be done explicitly, so that I may recognize it as such in my, and other people's, code. And I think I prefer not having to disambiguate name referencing via arbitrary syntax. I think that's what I prefer - and yet I see the allure of the "Ruby Way". Why use parenthesis for an empty parameter-list, when you don't have to? To be explicit. Why is that preferable? Because it's explicit? Um. Try again. Because explicit is better than implicit? Begs the question. Because ambiguous code requires you to expend more time reading to understand than does less ambiguous code? Hm. I don't find the code ambiguous, but even so the ambiguous code might take less time to write, so the overall time may balance out. People read code more often than they write it, so the balance would tip towards those who must read the code. Do they? Prove it. I site such and such a study. Well, I write more code than I read. Then you musn't be a very good programmer... and how could you write more code than you read? Do you not read your own code? You know what I meant, and who're you calling a bad programmer? ... And so on ... ad nauseum ... much like this post ... heh Sean From FBatista at uniFON.com.ar Tue Dec 16 13:34:25 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 16 Dec 2003 15:34:25 -0300 Subject: range of characters? Message-ID: Bud P. Bruegger wrote: #- I suppose there should be an elegant way of getting a range #- of characters #- as in #- #- range('A', 'Z') Python 2.2.3 (#1, Jun 18 2003, 16:30:09) [GCC 3.2.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> string.letters[26:] 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . Facundo From pln at razzle.Stanford.EDU Thu Dec 18 02:15:47 2003 From: pln at razzle.Stanford.EDU (Patrick L. Nolan) Date: Thu, 18 Dec 2003 07:15:47 +0000 (UTC) Subject: Tkinter+popen4+windows leads to unwanted window Message-ID: We have a python+Tkinter program that works properly on Linux, but when moved to Windows (XP) it behaves in a strange way. There's a section like this: (child_out, child_in) = popen2.popen4(cmd) line = child_out.readline() while line: do_something_with(line) line = child_out.readline() The program named in the string cmd is a C++ application which writes lines of text to its standard output. The function do_something_with() displays the output in a text window. When I run this script on Windows XP with a recent version of Active State python, nothing appears in the text window. Instead a new command tool window opens, and all the text appears there. When the program (cmd) terminates, the command tool remains, ready to accept commands. The Tkinter window locks up, with its menu bar blanked out. The python process burns 100% of the cpu time. Apparently the child_out "file" returned by popen4 isn't really passing its data to the python script. It seems to be going directly to a command tool, and I would guess that readline() is in an infinite loop. Is there some way to deal with this? -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From skip at pobox.com Wed Dec 3 17:54:14 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Dec 2003 16:54:14 -0600 Subject: Why Python (a bit different) In-Reply-To: <3fce6605$0$248$a3f2974a@nnrp1.numericable.fr> References: <3fce6605$0$248$a3f2974a@nnrp1.numericable.fr> Message-ID: <16334.27030.652114.73487@montanaro.dyndns.org> Gerald> 'Why did Guido create Python?' Start here: http://artima.com/intv/ Search for "Guido". Skip From bhoel at web.de Mon Dec 29 09:56:21 2003 From: bhoel at web.de (Berthold Höllmann) Date: Mon, 29 Dec 2003 15:56:21 +0100 Subject: make test segfaults with "--enable-shared" on Python 2.3.3 References: Message-ID: Andrew MacIntyre writes: > On Sun, 28 Dec 2003, Berthold Hoellmann wrote: > >> CXXFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ >> -ffast-math -fno-math-errno -funsafe-math-optimizations \ >> -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow >> >> CFLAGS=-O3 -fstrict-aliasing -funroll-loops -fschedule-insns2 \ >> -ffast-math -fno-math-errno -funsafe-math-optimizations \ >> -fno-trapping-math -march=athlon-xp -mfpmath=sse -msse -mmmx -m3dnow > > Build Python with the configure defaults before you start getting creative > with optimisation. > > Problems resulting from trying to use more aggressive optimisations than > the default should be taken up with the compiler vendor. Hello, make distclean env CFLAGS= CXXFLAGS= ./configure --with-thread --with-fpectl \ --with-signal-module --with-pymalloc --enable-shared --with-cxx=g++ env LANG=C CFLAGS= CXXFLAGS= make test gave: test_quopri test_random test_re make: *** [test] Segmentation fault aggain. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ It is unlawful to use this email address for unsolicited ads (USC Title 47 Sec.227). I will assess a US$500 charge for reviewing and deleting each unsolicited ad. From rasjidw at openminddev.net Wed Dec 3 05:40:58 2003 From: rasjidw at openminddev.net (Rasjid Wilcox) Date: Wed, 03 Dec 2003 21:40:58 +1100 Subject: Python, xml, databases, ... References: Message-ID: <3fcdbd79@mail.netspeed.com.au> Zunbeltz Izaola wrote: > I want to store the information in a A object in a file. The structure > is a tree-like structure and I think XML is a good choice. I want to > know what model SAX or DOM, will be better to write/read the > information from the file. Is posible the files to get big (>1MB) and > the XML HOWTO recommend to use SAX, is that ok? what would be eaiser? > > In a future i want to be able to do search and in different instances > of object A. I think i can storoe the information in a database > format. I think you want to be clear whether you want a database or not. If you want to put the data into a database, you probably do not want to also put it into a file structure. Although you certainly could then store to file in the database, I think you would end up loosing the usefulness of one or the other (or both). > What tool are suitable for this task? I have read somethin > about MySQL and PostgreSQL, but i think they are only for servers, no > for program, is that all right? What do you mean by 'they are only for servers'? Any machine can run a service (such as MySQL or PostgreSQL), and if it offers that service to other machines then it is acting as 'server', or it can just use it locally. What platform are you planning to run this on? If it is Linux, then either MySQL or PostgreSQL are easy options - most distros have pre-compiled versions out of the box. On Windows, both MySQL and PostgreSQL rely on the Cygwin dll. It looks like MySQL has an easier Windows install, but their use of the cygwin dll outside of Cygwin proper has serious stability consequences if the user installs another cygwin based program. PostgreSQL is a 'proper' cygwin program, but will be harder for non-unix/linux people to install/administer. You could also consider Firebird (http://firebird.sourceforge.net/) it has a native Windows version as well as a Unix/Linux version) or SQLite (http://www.hwaci.com/sw/sqlite/) with PySQLite (http://pysqlite.sourceforge.net/manual.html). There is also GadflyB5 (http://gadfly.sourceforge.net/) which looks like it is written in pure python. There are probably other options too. > I would build a GUI for the program (presumibly with wxPython). I want > to separate the GUI layer from the program layer. For comunication of > this two layer I have think in asyncore, but i have read something > about twisted and piro. Can anyone give my his/her opinion about this? Funny, I asked almost the same question about 20 minutes before you did. Cheers, Rasjid. From jeroen_ at _os3.dot.nl Sat Dec 6 10:54:08 2003 From: jeroen_ at _os3.dot.nl (Jeroen van der Ham) Date: Sat, 06 Dec 2003 16:54:08 +0100 Subject: Reading pipes in Python Message-ID: Hello, During my exploration of Python and rewriting something from Perl to Python I ran into something odd. I want to use a pipe so that a log of a program goes into a Python script instead of a log file. In Perl you just open a file, but specify that it is actually a pipe, but you read from it the same way. So I thought I'd do that with the following Python code: f=open('/tmp/myfifo','r') while 1: print f.readline() Now, here's the weird thing: - On Darwin this seems to work okay (seen it work odd on netmounts tho, but not able to test that atm) - On Linux this works fine until you send something to the pipe, after which it prints it and starts printing blank lines over and over. Even when using os.mkfifo() to create the pipe, this still does not work properly on Linux. Anyone any idea why this isn't working and what can be done to make it work? Regards, Jeroen. From andrew-pythonlist at puzzling.org Mon Dec 22 19:30:01 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 23 Dec 2003 11:30:01 +1100 Subject: Singleton process In-Reply-To: References: Message-ID: <20031223003001.GA4073@frobozz> On Mon, Dec 22, 2003 at 02:13:46AM -0500, Benjamin Han wrote: > On Mon, 22 Dec 2003, Andrew Bennetts wrote: > > On Mon, Dec 22, 2003 at 01:38:27AM -0500, Benjamin Han wrote: > > > > > > But this solution creates a file race condition? > > > > How? mkdir is atomic. Either it creates the directory and succeeds, or it > > fails. I don't see any problems here. > > ok I see. The reason I'm thinking of using a lock file through fcntl is that > even if a lock file exists (maybe due to a crash of some sort before), using > the locking mechanism would still work. The "test if it exists" approach > would fail because of some leftover from some accidental 'death' of the process > before. This is a potential problem, but Python is much less prone to unhandled crashes than C code. Use of a try/finally block, e.g.: if shouldRun(): try: main() finally: os.rmdir(MAGIC_PATH) You could possibly use an atexit handler instead. -Andrew. From mkent at webmd.net Tue Dec 30 13:10:29 2003 From: mkent at webmd.net (Mike Kent) Date: 30 Dec 2003 10:10:29 -0800 Subject: Problem with frozen app: compatibility between Unixware and SCO Unix References: <83846327.0312121348.f50f468@posting.google.com> Message-ID: <83846327.0312301010.3601e285@posting.google.com> Upon further intense investigation, here's what I now know. os.stat() is the culprit. A very simple test program frozen under Unixware 7.1 which does more more than stat '/tmp' will return proper results under Unixware, but return totally bogus results when that frozen test program is run on an OpenServer 5 machine. Bogus in the sense that the tuple of values returned by os.stat() contain values that are so far off, it is apparent that the structure returned by the OS's 'stat' system call is not being unpacked properly. The docs for the Unixware UDK state that the 'stat' system call is fully compatible across the two platforms. This was verified by writing a short 'C' language program, compiling it under Unixware, and running it on both Unixware and OpenServer. In both cases, it returned proper results. The problem appears to be something in Python's wrapper around 'stat' in posixmodule.c Any ideas on how I can proceed? From kamuelaf at verizon.net Sat Dec 27 05:54:17 2003 From: kamuelaf at verizon.net (Kamuela Franco) Date: Sat, 27 Dec 2003 10:54:17 GMT Subject: Using python to check the status of a program Message-ID: I would like to use a Python script to periodically check to see if a program is still running and if it isn't I want to start it up. Could someone point me on the right path? Thanks in advance. Kamuela From hungjunglu at yahoo.com Tue Dec 16 17:20:00 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 16 Dec 2003 14:20:00 -0800 Subject: Interactive programming Message-ID: <8ef9bea6.0312161420.6ef9b90e@posting.google.com> Hi, Is there a term for the ability of changing program code without the need of restarting the program? I mean, the most typical developer's cycle is: (a) write code (b) set break points, start the program (c) find bug, change code, goto (b) I know some environments allow you to modify the code, and resume execution, without having to restart your program from the very beginning. Some terms I have heard are "interactive programming", "edit-and-resume", etc. But is there standard name for this feature? regards, Hung Jung From hat at se-126.se.wtb.tue.nl Wed Dec 17 06:48:18 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Wed, 17 Dec 2003 11:48:18 +0000 (UTC) Subject: OO issues in python References: Message-ID: On Wed, 17 Dec 2003 11:23:33 +0100, Ali El Dada wrote: > in python, when a class, say Father, has a member that itself is an > instance of another class, say Child, an instance of Father actually > only has a reference to a Child, not the Child object itself, right? Correct, although I don't rally see why this is important. > because i know that in eiffel they give the programmer the 2 options, > the second being implemented with an additional keyword (expanded) so as > the eiffel documentation says, > > "Consider the example of a class covering the notion of car. Many cars > share the same originating_plant , but an engine belongs to just one You mean inheritance here, as in class Father(Child): ... ? > car. References represent the modeling relation "knows about"; > subobjects, as permitted by expanded types, represent the relation "has > part", also known as aggregation. The key difference is that sharing is > possible in the former case but not in the latter" Sharing is normally in one direction only, ie from Father to Child, afaik in both cases (both member-of and inheritance). Normally, one would write Child without being aware of Father, that is, Child should be written as a stand-alone, so it may be used in arbitrary contexts, such as class Mother(Child): .. > the reason why i'm asking is that i want my Child() instance to know > things about the parent without having to explicitly pass them as > arguments. this is not working :( You are trying to do something that is contradictionary to the OO idea. Luckily, that does not mean it is impossible to do. If the parent and the child class need to share data, you either put the data in the sub-class (ie Child), or you create a new class that holds the data where both the parent and the child have access to. Imho the first solution is preferrable because of a well-defined ownership of the data. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From ben at adversary.org Fri Dec 19 20:16:22 2003 From: ben at adversary.org (Ben McGinnes) Date: Sat, 20 Dec 2003 12:16:22 +1100 Subject: semi-OT: DNS issues for python.org Message-ID: <20031220121622.O749@devious.adversary.org> Hi all, I'm seeing a lot of "lame server" messages from my name server when trying to resolve mail.python.org and neither my name server (devious.adversary.org) nor those of my upstream (yarrina.connect.com.au & warrane.connect.com.au). In fact, one of my upstream's caches (yalumba.connect.com.au) is locating what appears to be invalid nameservers for python.org. Yalumba believes python.org's nameservers are ns53.worldnic.com & ns54.worldnic.com. While tracking back from UltraDNS points to ns.xs4all.nl & ns2.xs4all.nl. So does anyone know if there are currently any registration or delegation issues with python.org or if they are seeing similar things elsewhere? Regards, Ben P.S. Obviously I have no idea if this will even make it to the list, if I see Postfix whinge too much I'll re-post via Usenet. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 181 bytes Desc: not available URL: From http Thu Dec 11 16:46:55 2003 From: http (Paul Rubin) Date: 11 Dec 2003 13:46:55 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xad5z1jq5.fsf@ruckus.brouhaha.com> <3fd8df10$0$17113$626a54ce@news.free.fr> Message-ID: <7xhe0781tc.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > I guess > > I can get the client to pay > > Why ? It's free (as in free beer and free speech) I mean for the build tools (Visual C++ or whatever). I can't really use the WxWindows source code without a way to compile it. I'm getting discouraged to hear that WxWindows itself has numerous bugs though. From __peter__ at web.de Tue Dec 16 04:32:42 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Dec 2003 10:32:42 +0100 Subject: More info on my Python problem... References: Message-ID: JD wrote: > This is more details about my problem, which I already managed > to post as a Python bug to Sourceforge > > This problem is not related to the bug I encountered earlier, and > this is related to a question I have about Python hanging up > either from a shell, or my importing a module. > > I want to figure out if this really IS a python bug, but I suspect > that if it hangs up the console, it would be a bug. > > Is there someone who I might contact > via phone to walk me through this? (Assuming I can't get adequate > information here? Or does anyone care about Python bugs?) This is in > Python 2.3.3c1 on OpenBSD (though I doubt the OS matters). The symptom > is > that I run my program and Python locks up. I cannot control-C or > control-D > to get out of it; I have to log in separately and kill -9 the process. > The > process is listed as "D+" while it is hung, though it doesn't seem to be > accessing the disk, and I'm quite sure there are no disk problems > (though > I'm not physically next to the server, so I can't check the drive LED). > > How should I approach debugging this? Are there Python tools? Or should > I > use gdb? ktrace? systrace? I'm assuming I have to do this, as a bug > report > which reads "Python locks up" isn't to useful. Can you make a small variant of your program that still shows the error/bug? Chances are that in the process of making such a variant you will find the error yourself. If not, you have something that lends itself to posting on c.l.py. Only if no one here can point you to an error in your code, you should file a bug report. Here is a script that shows similar behaviour: import threading, time def forever(): while True: print "alive and kicking" time.sleep(1) threading.Thread(target=forever).start() The print statement makes it pretty clear what's going on when you run it. Putting print before/after access of external resources and into inner loops should make it clear where your program hangs. Peter From strombrg at dcs.nac.uci.edu Mon Dec 29 15:02:14 2003 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 29 Dec 2003 20:02:14 GMT Subject: writing a linux screensaver? Message-ID: I'd like to examine what's involved in writing a screensaver for linux (xscreensaver) using python, and who-knows-what GUI toolkit. I looked over pygtk2, pygame, and wxpython, but none seem able to write to the root window (wallpaper) as required by xscreensaver (?). pygtk1 appears able, but of course it's going away. I hope to use GL a little bit, not necessarily with hardware acceleration, so a GUI toolkit that allows that is a big plus. pygame apparently can be told which window id to write to, which might work out, but I'm not sure which window to tell it to write to. I tried the window id given by xwininfo -root, but that just seemed to result in a very confused X server. Any suggestions? From bokr at oz.net Fri Dec 12 05:47:39 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Dec 2003 10:47:39 GMT Subject: Function application optimization. References: Message-ID: On 12 Dec 2003 10:47:50 +0100, Jacek Generowicz wrote: >Given > > fncs = [func1, func2, ..., funcN] > args = [arg1, arg2, ..., argN] > >How should one spell > > results = map(lambda f,a: f(a), fncs, args) > >in order to get the result most quickly ? > > > >Unfortunately "apply" takes a tuple of arguments, and there is no >"funcall"[*] in Python. > > >[*] def funcall(fn, *args): > return fn(*args) > >>> fncs = [lambda x,f='func_%s(%%s)'%i:f%x for i in xrange(4)] >>> args = 'zero one two three'.split() >>> map(lambda f,a: f(a), fncs, args) ['func_0(zero)', 'func_1(one)', 'func_2(two)', 'func_3(three)'] I'd probably try a list comprehension >>> [f(a) for f,a in zip(fncs,args)] ['func_0(zero)', 'func_1(one)', 'func_2(two)', 'func_3(three)'] Regards, Bengt Richter From claird at lairds.com Sun Dec 14 08:10:44 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 14 Dec 2003 13:10:44 -0000 Subject: intro to python books References: Message-ID: In article , Kamus of Kadizhar wrote: . [request with much useful detail, to which we'll return later] . . >I've had good luck with the O'Reilly books in the past, but I have to >buy everything mail order, so I can't browse easily and see what I'm buying. . . . describes ways online browsing might be available to you. I think you'll want to read this. -- Cameron Laird Business: http://www.Phaseit.net From bokr at oz.net Sat Dec 13 19:41:54 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 00:41:54 GMT Subject: ANN: lunatic-python 0.1 References: Message-ID: On Sat, 13 Dec 2003 18:18:36 -0200, Gustavo Niemeyer wrote: >> Why the https? >> >> I expect you have a good explanation, >[...] > >Unbelievable... I apologize for whatever offense/unpleasant_astonishment I may have caused. I'm guessing "I expect" was not the best choice of words, since one interpretation could be to imply a totally inappropriate presumption of social relationship between us, as between parent and a child being admonished (certainly not my attitude towards you ;-) "Explanation" was not the best choice either, come to think of it. I meant it in the sense of "I'd be willing to bet you have good reasons..." I hope that works better. Sorry (and thank you for your restrained reply ;-) Regards, Bengt Richter From reply.in.the.newsgroup at my.address.is.invalid Fri Dec 26 15:09:22 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 26 Dec 2003 21:09:22 +0100 Subject: Multiple assignment behaves unexpectedly (was: Help ! newbie problem) References: Message-ID: ferdydurke: >... a,b,c = b,a+b,c+1 b is set to a + b. [...] >... a=b >... b=a+b ^ This a has a different value now, because of the previous statement. So this sets b to b + b. -- Ren? Pijlman From Scott.Daniels at Acm.Org Mon Dec 1 20:08:15 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 01 Dec 2003 17:08:15 -0800 Subject: Filtering through an external process In-Reply-To: <7xllpyyl1s.fsf_-_@ruckus.brouhaha.com> References: <7xllpyyl1s.fsf_-_@ruckus.brouhaha.com> Message-ID: <3fcbf321$1@nntp0.pdx.net> Paul Rubin wrote: > Anyone know if there's code around to filter text through an external > process? Sort of like the Emacs "filter-region" command. For Check out popen2 -- its the piece you need. dest, result = os.popen2('cmd') dest.write('echo Hello world\n') dest.write('exit\n') dest.close() result.read() So, perhaps you mean: import os def filtered(command, source): dest, result = os.popen2(command) dest.write(source) dest.close() try: return result.read() finally: result.close() -Scott David Daniels Scott.Daniels at Acm.Org From cbrown at metservice.com Tue Dec 16 14:25:51 2003 From: cbrown at metservice.com (Colin Brown) Date: Wed, 17 Dec 2003 08:25:51 +1300 Subject: traceback as string References: Message-ID: <3fdf5c2b$1@news.iconz.co.nz> "John Hunter" wrote in message news:mailman.202.1071593230.9307.python-list at python.org... > > What is the best way to get the traceback as a string. I define the following module "Excepts.py" for logging exceptions in daemon processes: ------------------------------------------ import sys,traceback def error(): tb = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info( )[2]) return tb[len(tb)-1].replace('\n','') def errorstack(): return ''.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.e xc_info()[2])) ------------------------------------------- Colin Brown PyNZ From klapotec at chello.at Fri Dec 12 07:19:25 2003 From: klapotec at chello.at (Christopher Koppler) Date: 12 Dec 2003 04:19:25 -0800 Subject: java.awt.Robot equivalent? Message-ID: I need to simulate mouseclicks (in Win2K) in another application's window. Googling threw up java.awt.Robot, and a bit of trial and error showed that it could do what I needed (simulate a mouseclick on an open window). However, I don't want to use Java (or Jython) if I can avoid it, as I already have a Python 2.3 app, which works quite nicely, thank you, and which needs to click into a foreign window. Is this capability available in any of the GUI toolkits (searching Tkinter docs brought up nothing)? Is there a C library that I could wrap? Or maybe I just need to use the Windows extensions. But if so, how - I don't have the slightest idea how that would work. Anyone have any pointers? -- Christopher From 9974331 at cvm.qc.ca Mon Dec 22 06:34:10 2003 From: 9974331 at cvm.qc.ca (Askari) Date: 22 Dec 2003 03:34:10 -0800 Subject: Thread and tkMessageBox (Synchonimous) Message-ID: <104c369a.0312220334.7ee4583f@posting.google.com> I think that my problem is in the syncho between main thread and my thread created with (with thread.start_new_thread(...) ). But, I don't understand the method for syncho with a thread... I want pop a message to user with tkMessageBox.showinfo("Title","Message") but when this command is in my thread, it's don't work (and my main thread give no reponse (crash)). How I can pop a message (or question) with a thread? Askari From brian at sweetapp.com Tue Dec 16 18:07:27 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 16 Dec 2003 15:07:27 -0800 Subject: Is anyone using Python for .NET? In-Reply-To: Message-ID: <030b01c3c429$6027f340$0000fea9@dell8200> > Is anyone using Python for .NET? I mean Brian's version at Zope, I'm using it. > Not the experimental ActiveState stuff, which tried to compile IL and > apparently didn't succeed. Microsoft funded it as a proof of concept. The concept was proven. > 1) whether to use it for my C++ / C# / .NET / Python (?) game project. > It's a prototype, so in this context a "mostly working beta" is > acceptable. A lot of important features (like subclassing abstract classes and implementing interfaces) don't work yet. Whenever that has bitten me, I've written a simple C# class to help me bridge into Python. > I won't need "ready for prime time" for another year yet. In another year it is possible that Python compiled to IL will be faster than CPython in most cases. But it is really hard to say. Cheers, Brian From robin at jessikat.fsnet.co.uk Wed Dec 31 09:47:06 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 31 Dec 2003 14:47:06 +0000 Subject: Uplevel functionality References: Message-ID: In article , Maciej Sobczak writes How about this, apparently f_locals/globals are readonly so you won't be allowed arbitrary scopes. ############################ C:\tmp>cat repeat.py def repeat(n, script): from sys import _getframe f = _getframe(1) L = f.f_locals G = f.f_globals for i in xrange(n): exec script in G, L def test(): i = 0 repeat(3,'print i;i+=5') if __name__=='__main__': test() C:\tmp>repeat.py 0 5 10 C:\tmp> ############################ >Hello, > >I would like to know if there is any possibility in Python to execute >arbitrary scripts in the context higher in the stack frame. > >In essence, I would like to have the equivalent of the following Tcl code: > >proc repeat {n script} { > for {set i 0} {$i < $n} {incr i} { > uplevel $script > } >} > >This allows me to do: > >repeat 5 {puts "hello"} > >prints: >hello >hello >hello >hello >hello > >Or this: > >set i 10 >repeat 5 {incr i} >puts $i > >prints: >15 > >That second example shows that the script provided as a second parameter >to the "repeat" procedure (the script is "incr i") is executed in the >context where the procedure was called, not locally in the procedure itself. > >The strongest analogy to the above repeat procedure in Tcl would be a >hypothetical Python function: > >def repeat(n, script): > for i in xrange(n): > EVALUATE script HIGHER IN THE STACK #??? > > >Thank you very much, > -- Robin Becker From michele.simionato at poste.it Mon Dec 15 13:25:22 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 15 Dec 2003 10:25:22 -0800 Subject: Build classes/packages dinamicaly References: Message-ID: <95aa1afa.0312151025.3c2bc0ae@posting.google.com> Paulo Pinto wrote in message news:... > Hi, > > > I have a package that generates classes from a > set of XML files using exec. > > So far the classes appear in the global namespace. > > Is there any way to also create packages dinamicaly > and add the classes to those packages? > > Thanks in advance, > Paulo Pinto By packages I think you mean modules. Here is a solution in Python 2.3: >>> from types import ModuleType >>> mymodule=ModuleType("mymodule") >>> print mymodule >>> class C(object): pass ... >>> mymodule.C=C In older Python versions, look for the module "new". From fowlertrainer at anonym.hu Wed Dec 10 03:22:02 2003 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Wed, 10 Dec 2003 09:22:02 +0100 Subject: mod_python and caching DB objects Message-ID: <1252667545.20031210092202@anonym.hu> Hello ! I want to create a site with mod_py. I am beginner. Can I create an persistent database connection/objects in mod_py ? I want to use KInterBaseDB with FireBird server. Thanx for any advance ! (...for links/docs an extra thanx) -- Best regards, fowlertrainer mailto:fowlertrainer at anonym.hu From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 10 12:17:47 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 10 Dec 2003 18:17:47 +0100 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? In-Reply-To: <3fd7471f@news.mt.net.mk> References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> <3fd728e3$0$213$e4fe514c@news.xs4all.nl> <3fd7471f@news.mt.net.mk> Message-ID: <3fd7553b$0$218$e4fe514c@news.xs4all.nl> ?????? ?. wrote: > Put this in ~/.pythonrc, and setup the PYTHONSTARTUP environment variable to > point to it: export PYTHONSTARTUP=~/.pythonrc > > > # ~/.pythonrc > # enable syntax completion > try: > import readline > except ImportError: > print "Module readline not available." > else: > import rlcompleter > readline.parse_and_bind("tab: complete") I say thank you ! This works like a charm. Somehow I've never discovered rlcompleter... :-) --Irmen From a.schmolck at gmx.net Sat Dec 20 13:58:09 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 20 Dec 2003 18:58:09 +0000 Subject: dynamic typing questions References: Message-ID: "John Roth" writes: > Also, pervasive testing has so many other advantages > that I'm beginning to think that debuggers were the > single worst invention in history. Pervasive testing is much easier in an interactive enviroment with a good debugger. 'as From tjreedy at udel.edu Tue Dec 30 10:34:05 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 10:34:05 -0500 Subject: Newbie question about memory management References: Message-ID: "Oh Kyu Yoon" wrote in message news:bsr299$eg0$1 at news.Stanford.EDU... > I am writing my first python program, and I have to deal with several lists > of double precision numbers that are about 10,000,000 in length. > If I have 5 such lists, 5 x 10,000,000 x 8bytes ~ 400 MB which is too much > for the computer memory. > Does anyone have better strategies to do this? If you use Python lists of wrapped floats, you will use more than 8 bytes each. To make arrays of C floats, and for much faster computation, use Numerical Python. It includes wrappings of LinPak and FFTPak. tjr From francisgavila at yahoo.com Tue Dec 23 17:40:50 2003 From: francisgavila at yahoo.com (Francis Avila) Date: Tue, 23 Dec 2003 17:40:50 -0500 Subject: global and None References: Message-ID: Paul McGuire wrote in message ... >"Francis Avila" wrote in message >news:vug3s0pa1q1sa3 at corp.supernews.com... >> Leo Yee wrote in message ... >> >My purpose is to init g. This is very useful when we cannot construct a >> >global variable. >> >> Like when? And why? >> > >One reason is to do late construction/initialization, or lazy >initialization. If an object is very time-consuming to construct, don't >create it at import time, wait until it is actually used. Once created, >save it in a global so that you don't have to re-create it every time. Hmm, I hadn't thought of that. If this is a use case, aren't the restrictions placed on global in the specs rather encumbering, and should be removed? (Well, except for for-loop targets and formal parameters.) As it is, to comply, you'd have to use a temporary name for construction, and then assign to the global name. -- Francis Avila From newsgroups at jhrothjr.com Sun Dec 21 19:15:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 19:15:42 -0500 Subject: Count Files in a Directory References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: "hokiegal99" wrote in message news:93f5c5e9.0312211545.363b91a6 at posting.google.com... > I'm trying to count the number of files within a directory, but I > don't really understand how to go about it. This code: > > for root, dirs, files in os.walk(path): > for fname in files: > x = str.count(fname) > print x I'm not sure why you're trying to use the str(ing) module. (untested) for root, dirs, files in os.walk(path): print "files in '%s': '%s'" % (root, len(files)) This should give you a list of the directories under 'path,' with the number of files (not directories!) in each one. > > Produces this error: > > TypeError: count() takes at least 1 argument (0 given) > > for root, dirs, files in os.walk(path): > for fname in files: > x = list.count(files) > print x > > TypeError: count() takes exactly one argument (0 given) > > Also wondered why the inconsistency in error messages (numeric 1 vs. > one)??? Using 2.3.0 One function (str.count) seems to have keyword arguments, the other one doesn't. That's why the 'at least' versus the 'exactly.' The two cases are processed slightly differently. John Roth > > Thanks!!! From adalke at mindspring.com Fri Dec 26 17:01:31 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 26 Dec 2003 22:01:31 GMT Subject: Project dream References: Message-ID: <%c2Hb.7537$lo3.4095@newsread2.news.pas.earthlink.net> Will Stuyvesant: > Suppose you have the time and the money to start a new project in > Python. What would you like to do? An integrated chemical/bioinformatics development and exploration environment. Got a few million dollars to fund me? (Actually, more like 10 million, but bootstrappable with only a few million.) :) > - A civilization like game in Python, with multiplayer support via > twisted. There's been a few civ clones -- I recall playing one in the mid-90s for Python using CLIPS for the AI. Don't recall the name now. There's also openciv (in Python, nearly complete, no longer active) or freeciv (in C, active). What would the advantage be to writing yet another clone? > - An easy to use tool for drawing diagrams, typically various kinds of > arrows and circles and boxes, that produces nice .eps and .svg files. What about Sketch? http://sketch.sourceforge.net/ > - A roguelike in Python. Since there is still no portable curses, it > needs WConio or something like that, and also multiplayer would be > great. Why does that need to be rewritten in Python? As I understand it, the C version is very portable and may simply need just bindings for Python. > - Something for weblogging and todo things, probably via CGI. Aren't there a few dozen of those already? Falls into the category of easy to write but without one clear way to do it. So there are a lot of different implementations, all different, all focused on solving the given author's needs. > What would your favorite be? More important, what would *your* favorite be. It looks like you want to do a project but don't know which one to focus on. My answer then is to do any of these projects; they are all great ones to learn how to do larger, more useful projects. Andrew dalke at dalkescientific.com From theller at python.net Thu Dec 11 03:37:17 2003 From: theller at python.net (Thomas Heller) Date: Thu, 11 Dec 2003 09:37:17 +0100 Subject: numarray doesn't work on win2k References: <3fd82588$0$18044$3b214f66@aconews.univie.ac.at> Message-ID: "Alexander Schwaigkofler" writes: > Hi! > > I have the following problem with numarray. I read the install.txt manual, > but it doesn't already work. > OS: Microsoft Windows 2000 [Version 5.00.2195] > python: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on > win32 > numarray: Version 0.7 > the output from the installation (by hand) you can see below: > > The other possibility to install numarray on a win32 platform is to run the > self-installing executable. If I tried it that way, I can't test the > numarray package. > Is there any problem with the installtion that doesn't descripe in the > install.txt-File? [...] > running build_ext > building 'numarray._conv' extension > creating build\temp.win32-2.2 > creating build\temp.win32-2.2\Release > cl.exe /c /nologo /Ox /MD /W3 /GX -IInclude/numarray -IC:\..\python22 > 3\include /TcSrc\_convmodule.c > /Fobuild\temp.win32-2.2\Release\_convmodule.obj > error: command 'cl.exe' failed: No such file or directory You need a working C compiler. Thomas From bostjan.jerko at mf.uni-lj.si Mon Dec 1 06:25:30 2003 From: bostjan.jerko at mf.uni-lj.si (=?utf-8?Q?Bo=C5=A1tjan?= Jerko) Date: Mon, 1 Dec 2003 12:25:30 +0100 Subject: comparing nan "number" Message-ID: <20031201112530.GA28059@mf.uni-lj.si> Hello ! I need to know if the result of math formula is nan (Not a number). How can I do that? Thanks, B. From try_vanevery_at_mycompanyname at yahoo.com Thu Dec 25 16:53:53 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Thu, 25 Dec 2003 13:53:53 -0800 Subject: ProtoCiv: porting Freeciv to Python References: Message-ID: "cr88192" wrote in message news:vul2i238el9hda at corp.supernews.com... > > > I am mostly responding because I found it amusing that I disagreed with > nearly every point mentioned here, this is not meant as any kind of > discouragement though... Different strokes for different folks! :-) > it is quite likely that I just have a very much different set of ideals... Yes, given our previous discussions in comp.games.development.programming.misc, I'd say your tastes run the opposite for a number of significant things. Functional vs. imperative, technology vs. Game Design. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "Trollhunter" - (n.) A person who habitually accuses people of being Trolls. From __peter__ at web.de Mon Dec 22 13:53:23 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Dec 2003 19:53:23 +0100 Subject: print arabic characters References: <3014031e.0312220305.c38ffa3@posting.google.com> Message-ID: Ahmad wrote: > I am a python newbie, I want to print on the console UTF-8 arabic > characters. They print OK with > print text.encode("UTF-8") > > BUT, the characters are printed LTR, not RTL (right to left). How can > I change the printing direction?? Are all arabic characters 2 byte in UTF-16? Then the following RTLStream class should work in an otherwise left to right environment. Call the script with a -d or --delay parameter to see it working. import sys, time def utfReverse(s): # CAVEAT: this will mess up characters that are # more than 2 bytes long in utf 16 u = s.decode("utf-8") return u[::-1].encode("utf-8") class RTLStream: """ Emulate a right-to-left printing console in a left-to-right environment """ def __init__(self, out=sys.stdout, wrapwidth=40): self.out = out self.wrapwidth = wrapwidth self.curline = "" def _write(self, s): if len(s) == 0: return self.curline += utfReverse(s) self.out.write("\r") if len(self.curline) > self.wrapwidth: self.out.write(self.curline[:self.wrapwidth]) self.out.write("\n") self.curline = self.curline[self.wrapwidth:] self.out.write(self.curline.rjust(self.wrapwidth)) def _nl(self): self.out.write("\n") self.curline = "" def write(self, s): lines = s.split("\n") lines.reverse() for line in lines[:-1]: self._write(line) self._nl() self._write(lines[-1]) class SlowStream: """ delay the output to the target stream """ def __init__(self, out=sys.stdout, delay=0.01): self.delay = delay self.out = out def write(self, s): for b in s: time.sleep(self.delay) self.out.write(b) self.out.flush() if __name__ == "__main__": rtlstream = RTLStream(wrapwidth=36) args = sys.argv[1:] if "--delay" in args or "-d" in args: rtlstream.out = SlowStream() # always save a copy of the original stdout orig_stdout = sys.stdout # redirect stdout sys.stdout = rtlstream print "sella ow", print "tsieweb kc\xc3\xbclg hcrud hcis" print "dnu", "thcsuat", print "kcilb ned", "hcuregniew mi\negnir eid thcsuat dnu", print "egnid red hcsuar mi" print "med kc\xc3\xbclgnegeg med ud tsneid" # restore stdout sys.stdout = orig_stdout # explicit redirection with # print >> rtlstream, some_text # is usually preferable print print "back to normal" print >> rtlstream, "a saner way to use it" print "that's all folks" Disclaimer: As I know nothing about right-to-left printing languages, it's likely that I have got it at least partially wrong. Can anybody point me to a way to iterate over characters with a varying number of bytes? Something like for c in "Gru\xc3\x9f".characters("utf-8): print repr(c), #should print 'G' 'r' 'u' '\xc3\x9f' Peter From http Thu Dec 11 10:05:30 2003 From: http (Paul Rubin) Date: 11 Dec 2003 07:05:30 -0800 Subject: What GUI toolkit looks the best? References: <7xekvby0xr.fsf_-_@ruckus.brouhaha.com> <7xekvb1koc.fsf@ruckus.brouhaha.com> Message-ID: <7x65gn1jk5.fsf@ruckus.brouhaha.com> claird at lairds.com (Cameron Laird) writes: > I persist at this out of concern that I'm not making things clear. > My stake, incidentally, is that you be successful, not that you > use any particular toolkit. > > The second URL gives working code that you can use immediately in > your own applications to improve their appearance. This is not an > extension or anything at all difficult or constraining; it's just > a little prologue that refines the standard Tkinter appearance. > It *is* in use, right now, in several applications that must have > professional appearances. The first URL is about committee work, > essentially, that will fold the enhancements of the second URL > back into the standard Tk distribution. Oh cool. The second screen shot on that page ("after") does look a lot better than the "before" shot. I guess I'll look at it more carefully, but Tkinter has always made me cringe because of its use of tcl (why does it need its own extension language if Python itself is supposed to be such a good one)? Thanks. From jkrauze at ccs.neu.edu Wed Dec 3 12:18:07 2003 From: jkrauze at ccs.neu.edu (Joseph Krauze) Date: Wed, 3 Dec 2003 12:18:07 -0500 Subject: reloading modules Message-ID: Assume a main python file that does the following: from lib_mod import performAction def main(): return performAction("myFile") Now, if I modify lib_mod.py and just try to reload main.py, lib_mod is not updated. I have searched online and came upon a few tinkers but nothing that seemed to be blessed by python.org. Is there a feature or an official modification that I'm missing? Otherwise, I'll probably always do a try on a reload at the top of main.py but that does not seem too robust to me. I am using 2.3.2 on CLI. Thanks, Joe From fredrik at pythonware.com Thu Dec 11 01:58:36 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 07:58:36 +0100 Subject: check disc space References: <99dce321.0312102124.3d54354e@posting.google.com> Message-ID: "T. Schulz" wrote: > I wonder if it would be worthwhile to have such a functionality > somewhere in the os module? two counter-arguments: - the os module is traditionally used to provide access to posix-style services provided by the OS (or the C library). in this case, os.statvfs is such a function; calling out to "du" isn't (shouldn't that be "df", btw? os.popen("du -k dir").split()[-5] sure doesn't give the free diskspace on any platform I have access to...) - what you mean with "free disc space" may depend on the platform and the application; os.statvfs provides lots of additional information that you can use on a Unix platform, and there are similar (but not identical) metrics available on Windows. (a third argument is that "free disc space" is a rather meaningless metric on a modern operating system; it's hardly ever useful for anything except "warning, warning, less than 5% free space" alerts. you really don't want people to write "if os.getfreespace() >= len(buffer): f.write(buffer)" and file a bug when write fails ;-) From eli456123 at hotmail.com Sun Dec 21 17:29:39 2003 From: eli456123 at hotmail.com (Eli Pollak) Date: Mon, 22 Dec 2003 09:29:39 +1100 Subject: dynamic typing questions Message-ID: > > The other programmer here is very concerned >about > > dynamic typing though in Python. He feels like >this > > would be too much of a hinderance on us and too >easy > > for us to make a mistake and not catch it until > > runtime making debugging harder. > >One problem with static typing is that the type >you want is too often not one of the types you >have immediately available. It may be a subset or >union thereof. If log(-1.0) passes the compiler, >then you get a runtime crash that is at most as >graceful as Python's default traceback. If log(1) >does not pass the compiler (if it does not >autocast to float), then you are delayed until you >stick in the 'missing' decimal point. > >The corresponding advantage of Python's dymanic >typing is that functions are generic; they work >with any data that works and is not specifically >excluded. C preprocessor text macros such as >(untested, written from years ago memory) > >#define max(a,b) ((a) > (b) ? (a) : (b)) /* beware >of double side-effects */ > >that implement generic pseudofunctions testify to >the usefulness of this. > >Terry J. Reedy I find the same problem. I have to check the type of every parameter of every method to ensure unbreakable code. php5 has something I think would be nice in python. they call it 'type hinting'. class blah: def fn(self, int num, obj): # declare num to be of type int, but obj is dynamically typed # do something such that you can optionally put in the type and it will be checked for you. This would save me alot of what I think is unnecessary parameter validation, yet allows dynamic typing if you want to use that instead. Cheers Eli _________________________________________________________________ Get less junk mail with ninemsn Premium. Click here http://ninemsn.com.au/premium/landing.asp From M.Dufour at ewi.tudelft.nl Fri Dec 19 10:30:35 2003 From: M.Dufour at ewi.tudelft.nl (Mark Dufour) Date: Fri, 19 Dec 2003 16:30:35 +0100 (MET) Subject: dynamic typing questions In-Reply-To: <20031219150339.63883.qmail@web60401.mail.yahoo.com> Message-ID: > The other programmer here is very concerned about > dynamic typing though in Python. He feels like this > would be too much of a hinderance on us and too easy > for us to make a mistake and not catch it until > runtime making debugging harder. I'm personally convinced that the increase in productivity, compactness of code in Python and long-term maintainability, among other things usually far outweigh the lack of static typing. Static typing tends to only catch some syntactical bugs on the surface, leaving the hard ones for the programmer. There is a nice article about this topic by Bruce Eckel (who subsequently wrote the books Thinking in C++, Thinking in Java, and who is now working on Thinking in Python.) He explains why unit tests are often better for catching the hard bugs, while of course this does not require static type checking.. ;) http://www.mindview.net/WebLog/log-0025 You can find some other nice articles about Python by Bruce Eckel here as well. IMO the only disadvantage of Python versus Java and C++ is the comparatively slow execution speed.. but this is being addressed. I know I'm hooked! Mark Dufour. -- 'Making Linux GPL'd was definitely the best thing I ever did.' - Linus Torvalds From grey at despair.dmiyu.org Fri Dec 19 19:57:29 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 20 Dec 2003 00:57:29 -0000 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: On 2003-12-20, John Roth wrote: > a third is the ability to forget the empty parenthesis after > a function/method call that doesn't require parameters. class ThisIs: avariable = 'a' def amethod(self): return 'b' thisis = ThisIs() print thisis.avariable print thisis.amethod() import this print "Read line 2." -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From exarkun at intarweb.us Thu Dec 18 14:43:45 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 18 Dec 2003 14:43:45 -0500 Subject: cleanup after exceptions In-Reply-To: <0%mEb.1392$HR.4074@news.indigo.ie> References: <0%mEb.1392$HR.4074@news.indigo.ie> Message-ID: <20031218194345.GA9208@intarweb.us> On Thu, Dec 18, 2003 at 07:11:12PM +0000, Padraig at Linux.ie wrote: > Hi, > > I'm a little confused why objects > are not deleted after they go > out of scope due to an exception? Because objects don't go out of scope. Only variables do. Objects remain "alive" as long as there are any references to them. > > For e.g. > > >>> import time > >>> > >>> def f(): > >>> myfile=open("file.test","w") > >>> myfile.write("not flushed\n") > >>> exception=throw > >>> > >>> f() > >>> time.sleep(10) > > > The file is not written/closed until > the python interpreter exits. > The same thing applies to other objects. In this case, the traceback still holds a reference to the frame from which the exception was raised, which itself holds a reference to all the locales from that function. Calling sys.exc_clear() (possibly followed by gc.collect()) should force the cleanup you expect. Jp From ich at jan-kesten.de Thu Dec 18 11:24:12 2003 From: ich at jan-kesten.de (Jan Kesten) Date: Thu, 18 Dec 2003 17:24:12 +0100 Subject: Module for Informix Database? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, does anybody know, if there is a module to connect to an Informix database? I looked around, but I have seen there only modules for Python 1.x - and this ones do not work with 2.x ;-( Thanks for any hint! Jan -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE/4dSsvvmCkIIgH8QRAomRAJ9vk8hKIGp3Lw+JFwPkBcRz8hWJXgCfXU5b UW4IYY39Lsut5DCDBLG+gx0= =lwKC -----END PGP SIGNATURE----- From jzgoda at gazeta.usun.pl Mon Dec 22 14:56:37 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 22 Dec 2003 19:56:37 +0000 (UTC) Subject: The Truth? References: <3d06fae9.0312211802.66ad7944@posting.google.com> Message-ID: jmdeschamps pisze: > http://honors.montana.edu/~jjc/easytut/easytut/easytut.html This tutorial was my wife's first introduction to programming. I couldn't explain better all these control statements, loops and data structures. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From sebastien.giraud at eds.com Thu Dec 18 04:09:48 2003 From: sebastien.giraud at eds.com (Giraud, Sebastien) Date: Thu, 18 Dec 2003 09:09:48 -0000 Subject: is file open? Message-ID: I should work cause it's made for it :) I had same problem checking socket bind and try did help me well :) -----Message d'origine----- De : python-list-bounces+sebastien.giraud=eds.com at python.org [mailto:python-list-bounces+sebastien.giraud=eds.com at python.org] De la part de Maxim Khesin Envoy? : mercredi 17 d?cembre 2003 23:41 ? : python-list at python.org Objet : is file open? I have a script that processes a file generated by another program. I need an unumbiguous way to know that the file has been written and closed by the other program, at least on Windoze. I am thinking of doing def CanOpen(fname): try: f = open(fname, 'a') f.close() return True except IOError: return False should this work OK? thanks, max -- http://mail.python.org/mailman/listinfo/python-list From skip at pobox.com Sat Dec 20 11:10:33 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 20 Dec 2003 10:10:33 -0600 Subject: UserLinux chooses Python as "interpretive language" of choice In-Reply-To: References: Message-ID: <16356.29817.475535.87865@montanaro.dyndns.org> John> The biggest problem is that I think Python is beginning to sucumb John> to the "we're better so we don't have to try harder" syndrome. John> One of these days, someone is going to start chewing up the user John> base, and for a while it looked like Ruby might have been it. >> Can you give some concrete examples which support your contention? John> I think the discussion on this thread is a reasonably good example John> [grin]. John> The responses to my comment about method calls with no arguements John> should say everything that needs to be said about attitude. Not really. You're holding this discussion on comp.lang.python, not on python-dev at python.org. I interpreted your statement about not having to "try harder" as being aimed at the people who work on the language and the standard library. Perhaps I was mistaken. In any case, I don't see it as necessarily a bad thing that there are multiple languages out there with overlapping features and audiences. They absorb some ideas but not others, and when they do they don't absorb them in precisely the same way. You can interpret that as not trying harder, but I don't. Python's design doesn't admit the option of calling functions without the parens. Perl's and Ruby's do. On the other hand, functions are first-class objects in Python. I don't know about Ruby, but in Perl, whether or not a function is called or treated as a piece of data is very context-dependent, to the point of near madness for people like myself who don't use it day in and day out. John> Let's skip the fluf and get to the crux. There are four languages John> (not counting minor entries) in the space Python occupies. John> Larry Wall (Perl): There's more than one way to do it. John> Guido vanRossum (Python): There should only be one obvious way to John> do anything significant. John> Metz (Ruby): I want a language that's both productive and fun to John> program. John> John Osterhout (TCL). I want a language I can embed in tools as a John> common scripting language. John> Notice that there is only one polarity here: Perl vs Python. Ruby John> goes meta on the discussion in that it looks at what the customer John> (the developer) *wants*, rather than what the language designer John> thinks they should have. Different design philosophies result in different languages. That's to be expected. If Ruby floats your boat, use it. Advocate for it if you like, but don't expect that because you like Ruby's philosophy better that Python necessarily ought to move in that direction. I happen to think Python is both productive and fun to use. But that's just me. John> Most businesses would look at a competitor who is stealing John> customers as an opportunity to figure out what those customers John> want that they aren't getting. Who's stealing customers? This is open source. We have no shareholders or board of directors to appease. We scratch our own itches. If Ruby relieves itching for more people than Python, so be it. Nobody's going to go out of business because of it. John> The jihad against the "functional" builtins is a good case in John> point. The replacements for apply, map and filter seem to be John> adequate, and in the case of list comprehensions, pretty darned John> useful although I think that it's a rather baroque addition to an John> otherwise very clear and comprehensible language. Why do you call it a "jihad"? Guido has stated on multiple occasions that he regretted adding functional constructs to the language. I still can't get to the Python website (have to wait another two hours for my ISP to reload its tables), but here's a Google pointer to an HTML-ized version of his OSCON 2002 Powerpoint slides: http://216.239.41.104/search?q=cache:2QztD1KncJgJ:www.python.org/doc/essays/ppt/regrets/PythonRegrets.ppt+OSCON+%22python+regrets%22&hl=en&ie=UTF-8 John> On the other hand, claiming that sum() is an adequate replacement John> for reduce() is so silly that it borders on the absurd. No, operationally that's a correct statement. People have looked at the use of reduce() in a number of different contexts. In all but the rarest of cases, reduce() was used to sum a list of numbers. sum() is a perfectly adequate replacement in all but those rare cases and is easier to read as well. As Guido mentioned in the talk I referenced above: reduce() nobody uses it, few understand it a for loop is clearer & (usually) faster John> The only explanation I can come up with for that level of John> absurdity is a desire to get rid of a feature, regardless of what John> it looks like. In other words, a jihad (holy war.) No, it's simply not used very much. Python never has been a very strong functional language. It's always been a very strong object-oriented language. Use it the way it's strongest. John> There is no replacement for lambda in sight, even though lambda is John> arguably the ***largest single*** one of the functional constructs John> that needs work, and has obviously needed work for a long time. Once again, you desire Python to be something it is not. If you want a strong functional language, program in Lisp or Haskell. John> The obvious replacement for lambda, which is some form of inline John> block, has not been seriously discussed, with proposed syntax and John> examples, anywhere I've seen it. Clearly, I'm not ominiscient, so John> that doesn't mean it hasn't, though. Anonymous blocks are not a replacement for lambdas, named functions are. How do you pass parameters to an anonymous block? John> The PEP 308 mess has left a rather sour taste in a lot of people's John> mouths: there was a clear majority in favor of doing *something*, John> but the voting was rigged (although I doubt if it was done John> deliberately) to make certain that no single proposal would get a John> majority. Again, it's something that doesn't fit easily into Python's design. There were several ternary operator proposals advanced, but none was a clear winner. Guido's a conservative language designer for the most part. It's better to leave it out than to put something in you'll regret later. PEP 308 wasn't the first time the ternary operator discussion has come up, by the way. Functional programming, ternary operators, anonymous code blocks. They've all been issues for a long time. You seem to have a burr under your saddle about this stuff. I'm not sure why. Maybe it's time to get out the curry comb... Skip From gregm-news at toadmail.com Sat Dec 20 20:13:39 2003 From: gregm-news at toadmail.com (Greg Menke) Date: 20 Dec 2003 20:13:39 -0500 Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> Message-ID: xah at xahlee.org (Xah Lee) writes: > i have a bunch of java files that has spaced-out formatting that i > want to get rid of. I want to replace two end of line characters by > one end of line characters. The files in question is unix, and i'm > also working under unix, so i did: Have a look at tr and sed. tr is also a handy tool for fixing Windows cr/lf madness. Gregm From mal at egenix.com Thu Dec 11 15:20:05 2003 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 11 Dec 2003 21:20:05 +0100 Subject: ANN: eGenix mxODBC Zope Database Adapter Message-ID: <3FD8D175.10402@egenix.com> ________________________________________________________________________ ANNOUNCEMENT EGENIX.COM mxODBC Zope Database Adapter Version 1.0.7 Available for Zope 2.3 through 2.7 on Windows, Linux, Solaris and FreeBSD ________________________________________________________________________ INTRODUCTION The eGenix mxODBC Zope Database Adapter (Zope DA) allows you to easily connect your Zope installation to just about any database backend on the market today, giving you the reliability of the commercially supported eGenix.com product mxODBC and the flexibility of the ODBC standard as middle-tier architecture. Unlike Zope's ZODBC Zope DA, the mxODBC Zope DA works on Windows XP/NT/2000/98, Linux, Solaris and FreeBSD using the same interface on all platforms. The mxODBC Zope DA implements high performance thread-safe connection pooling and multiple physical connects per logical Zope connection. You can safely run Z SQL Methods in parallel, achieving a much better throughput than ZODBC Zope DA or similar Zope database adapters under heavy load. This makes it ideal for deployment in ZEO Clusters and Zope hosting environments where stability and high performance are a top priority. ________________________________________________________________________ FEATURES * Zope Level 3 Database Adapter: the mxODBC Zope DA is fully multi-threaded and can handle multiple connections to multiple databases. * Fully compatible to Z SQL Methods. * Drop-in compatible to the ZODBC DA: the mxODBC Zope DA provides the same interfaces as Zope's ZODBC DA to allow a smooth upgrade path from this simplistic adapater to the high performance mxODBC Zope DA. * Fully compatible to the Znolk SQL Wizard Product and other similar products relying on the common database schema access methods .tables() and .columns(). * Connection Pooling: physical database connections are pooled and kept open, to reduce the connection overhead to a minimum. This is especially important for high latency database connections and ones like Oracle which take a considerable amount of time to setup * Parallel Execution of Queries on a single logical connection: the mxODBC Zope DA can manage any number of physical connections on a single logical connection. This enables running truly parallel Z SQL Method queries -- a feature not available in other Zope DAs. * Robust Mode of Operation: connections which have timed out or go away due to network problems are automatically reconnected. * Cross-platform Connection Objects: The Zope DA will automatically choose the right platform specific ODBC manager for you. * Per Connection Adjustable ODBC Interface: mxODBC comes with many different subpackages to choose from on Unix. The Zope DA allows you to select these subpackages on a per-connection basis. * Per Connection Error Handling: you can tell each connection whether it should report ODBC warnings or not; furthermore all warnings and errors are made available as list .messages on the DatabaseConnection object. * Transaction safe automatic reconnect: when the DA finds that a connection has timed out, it automatically tries a reconnect and replays the transaction on the connection (unlike other DAs which break the transaction scheme by doing a reconnect without replay). * Built-in Schema Cache: this results in improved performance under heavy load. * Database Schema Access: all ODBC catalog methods are made available for much better database schema inquiry. The catalog methods allow building generic database interrogation or manipulation tools and facilitates writing database independent Zope products. * Lazy Connect: the mxODBC Zope DA only connects to the database backends when a connection is actually requested. This results in a better use of resources compared to other Zope DAs. ________________________________________________________________________ NEWS Version 1.0.7 includes the following changes and enhancements: * Zope 2.7.0 and Python 2.3 are now fully supported. * The connection pooling was made more robust to allow less capable ODBC drivers to work nicely with the mxODBC Zope DA. * A new option was introduced to let the mxODBC Zope DA return empty strings instead of None for SQL NULL values. This should simplify porting applications to the mxODBC Zope DA. * A problem with the MS SQL Server was solved which caused deadlocks under heavy load in some application settings. In short: mxODBC Zope DA is continuing to become the number one solution for integrating relational databases with Zope applications. ________________________________________________________________________ UPGRADING If you have already bought mxODBC Zope DA licenses, you can use these license for the updated version as well. There is no need to buy new licenses. The same is true for evaluation license users. ________________________________________________________________________ MORE INFORMATION For more information on the mxODBC Zope DA, licensing and download instructions, please visit our web-site: http://www.egenix.com/ You can buy mxODBC Zope DA licenses online from the eGenix.com shop at: http://shop.egenix.com/ ________________________________________________________________________ Thank you, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 11 2003) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From t_therkelsen at hotmail.com Sat Dec 6 04:13:53 2003 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 06 Dec 2003 09:13:53 GMT Subject: Moving around in a string References: Message-ID: In article , Ryan Spencer wrote: [snip] > Well, I've gotten to an exercises where it wants me to write a translation > program that takes input from the user and translates it into either pig > Latin or something called "ubby dubby". It describes the basic rules and > all, and I somewhat understand in my mind on how to go about doing it, but... > > It requires me to, for the pig Latin part, remove the first letter and > move it to the end of a string (and then add ay to the end.) > > How should I go about "moving" to the end of the string? > > Just for clarification I want to do something like... > > Please enter a word: Orange > > rangeOay > > (taking the O and bringing it to end and then adding 'ay' to the end) This sounds suspiciously like homework, but... >>> foo = "Orange" >>> bar = foo[1:] + foo[0] + 'ay' >>> bar 'rangeOay' In other words, you can index strings the same way as any other sequence, [0] is the first element of the sequence, [1] the second, [-1] is the last, and so forth. See also the standard documentation on sequences: http://www.python.org/doc/current/lib/typesseq.html Regards, Troels Therkelsen From mfranklin1 at gatwick.westerngeco.slb.com Mon Dec 15 15:26:55 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 15 Dec 2003 20:26:55 +0000 Subject: build on AIX without Tk In-Reply-To: References: Message-ID: <1071520015.1096.3.camel@m-franklin> On Mon, 2003-12-15 at 19:38, Tennill, Dustin wrote: > Hello all, > > I am brand new to this list, not sure if this the right place to ask > this question. I have two AIX 5.1 64-bit boxes and would like to have > Python on both of them but don't need any of the graphical elements > (Tk/Tcl/Tkinter). One of the boxes happened to have Tk/Tcl stuff > installed on it, so I was able to build Python 2.3.2 without a hitch. > > The other box does not have Tk/Tcl installed, and I don't particularly > need it there. Below is the error message I get when attempting to make: > > building '_tkinter' extension > ./Modules/ld_so_aix cc_r -bI:Modules/python.exp > build/temp.aix-5.1-2.3/_tkinter. > o build/temp.aix-5.1-2.3/tkappinit.o -L/usr/X11R6/lib -L/usr/local/lib > -ltk8.2 - > ltcl8.2 -lX11 -o build/lib.aix-5.1-2.3/_tkinter.so > ld: 0706-006 Cannot find or open library file: -l tk8.2 > ld:open(): A file or directory in the path name does not exist. > ld: 0706-006 Cannot find or open library file: -l tcl8.2 > ld:open(): A file or directory in the path name does not exist. > *** WARNING: renaming "_tkinter" since importing it failed: from module > build/li > b.aix-5.1-2.3/_tkinter.so No such file or directory > error: No such file or directory > make: 1254-004 The error code from the last command is 1. > > > Stop. > > Is there any way to build without including tkinter support? (Or am I > just doing something wrong????) > > Thanks for any help at all . . . > Dustin, Did you use the same source code area for both builds? Clearly this install thinks you want to build Tkinter. I'm guessing that you didn't do make clean or make clobber before re-running configure for this machine.... New version of the python build system try to build extensions (like tkinter) only if supporting libraries are there... If you did do make clean (or indeed used a diffferent source area) then you should be able to simply comment out the _tkinter lines in the Modules/Setup file... then report this to python sourceforge page Regards, Martin. -- Martin Franklin From joconnor at cybermesa.com Mon Dec 1 12:07:24 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Mon, 01 Dec 2003 10:07:24 -0700 Subject: Python for web ? In-Reply-To: References: Message-ID: Fran?ois Pinard wrote: >[Jay O'Connor] > > >>black wrote: >> > > >>>2. If the answer of above is yes, then can we programms with Python in >>>both server and client side or either ? >>> >>> > >I guess yes to both. For my own usages, I use Python servers where >Python code is easily put within HTML pages. If I really wanted to have >Python executed on the client side browsers, I would likely follow the >Jython path, as Jython is Python over Java, and some Web browsers are >already able to run Java. (I did not really try Jython yet, however.) > > I'd forgotten Jython. >> First off, for any >>such HTML embedded scripting you have to have a server that while parse >>and execute the script. >> >> > >If you design carefully, the overhead could be quite negligible, besides >the cycles burned by the very execution of scripts. I would not really >see this as an impediment, in practice. > > I was mostly yhinking availibility, not performance. If you are using an ISP, then any server-side processing has to be enabled by the ISP and that may or may not be possible depending on your ISP > > >>More importantly, though, I'm not a big fan of the architecture of >>having HTML code interspersed with script coding. I think you'd end >>up with a better software design with a normal CGI-template approach >> >> > >Indeed. Templates allow a much nicer separation of the work between >the Web designers and artists on one side, and programmers on the other >side. Some templating systems are heavier than others (for both humans >and machines), one has to be careful when choosing or designing them. > > Same here. I do the backend programming and usually give the designer a page (See these marks? Don't touch them, the rest of the page is yours) Works well because I'm *not* a graphices designer and I get much better results when I make it work and I give it to a friend to make it look good. From mwh at python.net Fri Dec 19 18:10:37 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 19 Dec 2003 23:10:37 GMT Subject: Zen of ... References: <20031216183852.GA4318@nl.linux.org> <1071600670.1207.3.camel@emilio> Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article , > Michael Hudson wrote: > >Gerrit Holl writes: > >> > >> So the Zen of Python shouldn't *be called* the Zen of Programming. > > > >No, it should be called "19 Pythonic Theses", which has the advantage > >of being vaguely accurate... > > Actually, it should be called "20 Pythonic Theses", because that was > Tim's original title. But there isn't a 20th thesis yet is there? I thought that was still waiting on Guido... Cheers, mwh -- Windows 2000: Smaller cow. Just as much crap. -- Jim's pedigree of operating systems, asr From no.mail.please at se.invalid Sun Dec 28 08:28:42 2003 From: no.mail.please at se.invalid (Pjer Holton) Date: Sun, 28 Dec 2003 14:28:42 +0100 Subject: True standard Windows app in Python? Message-ID: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> If I were to build a Windows application that is a true standard Windows application in every conceivable way and that adheres to the MS Windows standards as much as possible (installation, GUI, printing, registry, RTF etc.), and if portability to other platforms is only a minor concern, ... would Python be a good choice? What packages, libraries and modules would you recommend for GUI, installation, data storage etc.? Thank you very much in advance for your advice! -- Pjer. From bokr at oz.net Sat Dec 13 22:05:07 2003 From: bokr at oz.net (Bengt Richter) Date: 14 Dec 2003 03:05:07 GMT Subject: connection to samba server References: <3fdbc954$0$218$e4fe514c@news.xs4all.nl> Message-ID: On Sun, 14 Dec 2003 03:33:31 -0800, "Przemo Drochomirecki" wrote: >very funny, ok, so now it sounds like this: >(damn smart way) > >I used Google to try to find "connecting to samba server"" on the Web, but I >got no useful hits. Does anyone know where I can find programming >information on this problem? > Which problem is your problem? Do you have a samba server running? On what? Do you have privileges to configure it (even though you don't have sufficient knowledge at this point)? What version of windows are you running? What connects the two? Are you trying to connect with a program or browsing "network neighborhood"? What makes you think there is a problem? What have you tried/observed? Why are we playing 20-questions? Regards, Bengt Richter From bill at rfa.org Sat Dec 20 20:09:16 2003 From: bill at rfa.org (Bill Eldridge) Date: Sun, 21 Dec 2003 02:09:16 +0100 Subject: Unicode from Web to MySQL In-Reply-To: <16356.44377.466955.783810@montanaro.dyndns.org> References: <3FE47726.90504@rfa.org> <3FE4796D.1010609@rfa.org> <16356.44377.466955.783810@montanaro.dyndns.org> Message-ID: <3FE4F2BC.5070901@rfa.org> Skip Montanaro wrote: > Bill> Note that I am able to do create Unicode data and insert it with a > Bill> carefully controlled unicode string > > Bill> data = u"Make \u0633\u0644\u0627\u0645, not war" > Bill> c.execute ( INSERT INTO junk (junklet) VALUES ('%s') ''' % > Bill> data.encode('utf-8','ignore') > > Bill> but this won't work with what I find on the Web. > >I suspect you either don't know the encoding of the data you find on the >web. Once you know that, you can convert it to unicode, then encode that as >utf-8, placing the result into the database. You should know the encoding >of the data from the Content-Type header. If that's missing or incorrect, >you should be able to make a reasonable guess based upon the non-ASCII >patterns you find in the data. > > > Encoding for example is a UTF-8 page Vietnamese, try: http://www.rfa.org/service/index.html?service=vie or http://www.rfa.org/service/article.html?service=vie&encoding=9&id=123655 I've tried grabbing this, doing vietstring.decode(None,'strict') gives an error (wants a string, not None), doing unicode(data,'unicode','replace') fails, unicode(data,'raw-unicode-escape','replace') somewhat works, I can then try unicode(data,'raw-unicode-escape','replace').encode('utf-8') but I get a SQL error at that point. (SQL statement is: ' Insert INTO test_utf8 (title) VALUES ( '%s') ' % data2 which if I put straight ascii text of some 1000 characters or so has no problem, Vietnamese gives me the SQL error. From jacek.generowicz at cern.ch Wed Dec 10 08:14:44 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Dec 2003 14:14:44 +0100 Subject: About the use of **args References: Message-ID: Zunbeltz Izaola writes: > Hi > > I'm starting a new proyect and i'm in doubt about diferent interfaces > for my clases. My clases will have a lot of attributes and i'm want to > know what aproach could be the best > > 1) Define one SetAttribute/GetAttribute pair of method for each > attribute. > 2) Define one SetAttribute/GetAttribute which argument is a key=value > format. > > Any advaice? 3) Not have any setters or getters at all. Ask yourself: "what is the point of getters and setters?". The most common answers are: a) Data hiding, privacy, etc. b) To protect myself against breaking the interface when I change the implementation of my object. c) Give you and your users typing exercise. In Python there is no enforced data hiding or privacy: you use a leading underscore in the identifier name to indicate to your users that something is _not_ part of the interface ... so (a) is irrelevant. As for (b), Python provides properties, which allow you to replace an attribute with a setter and/or a getter method, while maintaining the illusion that there is only an attribute. Properties also allow you to implement read-only (or write-only! (or delete-only!!)) attributes. (I won't comment on (c) :-) If you are a fan of Bertrand Meyer, you might also answer d) Attribute access and method calls should look the same. I'm not aware of a Python mechanism to make that irrelevant. From shalabh at gameboard.org Mon Dec 29 13:28:10 2003 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: Mon, 29 Dec 2003 18:28:10 GMT Subject: xmlrpc / SimpleXMLRPCServer and multi-threading References: <15c2d03b.0312290247.6a0bc41d@posting.google.com> Message-ID: <_m_Hb.4359$R_4.2181@nwrddc03.gnilink.net> Marco Aschwanden wrote: > How could the SimpleXMLRPCServer be turned into a multi-threaded > Server? Look for ThreadingMixin in the SocketServer reference. You should be able to create a new class derived from both SimpleXMLRPCServer and ThreadingMixIn to achieve a thread-per-request server. -- Shalabh From http Thu Dec 18 10:29:04 2003 From: http (Paul Rubin) Date: 18 Dec 2003 07:29:04 -0800 Subject: Small languages (was Re: Lua, Lunatic and Python References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> <7xwu8xes00.fsf@ruckus.brouhaha.com> <3FE1C42D.6050505@steinkuehler.net> Message-ID: <7xhdzycfgf.fsf@ruckus.brouhaha.com> Charles Steinkuehler writes: > Which is why I think that a small Forth kernel talking directly to the > linux kernel is the best solution. Forth is such a contorted language though, it's best to avoid it unless you're desperate. From tjreedy at udel.edu Tue Dec 30 10:44:54 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Dec 2003 10:44:54 -0500 Subject: HDD Burn In with Python References: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> <84fc4588.0312300019.41a81615@posting.google.com> <3ff15d8a$0$318$e4fe514c@news.xs4all.nl> Message-ID: "hokieghal99" wrote in message news:bss1jq$8qk$1 at solaris.cc.vt.edu... > Irmen de Jong wrote: > > > (although you could format the disk in one huge partition and > > then write random files to it until the disk is full). > > > > That's an idea. But what approach might one take if there were already > files and folders on the volume that should not be destroyed? Some type > of non-destructive test? You can start start with the root directory and use os.path.walk to read everything already the disk. You could also get the assembly coded SpinRite5 (<$100) which will systematically read and test every block, including boot sectors, on the disk (moving each block of data temporarily to another place while write testing). It also fixes bad formatting and has twice saved a disk for me that ScanDisk could not. Terry J. Reedy From gerrit at nl.linux.org Mon Dec 1 10:30:53 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 1 Dec 2003 16:30:53 +0100 Subject: gzipping several files In-Reply-To: References: Message-ID: <20031201153053.GB4181@nl.linux.org> Byrom, R (Rob) wrote: > Does anyone know how to read-in several files and then batch all together > into a *.zip format? I've looked at the gzip module but I'm not sure how to > use this with several files. Any help gratefully received! The gzip module is about gzip, not about zip. Zip is different from gzip: zip is both an archiver and a compressor: it bundles several files into 1 file, *and* compresses them. In Unix, there are two different protocols for that: archiving is done with tar (tarfile[0]), compressing is done with gzip or bzip[1]. If you want to create a zip file, you may use the zipfile module ;)[2]. A good place to look for a module if you can't find it is the standard library documentation[3]. It is very useful! yours, Gerrit. [0] http://www.python.org/dev/doc/devel/lib/module-tarfile.html [1] http://www.python.org/dev/doc/devel/lib/module-gzip.html, http://www.python.org/dev/doc/devel/lib/module-bz2.html [2] http://www.python.org/dev/doc/devel/lib/module-zipfile.html [3] http://www.python.org/dev/doc/devel/modindex.html -- 273. If any one hire a day laborer, he shall pay him from the New Year until the fifth month (April to August, when days are long and the work hard) six gerahs in money per day; from the sixth month to the end of the year he shall give him five gerahs per day. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From tnienstedt at telesyn.com Thu Dec 4 11:04:37 2003 From: tnienstedt at telesyn.com (Ted Nienstedt) Date: Thu, 4 Dec 2003 11:04:37 -0500 Subject: stddev bug in util.py Message-ID: <000a01c3ba80$515103f0$421210ac@telesyn.corp> Gentlemen, et al: The stddev function in the current, as of 11/03, utils.py module has a bug. Corrected code excerpt below, in red; comments in blue. Ted Nienstedt tnienstedt at telesyn.com def mean(values): """Return the arithmetic average of the values.""" return sum(values) / float(len(values)) def stddev(values, meanval=None): """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) #return math.sqrt( sum([(x - meanval)**2 for x in values])) # the above was missing the crucial divide by n-1 ! return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.com Mon Dec 15 09:37:50 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 15 Dec 2003 14:37:50 -0000 Subject: Python vs Unix shells References: <2ae25c6b.0312130213.2f5452c6@posting.google.com> <2ae25c6b.0312140316.77f7059f@posting.google.com> Message-ID: In article <2ae25c6b.0312140316.77f7059f at posting.google.com>, Paddy McCarthy wrote: . . . >> > This is really a comment on "Python in Systems Administration: Part I >> > -- Better Scripting" >> > http://www.samag.com/documents/s=8964/sam0312a/0312a.htm >> > by Cameron Laird. . . . >I was expecting replies of maybe "the pressures of getting an example >to fit the article made his example maybe a little artificial" (but >still useful). or people agreeing or disagreeing with the idea of >modules that are also Unix scripts. . . . As I read your comments, you do a good job of answering all the questions yourself. In other articles, I've said a few words about the difficulty of writing good examples for an audience of systems administrators; I do find it hard not being "maybe a little artificial" (I appreciate your gentle touch), without complexification that loses the reader. Your posts challenge me, but in a good way. I do want to say that one of my favorite signs of health in Pythoneering is the tradition of using the "if __name__ == '__main__':..." idiom to compose source which is both importable and executable. So: can I enlist you to review my drafts? -- Cameron Laird Business: http://www.Phaseit.net From Mike at DeleteThis.Geary.com Fri Dec 5 12:20:09 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 5 Dec 2003 09:20:09 -0800 Subject: True, False, None References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> Message-ID: > Douglas Alan wrote: > > When you use a case-insensitive language, you do not typically > > use StudlyCaps at all, so you wouldn't ever write "myFunction". > > Instead, you would write "my_function" or "my-function", > > depending on the language. Peter Hansen wrote: > When *I* have used case-insensitive languages, I have certainly > used various forms of capitalization to represent different types > of information, such as functions or constants. I am definitely > not alone in this approach, as I have learned it from reading > others' code. In fact, mixed case names have always been very popular in the case-independent Pascal language. Just look at any Apple code. The original Mac toolbox was written for Pascal and it's full of MixedCaseNames. Mixed case names with an initial capital letter are sometimes even called PascalCase. http://www.google.com/search?q=Pascal+CamelCase http://www.google.com/search?q=PascalCase -Mike From __peter__ at web.de Mon Dec 22 14:16:42 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Dec 2003 20:16:42 +0100 Subject: Count Files in a Directory References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: hokieghal99 wrote: > The os thinks there are 12,204 objects in the path while Python > thinks there are 12,205 objects. If it's always one more directory then it could be the initial directory setpath (ugly name, by the way) that is counted by the os but not by your function. To fix it, you could initialize dir_count = 1 # instead of 0 Peter From tismer at tismer.com Wed Dec 10 22:50:53 2003 From: tismer at tismer.com (Christian Tismer) Date: Thu, 11 Dec 2003 04:50:53 +0100 Subject: Preview of a Stackless Zope Application Message-ID: <3FD7E99D.70108@tismer.com> Howdy, I made a little demo of Stackless Zope. It is just a quick hack to see how things can work. The example is a long-running Python method which "prints" lines to the browser. The key to this surprizing solution is tasklets, channels, and thread pickling. Let me know your thoughts... http://www.centera.de/tismer/stackless/zope_demo -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From ahmedmo at wanadoo.fr Fri Dec 26 09:35:49 2003 From: ahmedmo at wanadoo.fr (Ahmed MOHAMED ALI) Date: Fri, 26 Dec 2003 15:35:49 +0100 Subject: Question about functions References: Message-ID: Hi, don't use the form "from A import" instead use the form " import A" and then use A.Product to modify the "Product" variable. Ahmed "Aubrey Hutchison" wrote in message news:I_2dnalUksLsg3GiRVn-uA at comcast.com... > Question about functions: > > 1)--- module "A" contains the following > X = 999666 #easy to notice value > Y = 111222 #easy to notice value > Product = 69696969 #easy to notice value > > def DoSomething(): > global Product,X,Y > Product = X*Y > return 0 > > module imported > from A import * > > 2)--- toplevel code > > def Mult(): > global Product,X,Y > DoSomething(): > return 0 > > """start of top level code """ > ... > ... > Product =Mult() > ... > print Product ( Result ----> print out is 69696...) > > Per "Python Nutshell" this appears to be the correct result. > How do you or can you modify the imported variables without using > classes objects? > > Aubrey > > From ark at acm.org Thu Dec 4 10:05:16 2003 From: ark at acm.org (Andrew Koenig) Date: Thu, 04 Dec 2003 15:05:16 GMT Subject: Hopelessly Lost And Desperate Newbie References: <20031204092605.01786.00000161@mb-m20.aol.com> Message-ID: > Hello, there. I'm desperately in need of assistance, because I can't figure > out how to get Python to work. Could someone help me with a program that can > examine textual input in pairs of letters, keep track of how often the letters > occur, and then write a random letter generator based on that input, do you? > I mean,....well, let's say that this thing (in its most primitive state) would > just count the occurances of a single letter. From the input, "a" occurs 12 > times, "z" occurs 3 times, "q" occurs once, "e" occurs fifteen times, etc. I suggest you start by writing a program that does just this part. Once you've gotten that far, post your program here and ask for suggestions on how to improve it. From alan.gauld at btinternet.com Sun Dec 28 19:50:52 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Dec 2003 00:50:52 GMT Subject: True standard Windows app in Python? References: <38mtuv84irng80akhinrd0k0uj0ic7sceq@4ax.com> Message-ID: <3fef7965.439576157@news.blueyonder.co.uk> On Sun, 28 Dec 2003 14:28:42 +0100, Pjer Holton wrote: > If I were to build a Windows application that is a true standard Windows > application in every conceivable way It depends on what the app does, there are some things you simply can't do with python in Windows even with winall installed. But then again there are things you can't do with MFC and C++. It depends what you are aiming for. > and that adheres to the MS Windows > standards as much as possible (installation, GUI, printing, registry, RTF > etc.), If you want to get the Windows "kite-mark" then probably Python is not the best solution, then again if you want to produce it quickly and cheaply... Pick the tool for the job. Most commercial apps on Windows are still written in C++ for performance reasons and because you get access to all the windows stiuff when you need it. But that comes at a significant price in terms of effort. > What packages, libraries and modules would you recommend for GUI, > installation, data storage etc.? If you do go down the Python route I'd recommend either the MFC stuff in winall, or maybe Qt or wxPython. They all use the native toolkit/API under the covers. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From tismer at tismer.com Fri Dec 12 10:37:00 2003 From: tismer at tismer.com (Christian Tismer) Date: Fri, 12 Dec 2003 16:37:00 +0100 Subject: Stackless 3.0 can pickle generators, now Message-ID: <3FD9E09C.6040707@tismer.com> What else should I say? You can pickle generators. Try it by yourself. CVSROOT=:pserver:anonymous at centera.de/home/cvs cvs co stackless -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From tim.one at comcast.net Thu Dec 18 15:06:23 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 18 Dec 2003 15:06:23 -0500 Subject: cleanup after exceptions In-Reply-To: <0%mEb.1392$HR.4074@news.indigo.ie> Message-ID: [Padraig at Linux.ie] > I'm a little confused why objects > are not deleted after they go > out of scope due to an exception? Because they don't go out of scope then -- named locals are still accessible by crawling over the traceback information available via the sys module. > For e.g. > > >>> import time > >>> > >>> def f(): > >>> myfile=open("file.test","w") > >>> myfile.write("not flushed\n") > >>> exception=throw > >>> > >>> f() > >>> time.sleep(10) At this point you can still get at myfile, because of the traceback info that still exists. You neglected to show us the NameError: global name 'throw' is not defined traceback produced if you actually run this. It's possible to recreate the entire call stack at the point of the exception from the traceback info, and from the call stack you can get to all the locals of all the functions on the call stack, so "myfile" is still reachable. See the docs for sys.exc_info(). Note that locals in Python have lexical scope but dynamic extent: this isn't like C or C++ in the latter respect. All objects stay alive in Python for as long as they're reachable by any means, and nothing is destroyed *just* because a function exits (not even the stack frame is necessarily destroyed then -- it *usually* is, but a traceback can keep it alive, and a generator "yield" statement keeps the frame alive deliberately). From tzot at sil-tec.gr Tue Dec 30 23:20:56 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 31 Dec 2003 06:20:56 +0200 Subject: Storing objects required by functions. References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: On 31 Dec 2003 04:07:01 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >>It's much more general to use new.instancemethod. See: >I think I did use new.instancemethod, through another door ;-) No doubt :) . *I* wasn't clear: new.instancemethod accepts any callable I throw to it, while not all callables have a __get__ method... >>>> foom(1,2,3,hi='Hello') > self='dummy self', args=(1, 2, 3), kw={'hi': 'Hello'} > >I didn't make voodoo out of it though. Interesting, but all that nested >calling at call-time seems like it would make for a performance hit? Unless maybe it is >all packed up in slots that C can get to very fast?? Actually, I think that most overhead lies in creating a frame object for the execution of a python callable. Calling C functions is fastest. I didn't spot any delays, but I didn't search thoroughly ;) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From garabik-news-2002-02 at kassiopeia.juls.savba.sk Mon Dec 8 08:49:54 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 8 Dec 2003 13:49:54 GMT Subject: sorting slovak utf References: Message-ID: Stano Paska wrote: > Hi, > > I have one problem. > In file aaa.txt I have slovak letters in utf-8. > ... > > I tried: > import locale > locale.setlocale(locale.LC_CTYPE, 'sk_SK.utf-8') > and > locale.setlocale(locale.LC_CTYPE, ('sk_SK', 'utf-8')) > but i got "unsupported locale" error > > What I must do to get correct sorting result? you probably do not have sk_SK.UTF-8 locale generated what OS, version are you using? What is the output of locale -a ? In some linux distributions, e.g. debian, you have to generate the locale beforehaned, with locale-gen (according to /etc/locale.gen file) -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From dima at xenon.spb.ru Wed Dec 24 17:09:47 2003 From: dima at xenon.spb.ru (Dmitry Rozmanov) Date: Thu, 25 Dec 2003 01:09:47 +0300 Subject: nonlinear least square In-Reply-To: References: <87ptefi9qj.fsf@pobox.com> Message-ID: Thank you for the link. It is of use for windows installation definitely. Regards. ---Dmitry. Chris Friedl wrote: > I recently found the Enthought python packages (2.2 & 2.3) which bundles a > whole lot of scientific/numeric/visualisation python code (see > www.enthought.com/python). Might be useful for you to get to the scipy > stuff. > > Merry Xmas > > > "Dmitry Rozmanov" wrote in message > news:bsaj7i$26om$1 at news.wplus.net... > >>John J. Lee wrote: >> >>Thank you for the suggestion. >> >>Yes, I do not like to have to install Scientific Python just for this >>purpose. As I understand it has some modules which have to be compiled >>anyway. >> >>I would be really grateful for any example code you provide. >> >>BWT do you know such a standalone code for nonlinear equations set >>solving? Newton's method or something. I mean in Python only. >> >>Thank you again. >> >>Regards. >> >>---Dmitry. >> >> >>>Konrad Hinsen's implementation in Scientific Python *is* in pure >>>Python, and as a consequence is probably about as simple as you're >>>going to get, I imagine. Is it dependencies on Scientific Python that >>>you don't like? If so, just dive in and remove them, if it's that >>>important to you -- I doubt you'll find a better pure Python >>>implementation. >>> >>>I can certainly testify that SciPy's MINPACK wrapper works fine, too. >>>I can dig out some example code if you like. >>> >>> >>>John >> > > From bwglitch at hotpop.com Fri Dec 5 22:40:39 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Fri, 05 Dec 2003 22:40:39 -0500 Subject: Python's simplicity philosophy In-Reply-To: References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: [snip] Welcome to my killfile. And stick with LISP. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- Fight for the good of all. -- Powermaster Optimus Prime with Apex Armor From forestiero at qwest.net Fri Dec 26 19:13:50 2003 From: forestiero at qwest.net (DogWalker) Date: Fri, 26 Dec 2003 16:13:50 -0800 Subject: _sre Import Error Python 2.3.3 Final Win98SE Message-ID: Python 2.3.3 failed to import the _sre [_sre.pyd] distributed with it. Said it couldn't find it but it could find, for instance, _csv which is in the same folder. I replaced the version of _sre.pyd of 2003Dec18 with the version of 2003Sep23 and the import succeeded. The windows installer added a couple of environmental variables: PYTHON_LIB looked suspect: c:\Python23\Libs\python22.lib I had the windows installer install Python 2.3.3 Final in the same folder as the previous version of Python2.3, creating backup copies of replaced files. Did I do something wrong? Should I replace other _sre files, too? From eddie at holyrood.ed.ac.uk Wed Dec 10 12:22:19 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 10 Dec 2003 17:22:19 +0000 (UTC) Subject: Building a new app in python and need some architecture advice. References: <5h7dtv4k4mmd1ovconager5lbggbv86jcr@4ax.com> Message-ID: Sam Watson writes: >>Since web browsers are so familiar to everyone it's still worth considering >>(assuming it can hack your 'rich' GUI client needs). I've written a couple of >>data entry web apps now based on BaseHTTPServer, one with state one without. >I hadnt given the web app idea a whole lot of thought only because my >experience with doing data entry with web pages has been pretty >dissatisfying. Depends on the app of course, a really demanding interface is difficult to make good even with javascript etc. but simple to just mildly complex can be done well. Only you can judge that of course. >>pretty damn secure. If you want to secure the app itself from snooping >>etc. then you might be able to use SSL on top of that (not sure, it's on my >>list of things to find out about). It's simple enough that you can get useful >>apps together quite quickly. For evidence of larger apps doing similar >>things, I believe roundup, which is a good system, works in the same way (but >>is obviously a lot bigger). >> >So apache is pretty easy to lock down? MY fear is i dont configure >apache correctly and leave something wide open. I should probably have been more explicit, when I say no external software I mean not even Apache (or any other web server). Applications like Roundup *can* use Apache but they can also run stand-alone. Basically you have a single program using BaseHTTPServer, which listens for HTTP requests and calls the appropriate method (GET, POST etc.) which you have subclassed in your app. So when the user enters a URL like http://blah/index, you take the path (after the host identifier) and go "Aha, he wants the index - I'll send him the HTML for the index page" or eg /form1 which is a HTML page that will probably contain a POST, when that POST comes in your do_POST method gets called, pulls out the fields (using http library functions) into a dictionary and you use that data. This is all a bit abstract so here's some code for a proof of concept that I made. When a user called http://my.machine:8000/scan it runs nmap on them (based on their IP address) and sends the result back. I don't have a short example with POST yet. import BaseHTTPServer, os # utils for making HTML def wrap (tag, txt): return '<%s>%s' % (tag, txt, tag) def mk_row (*cols): return wrap ('TR', ''.join ([wrap ('TD',a) for a in cols])) + '\n' # do the biz def scan_host (ip): x = os.popen ('nmap %s' % ip) res = x.read() x.close() return res class Handler (BaseHTTPServer.BaseHTTPRequestHandler): def do_GET (self): p = os.fork() if p == 0: return args = self.path.split('/')[1:] if args[0] == 'scan': self.doscan (args) else: self.send_error (403, 'Away and raffle') def doscan (self, *args): ip = self.client_address[0] dump = self.wfile.write self.send_response(200, "Script output follows") self.send_header ('Content-type', 'text/html') self.end_headers() dump ('\n') dump (mk_row ('host','%s' % ip)) dump ('
    \n') dump ('
    \n')                # pro tem
            dump (scan_host (ip))
            dump ('
    ') httpd = BaseHTTPServer.HTTPServer ( ('',8000), Handler) httpd.serve_forever() This code does a fork because of the length of time nmap takes to complete but that's optional, I do have an app that just handles each request serially - makes it easier to remove update conflicts and to retain state because it's the same code running in a loop. Hope that isn't too confusing. Eddie From deets_noospaam at web.de Wed Dec 10 10:56:49 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 10 Dec 2003 16:56:49 +0100 Subject: should i switch to IPYTHON interpreter? What is the killer feature of it? References: <87ekvdgig0.fsf@hugin.valhalla.net> <3fd6f329$0$209$e4fe514c@news.xs4all.nl> <7a7c50b80c9ade94550886eecf45d278@news.teranews.com> <3fd728e3$0$213$e4fe514c@news.xs4all.nl> Message-ID: > Sean was talking about the 'standard python shell' so I tried > the default python (2.3) on my mandrake 9.2 box. > It doesn't work, it just inserts a tab character. I use rlcompleter2 for this - in the standard shell. Very nice - but I think I've got to take a look at IPython, too. Diez From rob02omni at vodafone.it Tue Dec 23 11:30:55 2003 From: rob02omni at vodafone.it (Roberto) Date: 23 Dec 2003 08:30:55 -0800 Subject: Lanching application References: <%F6Eb.10980$Bl7.7345@news.cpqcorp.net> Message-ID: Hi Bengt, > > >>> import os > >>> def startit(path): os.system('start %s' %path) > ... well not really... Notepad is natively a multi-session program i mean it can run any number of itself cleanly. What i'm trying to accomplish is to launch an application that is not "multi-session". I know that this is possible (tricks in the process/applications threads) but i dont know how :) Any idea?? Thanks for reply! Rob bokr at oz.net (Bengt Richter) wrote in message news:... > On Fri, 19 Dec 2003 12:05:31 +0100, "Roberto" wrote: > > >I've tried win32api.WinExec but it seems to lanch application as single > >session. > > > >What i'm trying to do is lanch multiple session of a program that natively > >runs only in single session (i know that is possible). > > > >Any idea about this? > > > You mean like this? > > >>> import os > >>> def startit(path): os.system('start %s' %path) > ... > >>> startit('notepad') > >>> startit('notepad') > > (Two instances of notepad running at this point) > > Regards, > Bengt Richter From jjl at pobox.com Tue Dec 16 08:35:31 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Dec 2003 13:35:31 +0000 Subject: More than one cookie with urllib2 References: <8765gn2bpe.fsf@pobox.com> <3FD9D4E9.FE199F61@engcorp.com> <7xfzfphdzt.fsf@ruckus.brouhaha.com> <3FDDC1FD.6687FD2@engcorp.com> Message-ID: <874qw0zxzw.fsf@pobox.com> Peter Hansen writes: [...] > > Cookies aren't insane in concept, but their implementation leaves some > > things to be desired. > > Agreed... especially with IE6.1, where I still have an incredibly annoying > problem with a Zope-based Intranet where my cookies are being forgotten > periodically, which among other things has led to repeated data loss [...] Do you know why / when / which? Are these cookies in your browser or your users' browsers? Third party? Session or persistent? I ask because browser behaviour is the only standard in use, really. Guess which browser? Of course, cookies are "allowed" to vanish at random times. I remember reading something about servers telling browsers which cookies are important to users and shouldn't be thrown away, but I've completely forgotten where that was... John From http Tue Dec 30 16:45:13 2003 From: http (Paul Rubin) Date: 30 Dec 2003 13:45:13 -0800 Subject: NEWBIE: ishexdigit revisited References: <9ia1vv8gl3i9p3dlgbdim1d3lsd5rbk9tb@4ax.com> <7x3cb3mc5w.fsf@ruckus.brouhaha.com> <87ad5a2s08.fsf@strauser.com> <7x1xqmccda.fsf@ruckus.brouhaha.com> <871xqm2ekg.fsf@strauser.com> Message-ID: <7xbrpqgety.fsf@ruckus.brouhaha.com> Kirk Strauser writes: > >>> def retest(): > ... for i in xrange(1000000): > ... re.match(r'unlikely.*pat(..(.))?tern$', 'test') > ... > >>> def retest2(): > ... pat = re.compile(r'unlikely.*pat(..(.))?tern$') > ... for i in xrange(1000000): > ... pat.match('test') > ... > >>> start = time.time(); retest(); stop = time.time(); print stop - start > 5.28148591518 > >>> start = time.time(); retest2(); stop = time.time(); print stop - start > 1.04278099537 > > Pre-compiling the pattern is a huge win on my system. You're using an extreme example and seeing the cost of the cache lookup in the first example. You're certainly not seeing the pattern get recompiled a million times in 5 seconds. Doing would be many times slower. From SBrunning at trisystems.co.uk Mon Dec 1 06:45:31 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 1 Dec 2003 11:45:31 -0000 Subject: How to Extract the Control Name in VB Application Using Pytho n Message-ID: <31575A892FF6D1118F5800600846864D01200D67@intrepid> > From: bala [SMTP:blk at srasys.co.in] > Iam using python....to invoke VBApplication...in the VBApplication > contains lot controls...for Example > 1.TextBox > 2)CheckBox > 3)Button > 4)RadioButton > 5)ComboBox > 6)ListBox > > Outoff this six control....iam able to identify the Button,RadioButton and > CheckBox Control...But iam not able to find the TextBox,Combobox and > ListBox control name > What, exactly, dso you mean my 'name'? Are you using win32gui.GetWindowText()? If so, well, Text boxes etc don't *have* text, not as such. See http://www.brunningonline.net/simon/blog/archives/000664.html for how to extract the content of this kind of field. > iam able to find the handle for all the control... > Some of the Handle gives the Name and some of them is not giving the > control name.... > Example code? Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From rganesan at myrealbox.com Tue Dec 9 00:25:19 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Tue, 09 Dec 2003 10:55:19 +0530 Subject: from spam import eggs, spam at runtime, how? References: Message-ID: >>>>> "Ganesan" == Ganesan R writes: >>>>> "Fredrik" == Fredrik Lundh writes: >> spam = __import__('spam.eggs') >> eggs = spam.eggs > Is there a way to do this if I don't know about "eggs" beforehand. I have > some code which needs to import a DB module dynamically. The module could be > 'PyPgSQL.PgSQL' or 'sqlite'. Is there a sane way to do this without exec? db = __import__(dbname, globals(), locals(), ["connect"]) works. The last argument just needs to be a non-empty list. __import__ does not seem to do anything with it. Ganesan -- Ganesan R From TyBriD at si.rr.com Fri Dec 19 03:39:58 2003 From: TyBriD at si.rr.com (TyBriD) Date: Fri, 19 Dec 2003 08:39:58 GMT Subject: Newbie Question HELP! Message-ID: hello guys i am new top programming and was told python is the best place to start i so far understand variables ex: print ("Fill In Below") name = raw_input("Enter Your Name Please: ") age = input("Enter Your Age Please: ") print "Your Name Is", name print "Your Age Is", age but i was wondering if there was a way to compile a EXE file to display the print because this only seems to run in python shell, or is there a way to create my own interface for my program in python thanks in advanced From nessus at mit.edu Sat Dec 6 02:25:02 2003 From: nessus at mit.edu (Douglas Alan) Date: Sat, 06 Dec 2003 02:25:02 -0500 Subject: Python's simplicity philosophy References: <%N8tb.28277$hV.1041253@news2.tin.it> Message-ID: BW Glitch writes: > [snip] > Welcome to my killfile. And stick with LISP. Well, that's just about as eloquent and well-argued as anything you've posted on the topic so far. |>oug From hokiegal99 at hotmail.com Tue Dec 30 09:15:14 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 30 Dec 2003 09:15:14 -0500 Subject: HDD Burn In with Python In-Reply-To: <84fc4588.0312300019.41a81615@posting.google.com> References: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> <84fc4588.0312300019.41a81615@posting.google.com> Message-ID: Anand Pillai wrote: > I dont know of any application that currently does this. > > I think for applications that perform a lot of I/O, Python > might not be a good choice. The file I/O in Python is written > in optimized C, but still you would be better off writing > a C program for this, that is portable. For example, if you > are targeting only Unix/Linux platforms there wont be much > difficulty writing a portable C app optimized, say for the > gcc compiler. > > Since you have Windows also mentioned, I recommend Perl. > Perl is a bit faster than Python in system related tasks and > it is portable also. Python, though my favorite language comes > only second here. And of course, forget about Jython ;-) Speed isn't a huge concern for this test. Heck, it will take many hours or possibly a day or two depending on the size of the drive. I like Perl as well, but it's too convoluted. I sometimes look back at one month old Perl scripts and wonder what the heck they do. To me, that's scary. I have a close friend who heads up a large NOC at a big US university and they have banned Perl for this very reason. I only use Perl when there is no other option, and I think Python is a valid choice for this task. > If you do write your app in Python, perform benchmarks to > time the Python app itself. A good way to do this is by > using the 'Profile' class (of 'profile' module) by its 'calibrate' > method. This will make sure that the timings are done accurately. > This will be the major difference between a C app and a Python app, > since the C system calls are fast enough that their times can be > ignored. This is a good tip. Thanks, I'll try it. From bokr at oz.net Mon Dec 29 01:54:58 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Dec 2003 06:54:58 GMT Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <99dce321.0312282146.3c2c78ea@posting.google.com> Message-ID: On 28 Dec 2003 21:46:36 -0800, dw-google.com at botanicus.net (David M. Wilson) wrote: >engsolnom at ipns.com wrote... > >> Also, if I have a string 4 chars long, representing two bytes of hex, >> how can I *validate* the string as a *legal* hex string? >> >> isdigit works until string = '001A', for example >> isalnum works, but then allows 'foob' >> >> Is there a 'ishexdigit'? I could parse the string, but that seems >> "un-Pythonish" > > >Have you considered using the int() builtin? Here is an example: > > def is_hex(n): > ''' > Return truth if can be converted as hexadecimal > from a string. > ''' > > try: > int(n, 16) > return True > > except ValueError: > return False But that will accept '0x55' which I doubt the OP will like ;-) If you don't care about speed, (Not tested beyond what you see ;-) >>> def isHex(n): return bool(min([c in '0123456789ABCDEFabcdef' for c in n])) ... >>> isHex('005') True >>> isHex('0x5') False >>> isHex('0123456789ABCDEFabcdef') True >>> isHex('0123456789ABCDEFabcdefg') False Probably faster, depending on the C implementation: >>> def isHex(s): ... return not s.translate( ... '................................' ... '................................' ... '................................' ... '................................' ... '................................' ... '................................' ... '................................' ... '................................', ... '0123456789ABCDEFabcdef') ... >>> isHex('0123456789abcdefABCDEF') True >>> isHex('0123456789abcdefABCDEFg') False >>> isHex('0x5') False >>> isHex('005') True Regards, Bengt Richter From dw-google.com at botanicus.net Tue Dec 30 11:28:25 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 30 Dec 2003 08:28:25 -0800 Subject: HDD Burn In with Python References: <93f5c5e9.0312291536.7ba81c3b@posting.google.com> Message-ID: <99dce321.0312300828.69908074@posting.google.com> hokiegal99 at hotmail.com (hokiegal99) wrote... > I have Macs, Windows and Linux PCs. I'd like to have a generic HDD > burn in program to test new drives on all platforms. I know Python is > portable enough to handle the platform differences, but would it be a > good language for this type of application? The process would involve > lots of reads and writes all over the drives for an extended period of > time (several hours). Anybody else done something similar to this? Any > suggestions? Properly burn-in testing a hard drive via lots of seeks, reads, and writes etc. is something I wouldn't have thought Python was particularly applicable to. The problems I can see here are: - Python can't provide uniform low-level access to your disks. You can use the os module, or write your own uniform disk module, which would possibly be more effort than it was worth. - Using the os module to create a massive file, then doing seeks, reads, and writes around in it is not my idea of a good solution to the problem. You are also then including the underlying operating system's filesystem layer which will almost certainly be doing all manner of caching and additional journalling which you can't control. - Once you've solved the problem of uniform low level access in a 'disk' module, you also have the problem of ensuring that data actually hits the disk. The disk has buffers, and the os has buffers. If your targets are only *NIX/x86 and OS/X, then you are at least confined to a unix-style environment, which makes getting low-level disk access easy and the only problem is working out device file names. I'm not sure how fsync() works on file descriptors open on device files, but at a guess, I think you're going to have to try harder to make sure the data actually hits the disk (ioctls?). I don't think the problem is even confined to making sure writes hit the disk. You may have problems with the operating system caching reads too. Are the disks IDE-based? 99.9%+ of all modern drives manufactured have SMART capability, which has a lot of disk tests built into it, although I don't think it has the ability to do thorough write tests. On top of that, if you are expecting to use the burn-in tests for benchmarking too, the results you'll get will probably not represent the true performance of the drive in a platform-neutral way. HTH, David. From user at domain.invalid Wed Dec 3 06:51:07 2003 From: user at domain.invalid (user at domain.invalid) Date: Wed, 03 Dec 2003 13:51:07 +0200 Subject: Random traceback Message-ID: Is there any condition that would cause the following traceback: ++++++++++++++++++++ Traceback (innermost last): File "/tmp/multimeter.py", line 157, in ? myLogger.logMessage(message) File "/tmp/Logger.py", line 46, in logMessage self.__logToSyslog__(message) File "/tmp/Logger.py", line 85, in __logToSyslog__ syslog.syslog("%s" %reading) TypeError: [priority,] message string ++++++++++++++++++++ From bdesth.nospam at removeme.free.fr Wed Dec 10 20:10:58 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Thu, 11 Dec 2003 02:10:58 +0100 Subject: Upgrage openoffice to 2.3.3? In-Reply-To: <20031210182052.26181.00000472@mb-m15.aol.com> References: <20031210182052.26181.00000472@mb-m15.aol.com> Message-ID: <3fd7bff6$0$28702$626a54ce@news.free.fr> Allenabethea wrote: > Is there any advantage to upgrading the python distribution > which is part of OpenOffice to 2.3.3? > I notice it is version 2.2.2 > Are the bug fixes crucial? I didnt know that OOo included a Python distro... Anyway, you'll find the differences between Python 2.2.2 and 2.3.3 on the Python home : http://www.python.org As you'll see, it's much more about language evolution than bugfixes. Bruno From johnk at aurema.commercial Mon Dec 1 22:45:02 2003 From: johnk at aurema.commercial (John Ky) Date: Tue, 2 Dec 2003 14:45:02 +1100 Subject: Conflicting gethostname function definition on Solaris 9 References: <1069977306.415163@cousin.sw.oz.au> <1070335876.873683@cousin.sw.oz.au> Message-ID: <1070336715.351786@cousin.sw.oz.au> "John Ky" wrote in message news:1070335876.873683 at cousin.sw.oz.au... > To work around this, I had to do two things: > > 1. not defined "SOLARIS" > 2. put "python.h" first in the header file. Oops - I meant include "python.h" first before any other header from my *.cpp file. -John From jan at jandecaluwe.com Tue Dec 9 12:49:39 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Tue, 09 Dec 2003 18:49:39 +0100 Subject: cell object dereferencing In-Reply-To: References: <3FD5FD4A.9060406@jandecaluwe.com> Message-ID: <3FD60B33.5050205@jandecaluwe.com> Peter Otten wrote: > Jan Decaluwe wrote: > > >>Is there a way to dereference a cell object (that is, get >>the object that it references to) in Python? >> >>Regards, Jan >> > > > I appreciate messages from the future, cryptic as they may be. > So: what cell in what prison? > > Sorry, couldn't resist... Cell objects are afaik only documented briefly in the Python C API, so I understand the question may sound cryptic. For you knowledge, they exist today and are used to implement nested scopes. The guy able to answer (I hope) will probably understand the question immediately. Regards, Jan -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From skip at pobox.com Fri Dec 19 12:02:42 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Dec 2003 11:02:42 -0600 Subject: any one used googles api? In-Reply-To: References: Message-ID: <16355.12082.560095.485947@montanaro.dyndns.org> Bill> Has anyone used googles API who would be will to share a simple Bill> example. I have been wanting to play around with SOAP for a while Bill> and this looks like a place to start. Google for pygoogle. Skip From edreamleo at charter.net Mon Dec 15 19:11:18 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 15 Dec 2003 18:11:18 -0600 Subject: Leo 4.1 rc1 released References: Message-ID: > While the edit pane is fine I do want my favorite Vim... Is this possible > somehow? I mean to embed Vim in the window.. This is a reasonable thing to want to do. There are several possible approaches: 1. Run Leo from Vim. This is now possible in Leo's batch mode. When executed from the command line Leo uses a "null gui" so nothing gets put on the screen. You can optionally turn off all of Leo's log output, which would otherwise go to the console window. 2. Implement scintilla/scite using Leo's experimental wxPython plugin. Not quite the same as Vim. 3. Use something like pymacs to communicate between Emacs and Leo. This is in the daydream stage. Leo now has a Vim/Scite SIG and I welcome comments, ideas and code there. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From michele.simionato at poste.it Mon Dec 15 00:40:30 2003 From: michele.simionato at poste.it (Michele Simionato) Date: 14 Dec 2003 21:40:30 -0800 Subject: Python Cookbook question re 5.6 References: Message-ID: <95aa1afa.0312142140.3bc52827@posting.google.com> "Sean Ross" wrote in message news:... > I'm not exactly sure what Python's doing behind the scenes http://users.rcn.com/python/download/Descriptor.htm From jsbenson at bensonsystems.com Thu Dec 11 13:52:04 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Thu, 11 Dec 2003 10:52:04 -0800 Subject: What GUI toolkit looks the best? Message-ID: <045401c3c017$de925a60$0809500a@jsbwxp3> I've seen some pretty knockout, artistic GUIs in John Grayson's "Python and Tkinter Programming" book; you just have to look in the second half of the book for artsy and ray-traced interfaces. From tim.one at comcast.net Tue Dec 30 11:57:06 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 30 Dec 2003 11:57:06 -0500 Subject: Is Python Mac Centric??? In-Reply-To: Message-ID: [hokieghal99] > While trying to learn more about Python's standard modules, I noticed > that there are *a lot* of Mac only modules... more so than Unix and > Windows specific modules combined. Is there a reason for this? They're for the benefit of the "Mac Classic" OSes, and they exist because Jack Jansen devoted a large part of his life to supporting those beasts. > I am familiar with the Windows extensions by Mr. Hammond and wonder if > they'll ever become apart of the official Python distribution. Hard to say. Mark likes having a release schedule independent of Python's, and Guido hates Mark's coding style. Both act against folding the Windows extensions into the core. > It looks as if something similar already exists for Macs with all > these Mac only modules. Why is this? Jack doesn't like having a release schedule independent of Python's, and Guido doesn't hate Jack's coding style (Guido and Jack were coworkers at CWI, by the way). > Also, I've noticed that OSX 10.3 comes with Python 2.3 installed, That was Apple's decision, not "ours". > but that Windows XP does not. And that's Microsoft's decision, not "ours". We can't tell OS vendors what to ship, and all OS vendors are equally free to redistribute Python (the Python license extends that right to everyone who wants it). > Python installation is much more cumbersome on Windows. The user has > to dl Python and then Mr. Hammond's extensions to get up to speed > with the new Macs out of the box. I think you meant "Windows systems" rather than "Macs" there, but yes, that's true. Microsoft could bundle both, but they don't, and what MS ships is solely up to MS (well, up to them and hundreds of courts all over the globe ). > Does Python play favorites? It tries not to. In practice, it favors Unix-ish systems, mostly because a large majority of Python contributors run on Unix-ish systems, and because at least the open-source flavors of Unix-like systems are delighted to ship all the high-quality open-source applications they can. < I think it would have a much larger user base if Windows user got > what mac users get. It would, but why would Microsoft want to increase Python's user base? They probably see Python as a competitor to their own programming language offerings, and they make money from the latter. > Could someone explain this to me? Not every company is primarily concerned with your best interests . From ralf at brainbot.com Wed Dec 10 10:44:19 2003 From: ralf at brainbot.com (Ralf Schmitt) Date: Wed, 10 Dec 2003 16:44:19 +0100 Subject: Reading and writing Mozilla-mail in python References: Message-ID: <86ekvcad9o.fsf@stronzo.brainbot.com> Uwe Grauer writes: > Now i tried it under Linux (Suse 8.2) + self compiled python 2.3.2. > It works!! > So, what the hell is going on with my stupid win2000? maybe opening the file in binary mode helps (i.e. open(infile, "rb")) ? > > Has anyone seen this before? > > It think i'm going to reinstall the whole Shit. > > Uwe > > > Uwe Grauer wrote: >> Whats going on here. >> Could someone please verify this? >> I'm using python 2.3.2 on Win2000 SP4 + all patches >> Thanks, >> Uwe >> -- brainbot technologies ag boppstrasse 64 . 55118 mainz . germany fon +49 6131 211639-1 . fax +49 6131 211639-2 http://brainbot.com/ mailto:ralf at brainbot.com From db3l at fitlinxx.com Thu Dec 11 12:00:51 2003 From: db3l at fitlinxx.com (David Bolen) Date: 11 Dec 2003 12:00:51 -0500 Subject: polymorphism in python References: Message-ID: Jay O'Connor writes: > I actually ran into this recently with a Smalltalk application to > Postgresql. However, since Smalltalk allows you to add new behavior > to existing classes; I just added String>>asDBString and > Number>>asDBString. So my above code would look like: > > MyClass>>doSqlStuff:: filedName with: fieldValue > formatString := fieldValue asDBString. > > And it would polymophically get the right formatted string without any > type checking at all. While you could inject such a method with user defined classes, it's clearly a problem for built-in types. But one approach to achieve something similar in Python would be to define an interface (using a PEP 246-like approach such as PyProtocols) that contained the asDBString method, and explicitly adapt the arguments to the SQL function to that interface. You could then define (right in the module defining that interface if you like) very simple adapters for the built-in types that would let them be used without changing any calling code. So you could end up with a module like (I prefer the abstract class version of interfaces): - - - - - - - - - - - - - - - - - - - - - - - - - from protocols import Interface, advise, adapt class ISQLFieldValue(Interface): """Value to be used in a SQL operation""" def asDBString(self): """Return string representation valid for use in a query""" raise NotImplementedError class SQLAdapterString: """Adapter for string types""" advise(instancesProvide = [ISQLFieldValue], asAdapterForTypes = [str,unicode]) def __init__(self, ob, protocol): self.ob = ob def asDBString(self): return "'%s'" % self.ob class SQLAdapterNumeric: """Adapter for numeric types""" advise(instancesProvide = [ISQLFieldValue], asAdapterForTypes = [int,long]) def __init__(self, ob, protocol): self.ob = ob def asDBString(self): return str(self.ob) class MyClass: def doSqlStuff (fieldName, fieldValue): formatString = adapt(fieldValue,ISQLFieldValue).asDBString() return formatString - - - - - - - - - - - - - - - - - - - - - - - - - And once written, other objects could inherit the interface, and/or other modules could externally define their own adapters for other data types, and MyClass never needs to change. -- David From sombDELETE at pobox.ru Wed Dec 10 01:01:21 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Wed, 10 Dec 2003 09:01:21 +0300 Subject: python unicode display of chinese characters References: Message-ID: > "Posadas, Dennis" wrote in message news:... > Hi, > > I've done some google searching w/c referred me to a couple of > articles on unicode, but I'm looking for something really simple - not > for a web application. > > See my sample code below. Any ideas how to convert it to display > maybe Simplified Chinese ? The first idea is to debug input and output separately, i.e. save your Chinese text to utf-8 file in a Chinese-aware editor. Read it from your Python program and try to display. You're trying to use cp347 encoding, did you install it? My python installation does not have it. What console do you use? Are you sure it supports cp347? -- Serge. From jjl at pobox.com Wed Dec 10 08:56:18 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Dec 2003 13:56:18 +0000 Subject: Pyrex problem - Py_NoneStruct References: Message-ID: <878ylkydx9.fsf@pobox.com> "Gary Stephenson" writes: > I'm getting a clean generate, compile and link from my .pyx script, but when > I attempt to run the resultant .exe, I get: Hmm, what resultant .exe? Are you using py2exe or similar, or is there a feature of Pyrex I haven't noticed? I've always ended up with a .so / .DLL. > "The procedure entry point Py_NoneStruct could not be located in the > dynamic link library python23.dll" [...] Had this before, but forget what the problem is. Try posting some Pyrex code (the pyrex list is probably a better place than here). John From claird at lairds.com Mon Dec 22 19:50:40 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 23 Dec 2003 00:50:40 -0000 Subject: Singleton process References: Message-ID: In article , Benjamin Han wrote: >On Mon, 22 Dec 2003, Andrew Bennetts wrote: >> On Mon, Dec 22, 2003 at 01:38:27AM -0500, Benjamin Han wrote: >> > On Mon, 22 Dec 2003, Jp Calderone wrote: >> [...] >> > > import os, errno >> > > >> > > def shouldRun(): >> > > try: >> > > os.mkdir(MAGIC_PATH) >> > > except OSError, e: >> > > if e.args[0] == errno.EEXIST: >> > > return False >> > > raise >> > > return True >> > >> > But this solution creates a file race condition? >> >> How? mkdir is atomic. Either it creates the directory and succeeds, or it >> fails. I don't see any problems here. > >ok I see. The reason I'm thinking of using a lock file through fcntl is that >even if a lock file exists (maybe due to a crash of some sort before), using >the locking mechanism would still work. The "test if it exists" approach >would fail because of some leftover from some accidental 'death' of the process >before. > >Any more suggestion? Thanks. > Open a socket service. I expected Andrew to write that. Here's how I think about this: what does the OS itself manage as a process-referring singleton? Socket service! Only one server can be on a port at a time; that's exactly the expressed requirement. Apparently I haven't needed this yet in Python. If you're will- ing to read along in a foreign language, though, comments on Tcl-based implementations. -- Cameron Laird Business: http://www.Phaseit.net From vincent at visualtrans.de Fri Dec 12 13:07:48 2003 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 12 Dec 2003 19:07:48 +0100 Subject: Trouble building Python2.3.3c1 on WinXP: where's pythonnt_rc.h? Message-ID: Hi, I'm running into trouble building Python2.3.3c1 from source on a Windows XP machine. I'm getting C:\Python-2.3.3c1\PC\python_nt.rc(14) : fatal error RC1015: cannot open include file 'pythonnt_rc_d.h' Is this some magic involving "make_versioninfo.dsw"? What gives? I am lost here... Any pointers much appreciated. Regards, Vincent Wehren From jjl at pobox.com Tue Dec 23 15:01:56 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 20:01:56 +0000 Subject: nonlinear least square References: Message-ID: <87ptefi9qj.fsf@pobox.com> Dmitry Rozmanov writes: > I am looking for simple and convenient way to do nonlinear least > square fit from within Python. > > I know that there are such a modules in Scientific Python and SciPy > has it. But I would like to have it small and simple. Module with just > this functionality. It can be not very fast, but in pure python for > beter compatibility. [...] Konrad Hinsen's implementation in Scientific Python *is* in pure Python, and as a consequence is probably about as simple as you're going to get, I imagine. Is it dependencies on Scientific Python that you don't like? If so, just dive in and remove them, if it's that important to you -- I doubt you'll find a better pure Python implementation. I can certainly testify that SciPy's MINPACK wrapper works fine, too. I can dig out some example code if you like. John From djoh at yahoo.com Fri Dec 12 03:33:26 2003 From: djoh at yahoo.com (D. Johnson) Date: Fri, 12 Dec 2003 00:33:26 -0800 Subject: Make $$ now quick. THIS WORKS I SWEAR TO IT!! paid my tuition Message-ID: I found this on a bulletin board and decided to try it: A little while back, I was browsing through news groups and e-mails, just like you are now, and came across an article similar to this that said you can make thousands of dollars within weeks with only an initial investment of $6.00!! So, I thought, "Yeah right, this must be a scam," but like most of us, I was curious, so I KEPT reading. Anyway, it said that you send $1.00 to each of the six names and addresses stated in the article. You then place your own name and address in the bottom of the list at $6.00, and post the article in at least 200 news groups. (There are thousands) No catch, that was it. So after thinking it over, and talking to a few people first, I thought about trying it. I figured, "What have I got to lose; except six stamps and $6.00 right, right?" Then I invested the measly $6.00. WELL GUESS WHAT!!! Within seven days, I started getting money in the mail!! I was shocked!! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end of the second week I had made a total of more than $1000.00!! In the third week I had more than $10,000.00 and it's still growing!! This is now my fourth week and I have made a total of $42,000.00 and it's still coming rapidly. It's certainly worth $6.00 and six stamps, and I have spent more than that on the lottery without ever winning!!! Let me tell you how this works and most important, why it works.......... also make sure you print this out NOW, so you can get the information off of it, as you will need it. I promise you that if you follow the directions exactly that you will start making more money than you thought possible by doing something so easy!! Suggestion: Read this entire message carefully!! (Print it out or download it) Follow the simple directions and watch the money come in!! It's easy. It's legal. And, your investment is only $6.00 (Plus postage)!!! IMPORTANT: This is not a rip-off, it is decent; it's legal; and it is virtually no risk - it really works!! If all the following instructions are adhered to, you will receive extraordinary dividends. PLEASE NOTE: Please follow the directions EXACTLY, and $50,000 or more can be yours in 20 to 60 days. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. You will now become apart of the Mail Order business. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to income, which is made from people like you and me asking to be included in that list. Here are the four easy steps to success. STEP ONE: Get six separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 U.S. $1.00 bills and place ONE inside of EACH of the six pieces of paper so the bill will not be seen through the envelope (to prevent thievery). Next, place one paper in each of the six envelopes and seal them. You now should have six sealed envelopes, each with a piece of paper stating the above phrase, your name and address, and a $1.00 bill. What you are doing is creating a service. THIS IS ABSOLUTELY LEGAL!!!!! You are requesting a legitimate service and you are paying for it!! Like most of us I was a little skeptical and little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-238-5355) and they confirmed that it is indeed legal!! Mail the six envelopes to the following addresses: 1) W. Edens 4829 Bud Ln Lexington, KY 40514 2) L.Lessard 40 Martins Ferry Rd Hooksett,NH 03106 3) J. Safian 6950 W. Forest Presrv. Dr., #115 Norridge, IL 60706-1324 4) G. Takla 690 Adelaide Avenue East Oshawa, Ontario, L1G 2A8 5) Q. Huda 1212- 1315 Bough Beeches Blvd. Mississauga, Ontario, L4W 4A1 6) D. Jacobs 148 La Rue Rd. #243 Davis, CA 95616 STEP TWO: Now take the #1 name off the list that you see above, move the other names up (six becomes 5, 5 becomes 4, and etc.) and add YOUR NAME as number 6 on the list. STEP THREE: Change anything you need to but try to keep this article as close to original as possible. Now post your amended article to at least 200 news groups. : (I think there are close to 24,000 groups) All you need is 200, but remember, the more you post, the more money you make!! This is perfectly legal!! If you have any doubts, refer to Title 18 Sec. 1302 & 1341 of the Postal Lottery laws. Keep a copy of these steps for yourself and whenever you need money, you can use it again, and again. PLEASE REMEMBER that this program remains successful because of the honesty and integrity of the participants and by their carefully adhering to directions. Look at it this way. If you were of integrity, the program will continue and the money that so many others have received will come your way. NOTE: You may want to retain every name and address sent to you, either on a computer or hard copy and keep the notes people send you. This VERIFIES that you are truly providing a service. (Also, it might be a good idea to wrap the $1 bill in dark paper to reduce the risk of mail theft). So, as each post is downloaded and the directions carefully followed, all members will be reimbursed for their participation as a List Developer with one dollar each. Your name will move up the list geometrically so that when your name reaches the #1 position you will be receiving thousands of dollars in CASH!!! What an opportunity for only $6.00 ($1.00 for each of the first six people listed above) Send it now, add your own name to the list and you're in business!!! *****DIRECTIONS FOR HOW TO POST TO NEWS GROUPS!!!***** STEP ONE: You do not need to re-type this entire letter to do your own posting. Simply put your cursor at the beginning of this letter and drag your cursor to the bottom of this document, and select 'copy' from the edit menu. This will copy the entire letter into the computer's memory. STEP TWO: Open a blank 'notepad' file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into the notepad so that you will add your name to the list. STEP THREE: Save your new notepad file as a text file. If you want to do your posting in different settings, you'll always have this file to go back to. STEP FOUR: You can use a program like "postXpert" to post to all the newsgroups at once. You can find this program at . If you don't understand how it works you can email me at: mailto:andreass at orange.nl (this is only when my name is in the list, so send a copy of my address as well. put this in the header: make millions very easy + my full name) Use Netscape or Internet Explorer and try searching for various new groups (on- line forums, message boards, chat sites, discussions.) STEP FIVE: Visit message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done. Congratulations!!!!!! THAT'S IT!! All you have to do, and It Really works!!! Best Wishes From google at evpopov.com Wed Dec 3 09:56:06 2003 From: google at evpopov.com (popov) Date: 3 Dec 2003 06:56:06 -0800 Subject: In a function, how to get the caller object ? Message-ID: <7eecf173.0312030656.7aaf405e@posting.google.com> Look at this code: class C: def func(): .my_attrib = 1 func = staticmethod(func) C.func() c = C() c.func() In func, I would like to get C for the first call, and c for the second one, to be able to add a new attribute to this object (so that would add the attribute either to the class object or to the instance). How can I do this ? I tried to give a look to the inspect module with no luck. From google at daishi.fastmail.fm Fri Dec 12 19:45:45 2003 From: google at daishi.fastmail.fm (daishi) Date: 12 Dec 2003 16:45:45 -0800 Subject: Q: Meta-class usage References: Message-ID: Hi Michael, Thanks for the response. Some followup inline. Michael Hudson wrote in message news:... > google at daishi.fastmail.fm (daishi) writes: > > > Hi, > > > > I am wondering if someone could help me understand some of the > > details of using metaclasses. > > > > I am trying to use metaclasses to auto-generate some attributes > > and methods in a class definition. I am attaching a simplified > > example of the kind of code I am considering below, and I have > > the following questions: > > > > 1. Is the code in NamedType.__new__ the "right" way to have a > > class which has NamedType as its metaclass inherit from > > NamedClass? > > Apart from the fact that tuple(list(bases)+[NamedClass]) is a strange > way of spelling bases + (NamedClass,), yes. Thanks; I had forgotten about being able to do that w/ tuples. > > > Are the semantics different from if the class with NamedType as its > > metaclass explicitly listed NamedClass as a superclass in the > > standard way? > > Well, potentially, depending on where in the bases list you put > NamedClass. In general, it might be wise to not add NamedClass to the > bases list unless you need to (to avoid MRO calculation errors). I was/am having some difficulties understanding what happens here. E.g., in the example code that I gave if I make the class definition of NamedFoo to have an explicit superclass: class NamedFoo(object): I obtain the error: Traceback (most recent call last): File "", line 1, in ? File "meta2.py", line 28, in ? class NamedFoo(object): File "meta2.py", line 8, in __new__ return super(NamedType, mcl).__new__(mcl, name, bases, dictionary) TypeError: Cannot create a consistent method resolution order (MRO) for bases object, NamedClass If I add NamedClass to the beginning by doing: bases = (NamedClass,) + bases (instead of appending to the end of bases), I obtain the error: Traceback (most recent call last): File "", line 1, in ? File "meta2.py", line 32, in ? class SubNamedFoo(NamedFoo): File "meta2.py", line 8, in __new__ return super(NamedType, mcl).__new__(mcl, name, bases, dictionary) TypeError: Cannot create a consistent method resolution order (MRO) for bases NamedFoo, NamedClass (Note that the error is now for class SubNamedFoo instead of NamedFoo.) Now based on http://www.python.org/2.3/mro.html I believe this has to do with the fact that in the first case of NamedFoo we have merge([object], [NamedClass, object], [object, NamedClass]) (as opposed to merge([NamedClass, object], [object], [NamedClass, object]) when the modification to bases is changed) And the SubNamedFoo error arises because of merge([NamedClass, object], [NamedFoo, NamedClass, object], [NamedClass, NamedFoo, object]) Is this correct? (I just want to make sure that I am understanding what's going on correctly.) > > 2. Is the try/except clause in NameType.__init__ the "right" way to > > prevent KeyErrors for subclasses of classes with NamedType as its > > metaclass? > > I'd say so, but I'm not totally sure what you're trying to achieve... The basic idea of what I'm trying to do is (I think) fairly simple. I have several fairly similar class definitions that I want, and I was hoping to use metaclasses to make their definition more compact. (As comparison, I would use a #define in C or a defmacro in Lisp). I would like to use these classes once defined as if they were regularly defined classes, included subclassing. My initial attempt at subclassing with subclass class SubNamedFoo(NamedFoo) failed because of the fact that since the metaclass of SubNamedFoo inherits from NamedFoo and hence becomes NamedType, and the NamedType.__init__ is executed for SubNamedFoo also, which I didn't want - I would like SubNamedFoo to be oblivious of the fact that NamedFoo was defined using a customized metaclass. I was wondering what the ideal way to achieve this might be. > Cheers, > mwh Thanks again, d From andrew-pythonlist at puzzling.org Fri Dec 5 17:47:43 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 6 Dec 2003 09:47:43 +1100 Subject: xml-rpc/twisted question In-Reply-To: <3fd0ae8c$0$245$4d4ebb8e@news.nl.uu.net> References: <3fd0ae8c$0$245$4d4ebb8e@news.nl.uu.net> Message-ID: <20031205224743.GA1500@frobozz> On Fri, Dec 05, 2003 at 05:13:07PM +0100, Guyon Mor?e wrote: > Hi all, > > Below this message you can see my code. It is a modified version of the > twisted xml-rpc server examples. I am trying to figure out how to implement > non-blocking methods. I found out that I have to use 'defer' to do that, but > I have no clue how to do this. Unfortunately the documentation could not > make this clear to(unless I am missing some docs). I have already added a > function called xmlrpc_block to represent a actual 'blocking function'. > > I hope someone can show me how to modify this so the server does not block > any other clients when xmlrpc_block is called. You'll have better luck asking this sort of question on the Twisted list, at twisted-python at twistedmatrix.com... but here goes anyway :) [...] > def xmlrpc_block(self, duration=10): > """block the instance for a specified duration""" > import time > time.sleep(duration) > return "i slept %s seconds!" % (str(duration)) > Basically, you can't do any blocking operation in the main thread (unless it's acceptable to block your entire server!). Either resort to using threads: ---- from twisted.internet.threads import deferToThread from twisted.python import log def xmlrpc_block(self, duration=10): """block the instance for a specified duration""" import time d = deferToThread(time.sleep, duration) d.addCallback(lambda r: "i slept %d seconds!" % duration) return d ---- Or even better, don't use a blocking operation in the first place: ---- from twisted.internet.defer import Deferred from twisted.python import log def xmlrpc_block(self, duration=10): """block the instance for a specified duration""" import time d = Deferred() reactor.callLater(duration, d.callback, "i slept %d seconds!" % duration) return d ---- The trick with both of these is that Twisted's XML-RPC framework allows you to return a Deferred instead of a result. When you return a Deferred, Twisted won't return anything to the XML-RPC client until the Deferred is called -- it adds a callback to the Deferred to send the response. This gives you the oppurtunity to take as long as you need to answer the request without blocking the rest of your server. Note that Deferreds aren't magical. They are actually very simple objects that represent a "deferred result", with convenient hooks to add chains of callbacks (and "errbacks" for error handling) to them. In Twisted, when an operation is likely to take a long time, but the function you call to invoke that operation needs to return immediately, that function will return a Deferred. See http://twistedmatrix.com/documents/howto/defer for more information. -Andrew. From ababo_2002 at hotmail.com Mon Dec 29 09:28:08 2003 From: ababo_2002 at hotmail.com (Daniel Pryde) Date: Mon, 29 Dec 2003 14:28:08 +0000 Subject: Best match searching Message-ID: Thanks for the advice guys. I'll give it a try. One other thing I should mention is that, once a best match is found, the winner and its neighbours are changed slightly, and the euclidean distances have to be calculated again, so I'm not sure if a tree structure would be suitable for it. It's really a self organising map I'm trying to implement overall. Daniel _________________________________________________________________ Sign-up for a FREE BT Broadband connection today! http://www.msn.co.uk/specials/btbroadband From ptmcg at users.sourceforge.net Tue Dec 16 18:32:54 2003 From: ptmcg at users.sourceforge.net (Paul McGuire) Date: Tue, 16 Dec 2003 23:32:54 GMT Subject: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: Message-ID: "Skip Montanaro" wrote in message news:mailman.43.1071082685.9307.python-list at python.org... > > >> Probably because Stackless made it easier to write the server without > >> having to wrestle an async socket library such as Medusa or Twisted. > > Istvan> The question that needs to be answered is whether it would be > Istvan> worth to wrestle with those rather than locking out the vast > Istvan> majority of the potential users. > > I imagine Aaron provides the code (it is hosted on SF, after all). All you > need to do is port it to use Twisted or Medusa, then feed the diffs back to > Aaron. If it results in broader reach for xsdb without making the existing > code a nightmare to maintain, he'll probably fold it in. > > Skip > Well, actually, retro-installing Stackless isn't all that difficult. I had already upgraded to Python 2.3, but wanted to experiment with xsdb. I installed Python2.2 in its own tree, downloaded Stackless, and copied the compiled .libs into the Python 2.2 tree. Then went to the xsdb directory, and wrote a short setup.bat file to tweak my PATH to look at Python2.2 ahead of Python2.3, and then run the xsdb startup script. Now I can fire up an xsdb server using Python2.2+Stackless, and then hit at it from my mainline Python 2.3 client environment. Since this Stackless requirement would only be needed on server machines, this really shouldn't impair any serious deployment. xsdb has some very interesting features that, if they work out, will be well worth this minor inconvenience. -- Paul From reply.in.the.newsgroup at my.address.is.invalid Tue Dec 9 14:28:58 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 09 Dec 2003 20:28:58 +0100 Subject: from spam import eggs, spam at runtime, how? References: <8765gpudpm.fsf@pobox.com> Message-ID: John J. Lee: >Rene Pijlman: >> How do I do: >> >> from spam import eggs >> >> ... when 'spam' is only known at runtime? > >Why not just stick the import statement where you need it? Because I need a module from one of a number of different packages, at one specific point in my code. The modules are Cheetah templates (http://www.cheetahtemplate.org/) in different skins of a website. I've made one package per skin, and my website generator basically does: from skin import template where skin is only known at runtime (it's passed as a parameter or hidden field to my mod_python application). The alternative would be: if skin == 'basic': from basic import homepage elif skin == 'modern': from modern import homepage ... but this is unmaintainable and unpythonic. -- Ren? Pijlman From hokiegal99 at hotmail.com Tue Dec 23 08:42:37 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 08:42:37 -0500 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: Francis Avila wrote: > hokiegal99 wrote in message > <93f5c5e9.0312221718.23e42dac at posting.google.com>... > >>I was told earlier (w/o explanation) that functions should return >>something. I was under the impression that it was OK with Python to >>leave the return statement off. > > > Functions return something in Python, by definition. If you leave the > return statement off, Python inserts an implicit 'return None' to the end of > the text of your function. > > >>Could someone enlighten me on why or >>why not to use a return statement when defining functions? > > > This is a philosophic question. The final end of a function is to take > input and return output which is somehow based upon that input. The > functional *construct* can be abused every which way (often validly) to > violate any part of that statement: it can take arguments which don't > matter; it can return things which are unrelated to the arguments; it can > have all sorts of side effects that the caller isn't interested in, etc. > > >>Below is >>the bit of code I was told should return something: >> >>def fs_object_count(path): >> file_count = 0 >> dir_count = 0 >> for root, dirs, files in os.walk(path): >> file_count += len(files) >> dir_count += len(dirs) >> print "Number of Files Examined: ", file_count >> print "Number of Folders Examined: ", dir_count >> print "Total Number of FS Objects:", file_count + dir_count > > > The code is in poor style simply because it does multiple things at once in > a way that is not terribly modular: namely, it does file/dir counts, and it > prints results. > > Better would be this: > > def fs_object_count(path): > """Return (numdirs, numfiles) in path and its subdirectories.""" > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(path): > file_count += len(files) > dir_count += len(dirs) > return dir_count, file_count > > dn, fn = fs_object_count('mypath') > print "Number of Files:", fn > print "Number of Directories:", dn > print "Total:", fn+dn > > You can have more complex/prettier output logic if you want, but the point > is to make your functions as general as possible, while doing only one > thing. (And that's not a contradiction!) > -- > Francis Avila > This was very helpful to me. Thank you for taking the time to explain it!!! From martin at v.loewis.de Tue Dec 30 18:30:43 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 31 Dec 2003 00:30:43 +0100 Subject: selecting a random item from a set In-Reply-To: References: Message-ID: <3FF20AA3.7080603@v.loewis.de> Alexander Schmolck wrote: > Is there a better way? If not, how about something like Set.randompop()? In principle, random.choice "ought to" work. It doesn't, as it expects the set to be indexable. I would not like the Set type to grow random methods :-) Regards, Martin From deets_noospaam at web.de Wed Dec 3 18:26:13 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Thu, 04 Dec 2003 00:26:13 +0100 Subject: Turning f(callback) into a generator References: Message-ID: Hi, > This is a strange asymmetry, and I was wondering if I've overlooked a > simple way to transform a callback into a generator, but I now tend to the > assumption that you *need* threads: One thread with the callback puts > names or name lists into the queue until it's full (some arbitrary limit > that also determines the total memory needed), another thread (the > generator) consumes names from the queue. I also thought about that - its the only thing that allows for real lazyness - you can wait in the callback until the generator clears a semaphore. But if the context-changes are worth the effort is questionable. Diez From anton at vredegoor.doge.nl Wed Dec 17 13:08:54 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Dec 2003 19:08:54 +0100 Subject: Converting arrarys in Python to arrays in C References: <3fe06b14$0$25662$cc9e4d1f@news.dial.pipex.com> Message-ID: <3fe09bfe$0$3317$3a628fcd@reader2.nntp.hccnet.nl> Simon Foster wrote: >I have some code which attempts to convert Python arrays (tuples of >tuples of tuples...) etc. into C arrays with equivalent contents. > >The prototype code is shown below. > >My only question is, is there some way of doing this without repeating >the try..except blocks ad-infinitum to handle 3D, 4D arrays etc. > >I can see there is a pattern here but I can't seem to turn it into a >loop. Would a recursive solution do the trick? Probably yes, but why reinvent the wheel? Numeric does what you want already and allows for efficient conversions too [1]. Anton [1] For example, using your code as a basis: import Numeric def test(): cdata0 = 0 cdata1 = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) cdata2 = (( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 )) for cdata in cdata0, cdata1, cdata2: a = Numeric.array(cdata) print a.shape print a print if __name__=='__main__': test() From peter at engcorp.com Sat Dec 6 08:49:07 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 06 Dec 2003 08:49:07 -0500 Subject: Writing to the parallel port (Mem 0x378) when runnning WinXP or Mandrake 9.2 References: <9b849915.0312040054.66484ff1@posting.google.com> <04a7a1-s8r.ln1@dman13.dyndns.org> Message-ID: <3FD1DE53.850095EF@engcorp.com> Dennis Lee Bieber wrote: > > W98 system. It works, but I've not been able to track down and prevent > some OS preemption problem that occurs between 200 and 250 milliseconds > into a stream of output data. This is with the process upped to > REALTIME class, and the port "driver" thread upped to TIME_CRITICAL (a > combination that should have the thread running at priority 31!) Win98 is not a realtime OS, and it's unlikely you'll ever be able to fix this sort of thing completely. There are no guarantees whatsoever that your code, even at so-called "REALTIME" level, will have any particular latency. If you really need that kind of critical timing, you should use another OS. -Peter From fgeiger at datec.at Wed Dec 3 02:26:06 2003 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 3 Dec 2003 08:26:06 +0100 Subject: Chameleon ++ References: Message-ID: Have a look at Pike and ElastiC. They both offer scripting-like features. Probably you can find there some ideas. Cheers Franz GEIGER "Samuel Sagan" schrieb im Newsbeitrag news:cGdzb.37118$aT.29305 at news-server.bigpond.net.au... > Hi > I'm considering starting a new project at SourceForge, codenamed > 'Chameleon++'. > > The concept is to develop a set of C++ clases and functions that closely > mimmick the Python fundamentals: lists, tups, dictionnary, built-in > functions and, later, as many modules as possible. > > This would make it relatively easy to convert Python code into C++, using > mainly regular expressions and string replacement. > > In other words: compile Python apps via C++. > > Less important, but could come handy at times: the Chameleon++ subset of C++ > would make it very easy for people knowing Python to write in C++. > (Chameleon++ would not use pointers, etc -- only what we use in Python.) > > Among other things, Chameleon should also provide a pathway to .NET, since > C++ compiles to .NET. But the main goal remains to compile Python apps via > the C++ route. > > Before starting, any comments or directions you may have would be greatly > appreciated. > > Samuel Sagan > > > From dave at pythonapocrypha.com Fri Dec 5 12:43:43 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 5 Dec 2003 10:43:43 -0700 Subject: When is bare except: justified? References: <873cbzmbld.fsf@pobox.com> Message-ID: <065c01c3bb57$53b7d010$6500000a@YODA> > When *is* it justified to use except:, then? > > I've seen simple uses like this that seem fine (this one from Alex > Martelli, I think): [snip: example where code is probably too simple to contain a bug] > > Another reasonable use, in a straightforward debugging hack: > > try: > ... > except: > # use traceback module here to print out some detail of the exception > ... > raise > > > And: > > try: > use_dodgy_plugin_code() > except: > print "your plugin is buggy" The rule of thumb I use is that a bare except is bad if it hides the fact that an exception occurred. So, for example, using a bare except in code like this is okay: for worker in workers: try: worker.process() except: LogException() It's considered "okay" because even though the code prevents the exception from propagating, it doesn't lose record of the fact that something went wrong. We use these catch-all bare excepts in production code all the time to contain failures to as small an area as possible. One particular example where this is critical is in one application where we have a larger framework that also runs some custom code for each customer (like your plugin example). Although it's code we develop and own, we still have catch-alls around their execution so that the failure of one doesn't interrupt service of the others. There are actually quite a few cases like this for us where the reasons for partial failure are too many to enumerate, and we'd prefer to keep executing because the cause of the failure may go away over time and/or partial failure is preferrable to total failure. -Dave From davidcfox at post.harvard.edu Thu Dec 4 01:55:16 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Thu, 04 Dec 2003 06:55:16 GMT Subject: avoiding recursion in repr? In-Reply-To: <87oev6tu5s.fsf@pobox.com> References: <87oev6tu5s.fsf@pobox.com> Message-ID: John J. Lee wrote: > "David C. Fox" writes: > > >>The __repr__ methods of the built-in list and dict objects properly >>avoid an infinite loop when you take the representation of a list or >>dictionary which contains itself (or more complicated nestings: list >>l1 contains list l2 which contains l1, etc.). >> >>Looking at the CPython source code, it seems that the Py_ReprEnter and >>Py_ReprLeave functions are used to implement this protection. >> >>Is there any equivalent function for defining new container classes >>written in Python, or do potentially recursive containers have to be >>implemented in C? >> >>(I could of course try to translate these functions into Python, but >>I'm not sure that would catch mixed nestings of my class and >>list/dict). > > > What's a "mixed nesting"? For example an instance m of MyList containing a list l containing the same instance m of MyList... > > Couldn't you just use a dict to remember objects that have been seen, > like copy.deep_copy? No. deep_copy uses a memo argument (with a default value of None) to pass that dictionary around, but __repr__ for standard containers. Therefore, in the MyList example above, m.__repr__ can't pass such a dictionary when it calls the l.__repr__(), so when l.__repr__ calls m.__repr__ it doesn't get the extra argument. If I'm understanding the code for lists and dictionaries correctly, I think you need something global and thread safe (which is what Py_ReprEnter/Leave seem to be for). David From hokiegal99 at hotmail.com Fri Dec 12 14:42:25 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Fri, 12 Dec 2003 14:42:25 -0500 Subject: porting python script from linux to windows Message-ID: What are the specific steps that one should take to make a python script that works on a Linux x86 machine also work on a Windows x86 machine? I am using os, re and string in the script. How do paths differ between the two OSes? I am use to a unix-like path /blah/blah/blah. Would I need to change this to x:\blah\blah\blah where x = drive letter? What about creating fs objects? file works the same on both? os.walk works the same? Thanks for the advice!!! From kristofer at hotpop.com Wed Dec 3 09:11:21 2003 From: kristofer at hotpop.com (Kristofer Wouk) Date: Wed, 03 Dec 2003 14:11:21 GMT Subject: redirecting Stdin In-Reply-To: References: Message-ID: Jon Arter wrote: > Hi > Is is Possible to redirect the Python stdin in order to receive stdin > commands from a file ? > The time of redirection can last until exiting the Python and should > be transparent for python it self. > > with regards > Jon > > > > If you're on *nix I know you can do this: python myfile.py References: Message-ID: hokieghal99 wrote: > What are the specific steps that one should take to make a python script > that works on a Linux x86 machine also work on a Windows x86 machine? > > I am using os, re and string in the script. How do paths differ between > the two OSes? I am use to a unix-like path /blah/blah/blah. Would I need > to change this to x:\blah\blah\blah where x = drive letter? What about > creating fs objects? file works the same on both? os.walk works the same? Instead of using full paths, try using the os.path.join method. It makes it easier to port from/to any OS. -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "So you failed." "Absolutely!" "Completely." -- Optimus Primal, Rattrap, and Airazor, "Before the Storm" From munehiro at moc.emani.remove.and.reverse.it Tue Dec 9 09:40:14 2003 From: munehiro at moc.emani.remove.and.reverse.it (munehiro) Date: Tue, 09 Dec 2003 15:40:14 +0100 Subject: parsing equations Message-ID: hi all, i have a question. Given the string '3+2*6' i need to parse it and obtain the result, so 15. Does a module for this operation exists? i need to do simple operations, but also on floating point numbers. many thanks From pln at cosmic.stanford.edu Tue Dec 30 12:31:40 2003 From: pln at cosmic.stanford.edu (Patrick L. Nolan) Date: Tue, 30 Dec 2003 17:31:40 +0000 (UTC) Subject: Popen4 -> null lines on Windows References: Message-ID: vincent wehren wrote: > "Patrick L. Nolan" schrieb im Newsbeitrag > news:bsqil0$l3i$1 at news.Stanford.EDU... > | We have an application that works on Linux. It has to be ported > | to Windows XP, and there's one bug that's driving me crazy. > | There's a number-crunching program written in C++. It is invoked > | by a Tkinter python script. The script uses the threading > | module to separate out the heavy processing. The worker thread > | uses popen4 to run the C++ program and capture its standard > | output. This output is sent to the master thread through a > | queue and displayed by the gui. > | > | As I said, it works on Linux. On XP, every call to readline() > | on the program's stdout returns only a zero-length string. > | We are confident that the C++ program doesn't behave that > | way. We have tried both popen2.popen4 and win32pipe.popen4. > | > | Does this sound familiar to anyone? > The output doesn't contain any low values by any chance? Does this also > happen when the "mode" flag is set to "b" for binary? It works the same with both "b" and "t". -- * Patrick L. Nolan * * W. W. Hansen Experimental Physics Laboratory (HEPL) * * Stanford University * From imbosol at aerojockey.invalid Sat Dec 20 19:00:37 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 21 Dec 2003 00:00:37 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Rainer Deyke wrote: > > > Carl Banks wrote: >> You ideas about what a function's purpose is are just not relevant to >> whether the time of evaluation is consistent. > > I'm not talking about whether or not time of evaluation is consistent - > clearly either way is consistent so long as it is consistently used. I'm > saying that getting a fresh copy of default args is useless and dangerous > because it only helps with functions which shouldn't be written in the first > place. Well, ok. I don't agree that it's dangerous, and there are certainly useful functions that modify their arguments that could benefit from a fresh copy. def top_secret_code(a,b,c,stub=[]): stub.extend([f(a,b),g(b,c),g(c,a)]) return stub -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From secchi at sssup.it Thu Dec 4 15:04:20 2003 From: secchi at sssup.it (Angelo Secchi) Date: Thu, 4 Dec 2003 21:04:20 +0100 Subject: Simple newbie question In-Reply-To: References: Message-ID: <20031204210420.500dae81.secchi@sssup.it> Thanks a lot to everybody. Your points have been very useful. Angelo On Thu, 4 Dec 2003 15:50:45 +0000 (UTC) Duncan Booth wrote: > Angelo Secchi wrote in > news:mailman.107.1070547952.16879.python-list at python.org: > > > The code i'm using is the following: > > > > for line in lista: > > if sum(line == 0) > 0: > > lista.remove(line) > > > > > > The problem is that the loop stops at the first line with zeros and > > it doesn't remove the other lines with zeros (at least if I do not > > re-run the loop). Probably I do not understand how the loop works. > > The loop will assign the first element of lista to line, then the > second, then the third, and so on. > > The problem is that, if you remove an element everything after it > shifts up one place. Say you are looking at the first element and > remove it, what was the second element now becomes the first element, > but the next time round the loop you will look at the new second > element and the one that was originally second (and is now first) will > be skipped. > > The solution is never to work on the list you are modifying. Just make > a copy of the list and iterate over the copy, that means you can > safely modify the original. To copy a list, use the 'list' builtin. > > for line in list(lista): > if condition: > lista.remove(line) > > Alternatively turn your brain around and instead of deleting specific > elements from the list just build a new list with the elements you > want to keep. In this case you could do that using a list > comprehension: > > lista = [ line for line in lista if not condition ] > > (Obviously in both these cases replace condition with the correct > expression, which as Gerhard pointed out may not be the condition in > your original posting.) > > The list comprehension rebinds the lista variable, whereas your > original attempt was modifying the list inplace. This might be > significant if there are other references to the same list elsewhere > in your code. If it does matter, then you can still use a list > comprehension to mutate the original list: > > lista[:] = [ line for line in lista if not condition ] > > Unlike the original 'for' loop, this works by building a complete > replacement list then mutating the original list in one go. > > -- > Duncan Booth > duncan at rcp.co.uk int month(char > *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3""\6\7\xb\1\x > 9\xa\2\0\4"];} // Who said my code was obscure?-- > http://mail.python.org/mailman/listinfo/python-list From js at cis.uni-muenchen.de Tue Dec 2 03:19:53 2003 From: js at cis.uni-muenchen.de (Joerg Schuster) Date: 02 Dec 2003 09:19:53 +0100 Subject: leftmost longest match (of disjunctions) ; greediness of "|" References: <3FCB7C0B.D4B844AE@engcorp.com> Message-ID: Peter Hansen writes: > produce a longer overall match. In other words, the "|" operator is never > greedy. O.k. Thanks for pointing this out. Maybe I should have formulated my question differently: Is there a trick (be it dirty or not) to make "|" greedy in python? J?rg From newsgroups at jhrothjr.com Fri Dec 19 19:29:57 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 19 Dec 2003 19:29:57 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Ville Vainio" wrote in message news:du7ekv0z7g3.fsf at amadeus.cc.tut.fi... > I don't know if you have seen this before, but here goes: > > http://text.userlinux.com/white_paper.html > > There is a jab at Python, though, mentioning that Ruby is more > "refined". I'm not sure about refined, but it does seem to have several things that I think I'd like. One is a much better way of handling anonymous functions, aka "blocks." Another is the pervasive use of the visitor pattern, and a third is the ability to forget the empty parenthesis after a function/method call that doesn't require parameters. On the other hand, I'm mildly agnostic over the builtin function versus method issue. The biggest problem is that I think Python is beginning to sucumb to the "we're better so we don't have to try harder" syndrome. One of these days, someone is going to start chewing up the user base, and for a while it looked like Ruby might have been it. John Roth > > -- > Ville Vainio http://www.students.tut.fi/~vainio24 From tjreedy at udel.edu Thu Dec 11 13:54:24 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Dec 2003 13:54:24 -0500 Subject: nested function scopes References: <3fd83270$1@news.broadpark.no> Message-ID: "Nils Grimsmo" wrote in message news:3fd83270$1 at news.broadpark.no... > hi, > > i'm having some trouble nesting functions. consider the following: > > > def h(): > x = 1 > def g(): > print x # ok, x is taken from h > g() > > def f(): > x = 1 > def g(): > print x # this is not ok > x = 2 # this implies that x is local to g > g() > > h() # ok > f() # UnboundLocalError: local variable 'x' referenced before assignment ... > how do i declare that x belongs to the parent function, so that i can do > assignments to it? Currently you cannot. As you probably know, 'global' declares that x belongs to the module so you can assign to as well read it. This fall, there was an extended discussion on pydev (at least 30 posts, I am sure) on the subject of extending the idea of global to allow assignment to intermediate scopes. Would such be desireable? If so, what syntax? See python.org for B. Cannon's summaries or link to archives. Current bottom line: no change. > do i have to put it into a compound object? If compound = mutable collection, yes. Your example revised: def f(): x = [1] def g(): print x[0] x[0] = 2 g() The ease of doing this and the ugliness or other problems with proposed alternatives inhibits change. > it would be very handy to be able to do this if i have nested functions > that use a lot of varables. only passing the variables you assign to as > packed compound parameters is a bit ugly, since what subset of all > variables this is might change. You do not have to 'pass' the compound since you have read access to mutate it. > i cannot say i like the python scope rules yet. they probably are > practical, but they seem complicated an unstructured to me. They were simpler before nested scopes were introduced ;-). You can program without them if you wish. > take for example > > class C: > y = 0 > def f(self): > print y > which does not work unless y is a global. i understand and agree too why > y is not taken from the instance (self), because of the way classes and > instances relate in python. what i do not understand, is why y is not > taken from C, but from global, when nothing is specified. in the > previous example, with the functions h() and g(), g() took x from h(). > why should not f() take y from C? This is a different kettle of fish. Classes, though callable, are not functions and methods are not nested functions. Neither class nor instance methods can be called during class construction because neither the class nor instances thereof even exist. In any case, there is already a mechanism for accessing class attributes: C.y in this case. Use it. Terry J. Reedy From db3l at fitlinxx.com Thu Dec 11 18:32:17 2003 From: db3l at fitlinxx.com (David Bolen) Date: 11 Dec 2003 18:32:17 -0500 Subject: Converting a python script into a standalone application References: Message-ID: sandeep182 at hotmail.com (Sandeep Gupta) writes: > I've been referred to: http://www.mcmillan-inc.com/install1.html > > Which application would people recommend for creating a standalone > executable? I've been using the McMillan installer for a long time now very successfully, although there are others (such as py2exe) that are also available. You don't mention platform, but assuming your use of "executable" implies a Windows platform, if by standalone executable, if you mean a single .exe to run the application, you can create that with installer, but it'll still automatically unpack any needed extension dll/pyd files when it starts and remove them when it ends. If instead you mean a single .exe that can be used to install your application (like a normal Windows installer), then you can use normal installation packages to take the results created by installer and package them up. I'm a fan of Inno Setup (http://www.jrsoftware.org/isinfo.php) but there are others around (such as NSIS). BTW, if instead you were referring to a Unix (or MacOSX) platform then installer may be the only system to support them the way you want (and installer not necessarily on all Unix variants - Linux is probably the most tested). If you're talking about a Mac classic setup, I believe there is in fact some support for packaging up Python stuff for Mac installations, but other than vaguely remembering reading about it on a MacPython specific web page, don't know anything further. > Are there any licensing issues I need to consider wrt including a > "Python runtime" with my distribution? There shouldn't be - the Python license permits this even for commercial situations. You should double check however, that if your application involves any extension modules that are not part of the basic Python distribution that they may have their own more restrictive licenses. -- David From daniels at dsl-only.net Thu Dec 25 11:02:59 2003 From: daniels at dsl-only.net (sdd) Date: Thu, 25 Dec 2003 08:02:59 -0800 Subject: how to pass keyword arguments to derived class~ In-Reply-To: References: Message-ID: <3feb1641$1@nntp0.pdx.net> black wrote: > ... > class A: > def __init__(self, *args, **kw): > print args > print kw > print > class B(A): > def __init__(self, *args, **kw): > A.__init__(self, args, kw=kw) class C(A): def __init__(self, *args, **kw): A.__init__(self, *args, **kw) > a = A("a?", a_pro="a!") > b = B("b?", b_pro="b!") c = C("c?", c_pro="c!") Suggestion: Really use the standard python convention of 4 characters per indent. We promise not to charge you for extra spaces. This code was a trifle harder to cut out of the message and paste into idle to replicate. It also does help in reading code to trust there are no subtle indents. -Scott David Daniels Scott.Daniels at Acm.Org From sombDELETE at pobox.ru Fri Dec 12 17:14:53 2003 From: sombDELETE at pobox.ru (Serge Orlov) Date: Sat, 13 Dec 2003 01:14:53 +0300 Subject: Python code to replace shell scripts References: <3fd9832d.385255327@news.blueyonder.co.uk> Message-ID: "William Park" wrote in message news:brd7nv$264kc$2 at ID-99293.news.uni-berlin.de... > Alan Gauld wrote: > > On 12 Dec 2003 01:58:23 GMT, William Park > > wrote: > > > In any case, although Python does something well, shell does most > > > things better. (It's okey... I've got my helmet on.) > > > > Shell is generally better at quickly gluing together existing > > commands. But does so at a significant cost in machine resources and > > often execution time. Python provides a different approach that is > > generally better where the solution must be repeated often or where no > > suitable set of commands already exists. > > That is true, until you learn and program in shell. And that will be true again once you have handy module for gluing together cli applications. Since Python is not popular among system administrators, nobody was bothered to do it (yet?) From JTesser at nbbc.edu Sun Dec 7 18:47:55 2003 From: JTesser at nbbc.edu (Jason Tesser) Date: Sun, 7 Dec 2003 17:47:55 -0600 Subject: Python on web with mod_python Message-ID: <04875CB4331F0240A0AD66F970978651160A5E@paul> I am thinking about developing a CMS with Python and Postgres. I am developing on a Linux box with Apache 2. I have used PHP in the past but my at work we are considering going with Python as our main devellopment language. A few questions for you guys. 1. Is it best to just develop in all Pyhton or to use a mixture of PHP and Python? Why other than personal feelings? 2. What is the best way to template using Python for me to seperate content from logic? All the data that will be displayed in dynamic so I am not sure what the best way to template it would be in Python. Thank you for any thoughts offered. From clesh76 at comcast.net Wed Dec 10 23:08:28 2003 From: clesh76 at comcast.net (Charlie Lesh) Date: Wed, 10 Dec 2003 23:08:28 -0500 Subject: Drawing on the root window in Linux? Message-ID: Hey all: Is there any way to draw on the 'root' window? I'm thinking about a python screensaver for linux. I know that there are xlib bindings for python, maybe a little outdated, but do they have what I might need? Sorry if this has been asked before, but I couldn't find any answers, and Google was coming up empty. -Charlie From nilsgri at idi.ntnu.no Thu Dec 11 04:01:36 2003 From: nilsgri at idi.ntnu.no (Nils Grimsmo) Date: 11 Dec 2003 10:01:36 +0100 Subject: nested function scopes Message-ID: <3fd83270$1@news.broadpark.no> hi, i'm having some trouble nesting functions. consider the following: def h(): x = 1 def g(): print x # ok, x is taken from h g() def f(): x = 1 def g(): print x # this is not ok x = 2 # this implies that x is local to g g() h() # ok f() # UnboundLocalError: local variable 'x' referenced before assignment when i run this code i get: 1 Traceback (most recent call last): File "test.py", line 15, in ? f() # UnboundLocalError: local variable 'x' referenced before assignment File "test.py", line 12, in f g() File "test.py", line 10, in g print x # this is not ok UnboundLocalError: local variable 'x' referenced before assignment how do i declare that x belongs to the parent function, so that i can do assignments to it? do i have to put it into a compound object? it would be very handy to be able to do this if i have nested functions that use a lot of varables. only passing the variables you assign to as packed compound parameters is a bit ugly, since what subset of all variables this is might change. i cannot say i like the python scope rules yet. they probably are practical, but they seem complicated an unstructured to me. take for example class C: y = 0 def f(self): print y which does not work unless y is a global. i understand and agree too why y is not taken from the instance (self), because of the way classes and instances relate in python. what i do not understand, is why y is not taken from C, but from global, when nothing is specified. in the previous example, with the functions h() and g(), g() took x from h(). why should not f() take y from C? klem fra nils -- nils grimsmo "why is this thus? what is the reason of this thusness" - artemus ward From daniel.dittmar at sap.com Tue Dec 9 04:52:43 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 9 Dec 2003 10:52:43 +0100 Subject: Using the built-in cmd class References: Message-ID: Dipl. -Ing. Ashu Akoachere wrote: > Has any one got experience in using the built-in cmd class? I have > derived a subclass from the base class, but it seems as if the > arguments of functions using the cmd-interpreter are limited in their > number. Precisely' I have something like this: > . > .def help_add(self): > print "Adds arguments" > > def do_add(self,arg1,arg2): > return (arg1 + arg2) > > Python complains about the number of arguments in the do_add > function. Has anyone got a modified cmd that can handle multiple > arguments? The do_* methods get a string consisting of the remainder of the command line. So your method has to look like this: def do_add (self, strarg): intargs = [int (arg) for arg in strarg.split ()] print intargs [0] + intargs [1] If you return something true from a do_* method, the command loop will stop, this is probably not what you intended. You can do the split outside of all your do_* methods. This could be done by overriding the method parseline: def parseline (self, line): cmd, arg, line = Cmd.parseline (self, line) return cmd, arg.split (), line But if you really want to define the number of arguments in your do_add, then typing 'add 1 2 3' would lead to a TypeError exception, which is probably not helpful for the user. Daniel From op73418 at mail.telepac.pt Tue Dec 16 10:56:45 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 16 Dec 2003 15:56:45 +0000 Subject: introspecting builtin functions/methods Message-ID: Hi, Does anyone know if and how I can, from within Python, read the signatures of builtin methods/functions? The following fails: >>> import inspect >>> inspect.getargspec(list.append) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\inspect.py", line 655, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function >>> inspect.getargspec(list.append.__call__) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\inspect.py", line 655, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function Also: >>> for elem in dir(list.append): ... print elem ... __call__ __class__ __delattr__ __doc__ __get__ __getattribute__ __hash__ __init__ __name__ __new__ __objclass__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ gives no clue. TIA, with my best regards, G. Rodrigues From halloleo at noospaam.myrealbox.com Sun Dec 21 23:31:31 2003 From: halloleo at noospaam.myrealbox.com (leo) Date: Mon, 22 Dec 2003 15:31:31 +1100 Subject: no output of pyhton in emacs shell buffer Message-ID: hi there in an emacs shell buffer i get no output of python, even no ">>>"-prompt. however, behind the scene python still works, i can type a command blindly, and _after quitting python_ the associated output is written to the shell buffer. some shell config seems to be wrong. my shell buffer sttings are: (setq shell-file-name "bash") (setq explicit-shell-file-name shell-file-name) (setenv "SHELL" shell-file-name) (setq explicit-sh-args '("-login" "-i")) (setq shell-command-switch "-c") i work with ntemacs, the and the cygwin python 2.3.2 any idea? thanks, leo From jepler at unpythonic.net Fri Dec 5 15:15:39 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 5 Dec 2003 14:15:39 -0600 Subject: Turning f(callback) into a generator In-Reply-To: References: Message-ID: <20031205201530.GO11102@unpythonic.net> On Fri, Dec 05, 2003 at 07:42:22PM +0100, Peter Otten wrote: > How do you handle the case where the generator is not run to exhaustion? I didn't think about it or see your other message before I posted my code. I suppose you'd have to add some sort of communication in the opposite direction that causes cb to raise an exception instead of putting something in the queue. Something like: def delete(self): self.queue = None def __del__(self): if self.queue is not None: self.delete() def cb(self): if self.queue is None: raise AppropriateException ... def go(self): try: ... except AppropriateException: return # exit thread but this isn't quite right because delete must deal with a previous cb that is blocked, as well as races between 'delete' changing queue and cb using it. What you'd really want is a Queue subclass with a .shutdown() method: after a queue has been shutdown, any put() (including a blocked put in another thread) fails immediately with an exception, and get() (including a blocked get in another thread) fails immediately if the queue is empty. ... and __del__ still won't work because there are live references to self in the callback-thread. You'll need a container class that the thread doesn't reference whose __del__ takes care of doing the queue shutdown. Jeff From dek at compbio.berkeley.edu Fri Dec 12 12:44:16 2003 From: dek at compbio.berkeley.edu (David Konerding) Date: Fri, 12 Dec 2003 17:44:16 +0000 (UTC) Subject: win32 socket, "Operation not supported" Message-ID: Hello, I have written an app which opens a TCP connection to a server and uses a protocol to communicate with it. Specifically, I've written a python IMD client for the molecular dynamics application 'NAMD' (do searches for IMD and NAMD if you want to learn more). The protocol is very simple: both ends of the TCP connection can send messages to the other side at any time; when data is available on a read socket, a full packet (with known size) is read in a blocking fashion from the socket. This is used, on the client side, to make requests of the molecular dynamics engine (such as "speed up", or "slow down", or "quit"). The server side periodically sends updates on the state of the molecular dynamics engine (current step, atomic coords, etc). This all works fine on linux: I can connect, and send and receive messages as necessary. However, on Windows, I can connect and complete the initial handshake, and receive periodic updates, but when I try to send a message to the server, socket.send gets an "Operation not supported". >From my reading of the win32 docs, the socket send call returns this in a couple of situations: when a two-way socket had one half shut down and the send would have used the shut down direction, or when an out of band message was sent on a socket type which does not support it (such as UDP). Neither of these situations are true. When I re-code the app in C, the problem doesn't occur. Anybody got some suggestions? (PS: the socket I/O is set to blocking, and the Nagle algorithm is disabled). Dave From email at nowhere.foo Sat Dec 13 05:08:59 2003 From: email at nowhere.foo (Brandon Boles) Date: Sat, 13 Dec 2003 10:08:59 GMT Subject: beginner python cgi question Message-ID: Hi folks, I am trying to learn python, and have a form processing script giving me this error: Traceback (most recent call last): File "inquiry", line 16, in ? Address=fields["address"].value File "/usr/local/python2.2/lib/python2.2/cgi.py", line 550, in __getitem__ raise KeyError, key KeyError: address This is the snippet of code the error is referring to: ...snip... fields=cgi.FieldStorage() if (fields.has_key("name") and fields.has_key("emailaddr")): SenderName=fields["name"].value Address=fields["address"].value City=fields["city"].value State=fields["state"].value ...snip... I think what the problem is that if my form does not have one of the fields (except 'name' and 'emailaddr') with data in it, I get this error. What is the best way to fix this? Please be kind, this is my first attempt at python. Thanks for the help! Brandon From whiteywidow at yahoo.com Sun Dec 7 11:18:22 2003 From: whiteywidow at yahoo.com (RT Lange) Date: Sun, 07 Dec 2003 11:18:22 -0500 Subject: Instance Exception Oddity: Implicit and Explicit not the same? Message-ID: >>> class E1(Exception): pass >>> class E2(E1): pass >>> i = E2('foo') >>> raise E1(i) Traceback (most recent call last): File "", line 1, in ? raise E1(i) E1: foo >>> raise E1, i Traceback (most recent call last): File "", line 1, in ? raise E1, i E2: foo >>> Is there a reason the exception type is not the same? Is this behavior something that should be expected? -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From __peter__ at web.de Sun Dec 7 08:05:20 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Dec 2003 14:05:20 +0100 Subject: how to determine if files are on same or different file systems References: Message-ID: Kamus of Kadizhar wrote: > Peter Otten wrote: > >> No need to determine it beforehand, just try (untested): >> >> def movefile(src, dst): >> try: >> os.rename(src, dst) >> except OSError: >> shutil.copy2(src, dst) >> os.remove(src) >> >> >> Of course, if you are using Python 2.3 you should use shutil.move() as >> pointed out by Serge Orlov; the above was mostly posted to illustrate the >> popular concept "It's easier to ask forgiveness than permission", i. e. >> with Python's powerful exception handling mechanism you need not fear the >> failure of a particular code snippet, as long as you provide the >> appropriate error handling. > > Peter: > > I am copying 600mb - 1.2gb files over slow wireless to an NFS mount - > not exactly the model of reliability. It takes 40 minutes to an hour to > copy one of these. I am paranoid of failures - I don't want to lose > movies. > > So, I don't want to rely on innate error handling, because the failure > could come from wireless failure, and the copy could fail as well. > That's why I'm looking for a way to tell if a particular partition is > network mounted. > > The basic idea is that movies get moved on the same partition, but > copied (and not deleted) when moving between network mounted partitions > and local partitions. Deletes will be subject to manual review until I > get a comfort factor. > I still think that EAFP try: os.rename(src, dst) except OSError: # any error here will still result in a traceback # if not handled in client code shutil.copy2(src, dst) # os.remove() ommitted intentionally is superior style to LBYL (look before you leap) if isSamePartition(src, dst): os.rename(src, dst) else: shutil.copy2(src, dst) and fail to see the increased danger for your data. Plus, it saves you from writing the nonexistent isSamePartition() :-) Maybe you could replace the copy2() call with the invocation of some utility that reliably copies over an unreliable connection (maybe can someone else come up with a name), or you take the extra amount of work/time and compare the two files after you have copied them. >> >> Random remarks: >> - You might take a look at os.path.join() >> - Ok, this is paranoia, but I would ensure that ".avi" is only at the end >> of the string > > ".avi$" ? I still haven't figured out Python's string handling really > well. Or use the length of the string and count backwards? I admit, I > got lazy on this one. Use regular expressions only as a last resort. >>> import os >>> path = "/dir/name.ext" >>> os.path.splitext(path) ('/dir/name', '.ext') Putting it into a function: >>> def changeext(path, newext=""): ... return os.path.splitext(path)[0] + newext ... >>> changeext("/sowhat/movie.mpg", ".jpg") '/sowhat/movie.jpg' >>> changeext("/sowhat/movie.mpg") '/sowhat/movie' >>> changeext("/sowhat/movie", ".jpg") '/sowhat/movie.jpg' I you want to do it only with string methods: >>> path = "/one/two.three" >>> path[:path.rindex(".")] + ".four" '/one/two.four' However, you would have to ensure that the dot position is after the last slash. For a quick overview what is available for strings: >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] Peter From imbosol at aerojockey.invalid Fri Dec 19 22:55:22 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 03:55:22 GMT Subject: Default parameters References: <3fde309f$0$19285$626a54ce@news.free.fr> <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Bengt Richter wrote: > > > On Sat, 20 Dec 2003 01:43:00 GMT, Carl Banks wrote: > >>Paul Rubin wrote: >>> >>> >>> Carl Banks writes: >>>> Consider something like this: >>>> >>>> def func(param=((1,2),(3,4),(5,6),(7,8))): >>>> whatever >>>> >>>> Do you really want to be building a big-ass nested tuple every time >>>> the function is called? >>> >>> Come on, the compiler can easily recognize that that list is constant. >> >>Yes, but that doesn't account for all expensive parameters. What >>about this: >> >> DEFAULT_LIST = ((1,2),(3,4),(5,6),(7,8)) >> >> def func(param=DEFAULT_LIST): >> pass >> >>Or this: >> >> import external_module >> >> def func(param=external_modules.create_constant_object()): >> pass >> >>Or how about this: >> >> def func(param={'1': 'A', '2': 'B', '3': 'C', '4': 'D'}): >> pass >> >> >>The compiler couldn't optimize any of the above cases. > > For the DEFAULT_LIST (tuple?) and that particular dict literal, why not? Well, the value of DEFAULT_LIST is not known a compile time (unless, I suppose, this happens to be in the main module or command prompt). The literal is not a constant, so the compiler couldn't optimize this. (Remember, the idea is that default parameters should be evaluated at call time, which would require the compiler to put the evaluations inside the function's pseudo-code. The compiler could optimize default parameters by evaluating them at compile time: but you can only do that with constants, for obvious reasons.) >>Well, I don't have any data, but my gut feeling is this would be >>somewhat more than "miniscule" performance hit. Seeing how pervasive >>default arguments are, I'm guessing it would be a very significant >>slowdown if default arguments had to be evaluated every call. >> >>But since I have no numbers, I won't say anything more about it. >> > Don't know if I got this right, but > > [18:32] /d/Python23/Lib>egrep -c 'def .*=' *py |cut -d: -f 2|sum > Total = 816 > [18:32] /d/Python23/Lib>egrep -c 'def ' *py |cut -d: -f 2|sum > Total = 4454 > > would seem to suggest pervasive ~ 816/4453 > or a little less than 20% Well, if you don't like the particular adjective I used, feel free to substitute another. This happens a lot to me in c.l.p (see Martelli). All I'm saying is, default arguments are common in Python code, and slowing them down is probably going to be a significant performance hit. (You probably underestimated a little bit anyways: some functions don't get to the default arguments until the second line.) > Of course that says nothing about which are typically called in hot > loops ;-) But I think it's a bad idea as a default way of operating > anyway. You can always program call-time evaluations > explicitly. Maybe som syntactic sugar could be arranged, but I think > I would rather have some sugar for the opposite instead -- i.e., > being able to code a block of preset locals evaluated and bound > locally like current parameter defaults, but not being part of the > call signature. Well, personally, I don't see much use for non-constant default arguments, as we have them now, wheras they would be useful if you could get a fresh copy. And, frankly, the default arguments feel like they should be evaluated at call time. Now that we have nested scopes, there's no need for them to simulate closures. So, from a purely language perspective, I think they ought to be evaluated at call time. The only thing is, I very much doubt I'd be willing to take the performance hit for it. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From brian at sweetapp.com Wed Dec 17 05:01:57 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 17 Dec 2003 02:01:57 -0800 Subject: Is anyone using Python for .NET? In-Reply-To: Message-ID: <03b501c3c484$ce580cf0$0000fea9@dell8200> > For what sort of project? Unit testing for a C# application. Cheers, Brian From jdhunter at ace.bsd.uchicago.edu Thu Dec 4 15:30:22 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 04 Dec 2003 14:30:22 -0600 Subject: har har In-Reply-To: (John Hunter's message of "Thu, 04 Dec 2003 12:14:34 -0600") References: Message-ID: >>>>> "John" == John Hunter writes: John> # my python wrapping of pokereval -- results are exact This was not meant for python list and was accidentally sent; feel free to ignore! John Hunter From mesteve_b at hotmail.com Wed Dec 24 10:16:44 2003 From: mesteve_b at hotmail.com (python newbie) Date: Wed, 24 Dec 2003 15:16:44 GMT Subject: IDE for debugging References: <%thGb.1817$vz5.1144@newssvr27.news.prodigy.com> Message-ID: Ok, now I'm thinking _not_ Komodo, because it requires ActivePython, and I'd prefer to stick with my python.org installation of Python. If you still have advice as to what debugger you use for wxPython programs, I'd welcome the advice. "python newbie" wrote in message news:%thGb.1817$vz5.1144 at newssvr27.news.prodigy.com... > I need the ability to debug, so I think I'm learning toward buying Komodo, > however this would only be for straight Python. When I start building a > wxPython interface to my current program, will this work? > > Does anyone currently develop in wxPython and if so, are you using a > dependable tool for debugging in this? > > Thanks > Steve > > From leo at hiper.com.br Thu Dec 11 12:02:34 2003 From: leo at hiper.com.br (Leonardo Rochael Almeida) Date: Thu, 11 Dec 2003 15:02:34 -0200 Subject: [Zope-dev] Preview of a Stackless Zope Application In-Reply-To: <3FD7E99D.70108@tismer.com> References: <3FD7E99D.70108@tismer.com> Message-ID: <1071162154.3711.5.camel@localhost> On Thu, 2003-12-11 at 01:50, Christian Tismer wrote: > Howdy, > > I made a little demo of Stackless Zope. > It is just a quick hack to see how things > can work. The example is a long-running > Python method which "prints" lines to the > browser. > The key to this surprizing solution is > tasklets, channels, and thread pickling. > > Let me know your thoughts... > > http://www.centera.de/tismer/stackless/zope_demo This is very impressive. Can we get the rest of the source code? like, what is the definition of "channel_send()"? []'s Leo -- Ideas don't stay in some minds very long because they don't like solitary confinement. From jay at jaydorsey.com Sat Dec 6 22:07:32 2003 From: jay at jaydorsey.com (Jay Dorsey) Date: Sat, 6 Dec 2003 21:07:32 -0600 Subject: Accessing Python script with ColdFusion In-Reply-To: <6.0.0.22.2.20031206145251.052fc5c8@mail.stpo.com> References: <6.0.0.22.2.20031206145251.052fc5c8@mail.stpo.com> Message-ID: <20031207030732.GA22553@gentoo.Earthlink.net> On Sat, Dec 06, 2003 at 02:52:59PM -0800, Michael Wood wrote: > We're using mailman (python based) to do mailing lists. I'd like to write a > ColdFusion interface to the command line scripts for managing list > membership but there's a problem. I can run the scripts from the Linux > command line with no problem. But when I run the scripts via the CFExecute > tag in ColdFusion there isn't any output returned. That isn't entirely > true, if I use the -h argument the help screen displays okay but any other > sort of output never turns up. And it doesn't return an error so it seems > as though the script is executing or starts to execute but the output > buffer never flushes to the standard output or something like that... > > I'd really like to make this work. Does anyone have any ideas on how to do > so? > Have you made sure you specified a timeout in the CFEXECUTE tag? I just recalled a similar situation I encountered: http://lists.evolt.org/archive/Week-of-Mon-20030120/133253.html See if that helps any; esp. the use of the CFSAVECONTENT tag. I feel silly for not remembering this sooner :) -- Jay Dorsey jay at jaydorsey dot com From mwh at python.net Thu Dec 11 09:36:27 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 11 Dec 2003 14:36:27 GMT Subject: shy stackless Re: ANNOUNCE: xsdb -- the eXtremely Simple Database goes alpha References: <9a6d7d9d.0312101126.6b526167@posting.google.com> <7xwu93g759.fsf@ruckus.brouhaha.com> <7xisknr9nm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Robin Becker writes: > > I was just about to ask if generators allow for a stream like mechanism, > > but obviously if we're not allowed to change the generator state then it > > seems quite hard. > > Well, there's always global state. Or, if the generator is an instance method, instance state. Cheers, mwh -- Academic politics is the most vicious and bitter form of politics, because the stakes are so low. -- Wallace Sayre From MCollins at seminolecountyfl.gov Wed Dec 31 11:55:46 2003 From: MCollins at seminolecountyfl.gov (MCollins at seminolecountyfl.gov) Date: Wed, 31 Dec 2003 11:55:46 -0500 Subject: timing a web response using urllib.urlopen?? Message-ID: hi all, python newbie alert! i'm trying to open an array of websites, timing each site's response time (how may seconds until a response) if someone could point me in the right direction on accomplishing the timer part of the this application, i'd appreciate it. thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjorn.pettersen at comcast.net Sat Dec 27 16:26:05 2003 From: bjorn.pettersen at comcast.net (Bjorn Pettersen) Date: Sat, 27 Dec 2003 15:26:05 -0600 Subject: 2.3 list reverse() bug? References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> Message-ID: [posted and mailed] Arthur wrote in news:t0houvc69mtnlrmamh3klgvui8mbf1eu5t at 4ax.com: [...] > But this is also my approach, I guess. Not exactly writing Universe > Critical code, I tend to proceed with a light reading of the docs, and > learn by having my naive intuitions corrected - as necessary when > necessary, by finding something broken. My late boss approached languages and other problems the same way, and I never could understand how he dealt with what for me would be continous frustration. He seemed to have no problems with it though -- allthough there was the "what do you mean Python doesn't have a case statement?" meltdown that almost lead to an in-house Python dialect *eek*... Now, I'm not against a case statement in Python per se, but until one has experienced pattern matching in SML, one can't understand how inadequate the Pascal/C case/switch statements are -- and I _am_ against C style switches in Python (... and we all know how much my vote counts ). I'm more the kind of person that reads the user's manual to the VCR before ever putting a tape in (did I just date myself?). Doing language theory in grad school, while not always the most immediately useful, is a wonderful way to develop passionate ideas about how things ought to be (you should have heard the lunch discussions when Java came out ). > But there is I feel a valid point implicit in my original question. > > The "I have been using Python 42 years and never imported copy" is a > very ambiguous assertion,made time and again. You're most certainly correct, although I don't believe it was very ambigous when I stated it. If you look at my response to Alex, you'll see that I really do mean that copies are virtually never needed [in the aesthetic, not the Turing complete sense], and if you do use them you're likely to (a) do more work, sometimes potentially _much_ more work, (b) complexificate the algorithm making it harder to visually verify, (c) make it _much_ harder to _prove_ correct, and (d) you're adding another entity that you'll have to keep in memory when you're visualizing the system. [digressing, I never thought I'd feel the need to do algorithmic proofs until I started working for the people who give you your FICO score. The thought that we measure personal information in (a lot of) Tera-bytes, that we can store over 4000 individual pieces of data about a person and that a bug could make someones life severly miserable.. No wonder that for such a mission critical subsystem as the 'data-structure' managing this information we wouldn't use anything but a Python code generator, generating over 380KLoc of C++ code, SQL schemas and stored procs, etc.)]. Getting back to my point about copies, it is almost purely an aesthetic issue. You can get working code while creating copies all over the place without too much effort. If getting the code to work is the final goal, there is no place for what I call "clean" code. For me, working code hasn't been very exciting, probably since I saw the BSD sources long ago and was utterly flummoxed when the pinnacle of what I considered a big, complex "program" was easier to understand than what I was writing. I was immediately convinced that only clean code can be good code, and only good code can create exceptional systems. Being an aestethic quality, crafting clean code is more art than engineering, but listening to coders around me who wrote good code, and my own trial and error, I have no problem categorically denouncing the creation of copies. I can also categorically say that it's a really bad idea to walk to the middle of a bridge, precariously climb up on the railing, before doing a swan dive towards the dry riverbed several hundred feet below... but it's really fun if you have a bungie-cord attached. I haven't encountered any rules that didn't come with their own list of exceptions. However, while the exceptions _are_ important, focusing on them is perhaps misplaced. Taking an extra look when you're creating a copy has an amazing track record in languages with gc... as does removing functions bigger than 25x80, more than two levels of nested loops in a function, more than two sequential loops in a function, more than three levels of inheritance, almost all cases of multiple inheritance, classes with more than a dozen methods, inconsistent use of whitespace, etc., etc. Sure it is weird to want to think of such trivialities when the code is working, but clean code makes me happy , and hey, after 20+ years of programming, I'm still excited when I go to work and I still program after I come home... I hope you don't take my verbose mode as any kind of criticism -- while I have no problem voicing my opinion about how things should be, I never presume to tell someone else what to do (no desire, besides friends who disagree with me are much more interesting ;-) I sincerely do not grasp mentally however, how some people can "break path" in a new domain guided mainly by their intuition? My intuition definitely doesn't work at that level :-) If you have any meta-analysis it would be very interesting to contemplate... [...] > Don't we need to pick one meaning for that assertion? Or make the > meaning clear, when asserted. Of course not, this is USENET . I was going to put something here about the quote from Winnie the Pooh about "when I say ___ I mean ___", but googling for "Winnie the Poo" is not something anyone should do before lunch... seriously. Anyways, God Jul og Godt Nytt ?r allesammen, -- Bj?rn Steinar From david at rebirthing.co.nz Wed Dec 10 23:42:25 2003 From: david at rebirthing.co.nz (David McNab) Date: Thu, 11 Dec 2003 17:42:25 +1300 Subject: Drawing on the root window in Linux? In-Reply-To: References: Message-ID: <3FD7F5B1.4020207@rebirthing.co.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Charlie Lesh wrote: | Hey all: | | Is there any way to draw on the 'root' window? I'm thinking about a | python screensaver for linux. I know that there are xlib bindings for | python, maybe a little outdated, but do they have what I might need? Try xlib-python (or python-xlib). And welcome to a whole new world of pain. | | Sorry if this has been asked before, but I couldn't find any answers, | and Google was coming up empty. | | -Charlie | - -- Kind regards David - -- leave this line intact so your email gets through my junk mail filter -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQE/1/WxUuEuev/PjrcRAiznAJ9dk9T3A992rJ90rr9WwWMkAWQY8wCgwujA Klx2JpzsDb0ItSL33/wjy+s= =00GA -----END PGP SIGNATURE----- From cipher at be4mind.com Sat Dec 13 06:54:09 2003 From: cipher at be4mind.com (Matteo Memelli) Date: Sat, 13 Dec 2003 11:54:09 GMT Subject: hex and little endian Message-ID: Hello I'm getting in trouble.... I'm trying to convert an hex address like 0xbfffe2f1 in little endian format \xf1\xe2\xff\xbf. Is there any funcion that can make this? Whe I try to code somethig like this: "\x%s\x%s\x%s\x%s" % (string1, string2, string3, string4) I obtain this error: ValueError: invalid \x escape and if I escape the charachter "\" making something like this: "\\x%s\\x%s\\x%s\\x%s" % (string1, string2, string3, string4) It works but the resulting string is not an hex representation, I mean: >>> len('\xaa\xaa\xaa\xaa') 4 >>> len('\\xaa\\xaa\\xaa\\xaa') 16 Can anyone help me? Thank you very much in advance Matte From robin at jessikat.fsnet.co.uk Tue Dec 9 07:52:10 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 9 Dec 2003 12:52:10 +0000 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: In article , Duncan Booth writes .... >You obviously think something was wrong with my earlier timings, but I >can't understand from this what the problem was; timeit.py does some >reasonably clever things to try to give an accurate answer including >varying the number of times it repeats the test to ensure that the time per >loop is based on a reasonably large time interval. > not at all, I was puzzled by the reversal of earlier stuff. You're right about the comprehension as well, I had thought the variable was internal, but making it local gives the comprehension the edge. C:\tmp>\python23\python ttt.py list () = 1.72 list [] = 3.27 comprehension = 0.81 copy = 3.94 cCopy.copy = 1.59 lambda z: z[:] = 1.14 lambda z: list(z) = 4.73 lambda z: [] = 0.95 f=lambda z: [] = 0.95 like /F though I am extremely puzzled about the list result. -- Robin Becker From ask_me at gmx.de Wed Dec 24 10:11:40 2003 From: ask_me at gmx.de (=?iso-8859-1?q?Thorsten_R=FChl?=) Date: Wed, 24 Dec 2003 16:11:40 +0100 Subject: writing recursive lambda functions // Thank You References: Message-ID: Am Wed, 24 Dec 2003 12:33:46 +0000 schrieb JCM: >> def mapp(f): >> lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l)))) > > You're missing a return here: > > def mapp(f): > return lambda l: l and cons(f(car(l)),(mapp(f)(cdr(l)))) > > A common mistake if you're coming from lisp (I do it all the time). Thanks to you both for you?re quick answer... .. hehe obviosly an beginners mistake ;) Thank you for yur help !!!! :)))) CU Thorsten From skip at pobox.com Fri Dec 19 10:10:56 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Dec 2003 09:10:56 -0600 Subject: Broken python-model.el In-Reply-To: <6q3cbghoj0.fsf@salmakis.intevation.de> References: <274A369893F5FB4099345F006439D987013876D8@bella.corp.resmed.org> <6q3cbghoj0.fsf@salmakis.intevation.de> Message-ID: <16355.5376.213490.638537@montanaro.dyndns.org> Bernhard> One problem I'm seeing with 4.41 is that in "self.map" map is Bernhard> highlighted. According to the comment the builtins (kw3) Bernhard> should not be highlighted when they're used as attributes but Bernhard> the regexp matches attributes as well. Bernhard> I've submitted a patch: Bernhard> http://sourceforge.net/tracker/index.php?func=detail&aid=862952&group_id=86916&atid=581351 I applied this and several other pending patches. The current version is now 4.47. Please give it a whirl... (With all the changes I'll sync the version in Python's cvs if I don't hear any screams in the next couple days.) Skip From paska at kios.sk Mon Dec 8 08:07:32 2003 From: paska at kios.sk (Stano Paska) Date: Mon, 08 Dec 2003 14:07:32 +0100 Subject: sorting slovak utf In-Reply-To: <3FD45B2C.1080107@kios.sk> References: <3FD45B2C.1080107@kios.sk> Message-ID: <3FD47794.40902@kios.sk> I forgot append a file. Stano Paska wrote: > Hi, > > I have one problem. > In file aaa.txt I have slovak letters in utf-8. > > zcaron > scaron > aacute > ocircumflex > tcaron > yacute > ccaron > eacute > lcaron > iacute > dcaron > uacute > adiaeresis > oacute > lacute > ncaron > racute > > with this script (output is redirected to file bbb.txt): > > import fileinput > riadky = [] > a = fileinput.input("aaa.txt") > for i in a: > riadky.append(i.strip()) > a.close() > riadky.sort() > for i in riadky: > print i > > I have this result: > > aacute > adiaeresis > eacute > iacute > oacute > ocircumflex > uacute > yacute > ccaron > dcaron > lacute > lcaron > ncaron > racute > scaron > tcaron > zcaron > > and corrent result would be: > > aacute > adiaeresis > ccaron > dcaron > eacute > iacute > lacute > lcaron > ncaron > oacute > ocircumflex > racute > scaron > tcaron > uacute > yacute > zcaron > > I have set utf-8 in sitecustomize.py > > I tried: > import locale > locale.setlocale(locale.LC_CTYPE, 'sk_SK.utf-8') > and > locale.setlocale(locale.LC_CTYPE, ('sk_SK', 'utf-8')) > but i got "unsupported locale" error > > What I must do to get correct sorting result? > > Stano. > > P.S. lower, upper works correct > > > > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: aaa.txt URL: From tjreedy at udel.edu Tue Dec 9 12:54:12 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Dec 2003 12:54:12 -0500 Subject: Speed: bytecode vz C API calls References: Message-ID: "Jacek Generowicz" wrote in message news:tyfy8tmz7hq.fsf at pcepsft001.cern.ch... > "Terry Reedy" writes: > > Can any of your callables be memoized by list rather than dict? > > (ie, any count or restricted int args?) > > You've lost me there. Lookup tables. Dicts can memoize any function. Lists can memoize or partially memoize functions with one or more periodic domains. Perhaps I am being too obvious or simple for *you*, but I have seen people memoize fib() or fac() with a generic dict-based wrapper, which is overkill compared to a simple list. In another post, you said > If I want to compete on speed with C++, I'm >simply going have to eliminate Python bytecode from my inner loops[*]. > [*] Unless my overall algorithm is completely wrong, of course. For speed, you need to eliminate *executed* and *expensive* bytecodes, not static, possibly skipped-over, bytecodes. I'll take that as what you meant. It is certainly what our comments are aimed at. Hence my other suggestion to eliminate a layer of (expensive) function calls by combining value calculation and storage in one function (more space, less time). More specific suggestions will require more specific examples. Terry J. Reedy From Ashu.Akoachere at limbe.eurobell.co.uk Mon Dec 8 18:32:31 2003 From: Ashu.Akoachere at limbe.eurobell.co.uk (Dipl. -Ing. Ashu Akoachere) Date: Mon, 8 Dec 2003 23:32:31 -0000 Subject: Using the built-in cmd class Message-ID: Has any one got experience in using the built-in cmd class? I have derived a subclass from the base class, but it seems as if the arguments of functions using the cmd-interpreter are limited in their number. Precisely' I have something like this: . .def help_add(self): print "Adds arguments" def do_add(self,arg1,arg2): return (arg1 + arg2) Python complains about the number of arguments in the do_add function. Has anyone got a modified cmd that can handle multiple arguments? Ashu -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed Dec 31 08:14:14 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 31 Dec 2003 14:14:14 +0100 Subject: 'inverting' a dict In-Reply-To: <5b4785ee.0312301604.4934c96@posting.google.com> References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> <5b4785ee.0312301604.4934c96@posting.google.com> Message-ID: <3ff2cba6$0$316$e4fe514c@news.xs4all.nl> Wade Leftwich wrote: > def invert_dict(D): > return dict([(y,x) for (x,y) in D.items()]) No, this one only works for non-sequence-type values. I wanted to map every item of a value (a sequence) to the corresponding key. --Irmen From robin at jessikat.fsnet.co.uk Mon Dec 8 18:42:49 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 8 Dec 2003 23:42:49 +0000 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> Message-ID: unfortunately all of these tests are slower than 1 clock tick on my machine. I believe the may be biassed. -- Robin Becker From pythonguy at Hotpop.com Mon Dec 22 03:23:50 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 22 Dec 2003 00:23:50 -0800 Subject: Count Files in a Directory References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: <84fc4588.0312220023.727eb00@posting.google.com> If you are using Python 2.3, the new os.walk() function is a better and faster choice. Here is a sample code for counting files & sub-dirs recursively. ---------------------------------- # dircount.py import os dir_count, file_count=0, 0 for root, dirs, files in os.walk('.'): dir_count += len(dirs) file_count += len(files) print 'Found', dir_count, 'sub-directories in cwd' print 'Found', file_count, 'files in cwd' print 'Found', dir_count + file_count, 'files & sub-directories in cwd' ---------------------------------- -Anand Jay Dorsey wrote in message news:... > On Sun, Dec 21, 2003 at 03:45:31PM -0800, hokiegal99 wrote: > > I'm trying to count the number of files within a directory, but I > > don't really understand how to go about it. This code: > > > > Do you want the total number of files under one directory, or > the number of files under each directory? > > > for root, dirs, files in os.walk(path): > > for fname in files: > > x = str.count(fname) > > print x > > > > Produces this error: > > > > TypeError: count() takes at least 1 argument (0 given) > > str.count() is a string method used to obtain the number of > occurences of a substring in a string (try help(str.count)) > > >>> n = "this is a test" > >>> n.count("test") > 1 > > > > > for root, dirs, files in os.walk(path): > > for fname in files: > > x = list.count(files) > > print x > > > > TypeError: count() takes exactly one argument (0 given) > > > > Also wondered why the inconsistency in error messages (numeric 1 vs. > > one)??? Using 2.3.0 > Similar problem here, for a list method ( try help(list.count)). > > >>> n = ["test", "blah", "bleh"] > >>> n.count("test") > 1 > > In your example, fname would be an individual file name within a > directory list of files (in your example, the variable files). > > What you probably want is len(), not count(). > > If you want the number of files in each directory try: > > >>> for root, dirs, files in os.walk(path): > ... print len(files) > > Or, for the total number of files: > > >>> filecount = 0 > >>> for root, dirs, files in os.walk(path): > ... filecount += len(files) > >>> print filecount > > hth From skip at pobox.com Mon Dec 1 23:14:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 1 Dec 2003 22:14:13 -0600 Subject: sys._getframe() not behaving as expected In-Reply-To: References: <16331.44285.6257.338657@montanaro.dyndns.org> Message-ID: <16332.4501.839378.480748@montanaro.dyndns.org> Tim> [Skip Montanaro] >> sys._getframe() is acting peculiar. Tim> An argument < 0 is treated like 0. You want to pass 2 and 1, not Tim> -2 and -1. Thanks. That is the final bit of mortar needed for a small brick wall. On python-dev, Gerrit Holl suggested two new builtins: save() and load(), which would allow a user to save a session and later restore it. The very simpleminded implementation of that concept is available at http://www.musi-cal.com/~skip/python/save_session.py Skip From jacek.generowicz at cern.ch Wed Dec 17 04:40:56 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Dec 2003 10:40:56 +0100 Subject: Interactive programming References: <8ef9bea6.0312161420.6ef9b90e@posting.google.com> Message-ID: hungjunglu at yahoo.com (Hung Jung Lu) writes: > Hi, > > Is there a term for the ability of changing program code without the > need of restarting the program? I mean, the most typical developer's > cycle is: > > (a) write code > (b) set break points, start the program > (c) find bug, change code, goto (b) Typical, if you are unfrotunate enough to be programming in a very limited language or environment. > I know some environments allow you to modify the code, and resume > execution, without having to restart your program from the very > beginning. Lots ... Python, Forth, Smalltalk, Common Lisp ... The last even allows you te resume almost exactly from the point at which your error (or breakpoint) occurred. > Some terms I have heard are "interactive programming", > "edit-and-resume", etc. But is there standard name for this feature? Incremental ? I think that "incremental compilation" is typically used to describe the ability to compile a single function at a time, and the ability to replace a single function in your (running) program. (Apple's XCode apparently brings this ability to C++, but I haven't any first-hand experience with it.) I certainly refer to it as "incremental development", but I'm not entirely sure where I picked up this term. From http Tue Dec 23 16:04:50 2003 From: http (Paul Rubin) Date: 23 Dec 2003 13:04:50 -0800 Subject: Storing pairs of (int, int) in a database : which db to choose ? References: <21bb8d55.0312230435.49cad73c@posting.google.com> <21bb8d55.0312231254.4514d450@posting.google.com> Message-ID: <7xr7yvjle5.fsf@ruckus.brouhaha.com> andreif at mail.dntis.ro (Stormbringer) writes: > The only thing that bothers me a little is the speed for building the > index, I tried with around 5000 messages and I am not quite thrilled, > it's not _extremly_ slow but it has to be faster for what I need. > Perhaps I'll use the C++ version with some Python bindings. Why not do some profiling first. Maybe it's limited by i/o traffic rather than cpu cycles. I don't know how Lupy works but the one time I messed with full text indexing, the bottleneck was definitely the random disk accesses needed for every word of each update. The solution is to batch the updates. Sorting is much less seek intensive than random updates. From gandalf at geochemsource.com Fri Dec 5 03:59:54 2003 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 05 Dec 2003 09:59:54 +0100 Subject: [Boa Constr] Download of 0.2.7 Available References: Message-ID: <3FD0490A.1090002@geochemsource.com> It is 'boa'. Well, you can get valid repository names from the CVS interface of SourceForge. Start with here: http://sourceforge.net/projects/boa-constructor/ Select 'CVS' on the top. Under 'Anonymous CVS Access' you will see a link with this text: To determine the names of the modules created by this project, you may examine their CVS repository via the provided web-based CVS repository viewer . Click on 'web-based CVS repository viewer ' and you will see the module names. Currently, there is only one named 'boa'. Possibly you will have to be a member of SF to do this, I'm not sure. Best, L Jeff Wagner wrote: >When you attempt to 'Checkout', you are asked for a module name. What is it? I tried numerous >things but none of them worked. > >Jeff > >On Thu, 04 Dec 2003 09:18:00 +0100, Nagy L?szl? Zsolt wrotf: > > > >>Here is what you need to do: >> >>1. Download SmartCVS. Here is a link: >>http://www.smartcvs.com/download/setup-jre-2_4_2.zip >>2. Install it >>3. When you start it for the first time, please add a new repository. >>4. Give these parameters: >> >> - Connection type: Password-Authentication (pserver) >> - User name: anonymous >> - Server name: cvs.sourceforge.net >> - Repository path: /cvsroot/boa-constructor >> >>Then you can 'Checkout' to a directory (which you can select). After >>download 'boa', please replace your old boa folder with the one you just >>checked out. >> >>That's all. >> >>Cheers, >> >> Laci 1.0 >> >>Howard Dunlavy wrote: >> >> >> >>>Thanks for the response. >>> >>>I am using Windows XP. >>> >>>-Howard >>> >>> >>>----Original Message Follows---- >>>From: Nagy L?szl? Zsolt >>>To: Howard Dunlavy , Boa-users >>> >>>Subject: Re: [Boa Constr] Download of 0.2.7 Available >>>Date: Thu, 04 Dec 2003 08:03:18 +0100 >>> >>>I just downloaded it with CVS and that was easy, almost trivial. >>>What OS do you use? >>> >>>Howard Dunlavy wrote: >>> >>> >>> >>>>Is there a non-CVS way to download version 0.2.7? I don't know >>>>anything about how to do it directly from CVS and everything I have >>>>read about it makes it sound non-trivial. >>>> >>>>So I was looking for an easier way to get the latest version. >>>> >>>>Thanks. >>>> >>>>-Howard >>>> >>>> >>>> >> >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From maarten at remove_this_ws.tn.tudelft.nl Fri Dec 19 05:32:09 2003 From: maarten at remove_this_ws.tn.tudelft.nl (Maarten van Reeuwijk) Date: Fri, 19 Dec 2003 11:32:09 +0100 Subject: Sorting coordinates array Message-ID: I'm a newbie to Python, so sorry for this maybe trivial question. I have a numpy array with coordinates, which I want to sort, for example first on z-coordinate, then x and lastly y-coordinate. So an array like: [[0, 0, 0], [0, 2, 1], [1, 1, 0], [0, 1, 1]] should look after sorting like [[0, 0, 0], [1, 1, 0], [0, 1, 1], [0, 2, 1]] I tried the sort command, but that command mangles my coordinate pairs. Also converting the array to a list doesn't seem to improve the results. How should I tackle this problem? TIA, Maarten -- =================================================================== Maarten van Reeuwijk Heat and Fluid Sciences Phd student dept. of Multiscale Physics www.ws.tn.tudelft.nl Delft University of Technology From hokiegal99 at hotmail.com Sun Dec 14 10:37:38 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: 14 Dec 2003 07:37:38 -0800 Subject: Find and Delete all files with .xxx extension References: <3FDBC1B8.4010205@hotmail.com> Message-ID: <93f5c5e9.0312140737.3774ecad@posting.google.com> "Fredrik Lundh" wrote > to quote myself from an earlier reply to you: > > os.path.splitext(fname) splits a filename into prefix and extension > parts: > > >>> os.path.splitext("hello") > ('hello', '') > >>> os.path.splitext("hello.doc") > ('hello', '.doc') > >>> os.path.splitext("hello.DOC") > ('hello', '.DOC') > >>> os.path.splitext("hello.foo") > ('hello', '.foo') > > in other words, ext[1] *is* the extension. Yes, I know that. You helped me to understand that in a earlier, different question. > if you want to look for mp3, MP3, Mp3, etc, you can use the "lower" > method on the extension: > > for fname in files: > name, ext = os.path.splitext(fname) > ext = ext.lower() > if ext == ".mp3": > # ... do something with mp3 files ... > if ext == ".foo": > # ... do something with foo files ... Thank you for this example, it's exactly what I was thinking of. I didn't know that I could use an equivalent comparison to determine whether or not ext[1] contained the string I wanted to remove, that's all I was asking. After reading over the various replies and testing them, I think that this is the best solution: if fname.lower().endswith('.mp3'): remove... Thanks again for the examples. From puccio_13**NOSPAM** at yahoo.it Tue Dec 2 02:17:02 2003 From: puccio_13**NOSPAM** at yahoo.it (Alessio Pace) Date: Tue, 02 Dec 2003 08:17:02 +0100 Subject: python on handhelds devices (IPAQs) References: Message-ID: Il Tue, 02 Dec 2003 07:46:34 +0100, vincent wehren ha scritto: > "Alessio Pace" schrieb im Newsbeitrag > news:ZDMyb.658$5o6.317 at tornado.fastwebnet.it... > | Hi, python is without any doubt my first choice for common tasks on the > | desktop side, but now I have to develop something on an PDA: an HP IPAQ. > | > | I wonder if python can be also the preferable choice on this kind of > | platform, rather than the other J2ME/Jeode/JsomeThingElse non-free stuff > | out there. > | > | I have Familiar Linux installed on the IPAQ, I can flash OPIE or GPE, no > | problems. My needs are to use libraries for db connectivity, xml, tcp/ip > | and some GUI (so, specific binding to GTK or QT). > > > Google for "pypaq". I have already installed it.. I would like to know if this platform (python + GTK binding) is quite stable and good for most tasks... BTW, thanks for the reply > > HTH > > Vincent Wehren > > > | > | Has anyone tried something in this same way and could give me some advices > | suggestions/hints/.. ? > | > | Thanks a lot. > | > | -- > | bye > | Alessio Pace From gnari at simnet.is Sun Dec 21 09:43:41 2003 From: gnari at simnet.is (Ragnar Hafstað) Date: Sun, 21 Dec 2003 14:43:41 -0000 Subject: How to use a 5 or 6 bit integer in Python? References: <3FE2FB4C.5020909@users.ch> <3FE43F09.10307@crazy-compilers.com> Message-ID: "Hartmut Goebel" wrote in message news:3FE43F09.10307 at crazy-compilers.com... > Hi, > ... > - pack the key-tuples into a string using pack; you may even pack 4 > intergers into one byte since the values range from 1-64 (which is > equivalent to 0-63). sorry, but actually 0-63 is 6 bits (as in the Subject line) 6bits*4=24bits more like 3 bytes gnari From martin at v.loewis.de Thu Dec 4 14:22:52 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 04 Dec 2003 20:22:52 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo> <3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > Still, the actual characters used in the _source_ representation will have to > be whatever the -*- xxx -*- thing says, right? -- including the characters > in the source representation of a string that might wind up utf-8 internally? Yes, and no. Yes, characters in the source code have to follow the source representation. No, they will not wind up utf-8 internally. Instead, (byte) string objects have the same byte representation that they originally had in the source code. The source declaration only matters in the following respects: - the source may be erroneous, if the bytes form illegal encodings in the declared source encoding. - a unicode object will be created based upon the source encoding, by decoding the bytes in the unicode literal. - the meaning of certain bytes might not be what it would be in ASCII. In particular, byte 92 does not always denote a backslash (\), in all encodings. As a result, if byte 92 appears in a string literal, the end of the string literal might depend on the encoding. > >The byte string type is not going away. It is a useful type, e.g. when > >reading or writing to or from a byte stream. > > > Is this moving towards a single 8-bit str base type with various > encoding-specifying subtypes? I don't think so. If byte strings where tagged with encoding, you have to answer many difficult questions, like "what is the result of adding strings with different encodings?", or "what encoding tag has a string returned from a socket read", etc. Instead, applications should apply encodings whereever needed, using Unicode strings for character data, and byte strings for binary data. Regards, Martin From hokiegal99 at hotmail.com Tue Dec 23 08:48:39 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Tue, 23 Dec 2003 08:48:39 -0500 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> Message-ID: Peter Otten wrote: > hokiegal99 wrote: > > >>I was told earlier (w/o explanation) that functions should return >>something. I was under the impression that it was OK with Python to >>leave the return statement off. Could someone enlighten me on why or >>why not to use a return statement when defining functions? Below is >>the bit of code I was told should return something: >> >>def fs_object_count(path): >> file_count = 0 >> dir_count = 0 >> for root, dirs, files in os.walk(path): >> file_count += len(files) >> dir_count += len(dirs) >> print "Number of Files Examined: ", file_count >> print "Number of Folders Examined: ", dir_count >> print "Total Number of FS Objects:", file_count + dir_count > > > I think I was the guy who told that. I did not mean that you should always > add an explicit return statement, you just posted a slightly different > function > > [hokiegal99 in earlier post] > > >>def fs_object_count(path): >> file_count = 0 >> dir_count = 0 >> for root, dirs, files in os.walk(path): >> for fname in files: >> file_count += len(fname) >> for dname in dirs: >> dir_count += len(dname) >>fs_object_count() > > > > which attempted to calculate file and dir count but did neither return these > values nor print them. Thus the file_count and dir_count were lost and the > function useless. Yes, I see this now. It makes a lot of sense. In an earlier reply from Francis, it was made clear to me that functions work best when they do one thing well and when it's evident what they are attempting to do. By taking this approach to defining them, functions are very modular and easier to comprehend, no? So, they can then return their value to another function that maybe was written to print the information nicely or whatever. Is that a good way of thinking about functions? From cfriedl at bigpond.net.au Wed Dec 24 05:22:07 2003 From: cfriedl at bigpond.net.au (Chris Friedl) Date: Wed, 24 Dec 2003 10:22:07 GMT Subject: nonlinear least square References: <87ptefi9qj.fsf@pobox.com> Message-ID: I recently found the Enthought python packages (2.2 & 2.3) which bundles a whole lot of scientific/numeric/visualisation python code (see www.enthought.com/python). Might be useful for you to get to the scipy stuff. Merry Xmas "Dmitry Rozmanov" wrote in message news:bsaj7i$26om$1 at news.wplus.net... > John J. Lee wrote: > > Thank you for the suggestion. > > Yes, I do not like to have to install Scientific Python just for this > purpose. As I understand it has some modules which have to be compiled > anyway. > > I would be really grateful for any example code you provide. > > BWT do you know such a standalone code for nonlinear equations set > solving? Newton's method or something. I mean in Python only. > > Thank you again. > > Regards. > > ---Dmitry. > > > Konrad Hinsen's implementation in Scientific Python *is* in pure > > Python, and as a consequence is probably about as simple as you're > > going to get, I imagine. Is it dependencies on Scientific Python that > > you don't like? If so, just dive in and remove them, if it's that > > important to you -- I doubt you'll find a better pure Python > > implementation. > > > > I can certainly testify that SciPy's MINPACK wrapper works fine, too. > > I can dig out some example code if you like. > > > > > > John > From magnus at thinkware.se Tue Dec 2 08:41:54 2003 From: magnus at thinkware.se (Magnus Lyck?) Date: 2 Dec 2003 05:41:54 -0800 Subject: Python bug? Named parameters in recursive calls sometimes confuses python? References: <258fd9b8.0311271503.c134a25@posting.google.com> Message-ID: <258fd9b8.0312020541.50348a96@posting.google.com> Duncan Booth wrote in message news:... > I note that you reassign the 'column' variable in that last for loop. I > think your last line of output is simply the second time around the 'for > row in rows' in the outermost call. Perhaps if you used a different > variable name for that second variable called 'column' you wouldn't get so > confused. Silly me! Thank's Duncan. This really confused me a lot. Initially, I was sure it was one of these normal "I'm sure it's obvious once I spot it" problems, but somehow, I managed not to spot it for a very long time. This feels very reassuring. I was starting to wonder if there was something problematic with Python 2.3.2 on NT... Lucky it was just me being blind! :) From loverdos at di.uoa.gr Sat Dec 6 18:20:50 2003 From: loverdos at di.uoa.gr (Christos KK Loverdos) Date: Sun, 07 Dec 2003 01:20:50 +0200 Subject: Fuzzy Logic Message-ID: <3FD26452.90906@di.uoa.gr> Hi all! Is there any fuzzy logic package? From jponiato at ford.nospambot.com Fri Dec 12 08:35:39 2003 From: jponiato at ford.nospambot.com (Joe Poniatowski) Date: Fri, 12 Dec 2003 08:35:39 -0500 Subject: newbie architecture question Message-ID: I wish to define a hierarchy of classes - something like book, chapter, page, where books are made of one or more chapters, and chapters consist of one or more pages. Should the definitions be nested, or all at the module level with just the instantiations nested? Jp From gerrit at nl.linux.org Thu Dec 18 08:29:46 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Thu, 18 Dec 2003 14:29:46 +0100 Subject: documentation In-Reply-To: <20031218130743.GA3646@mrna.tn.nic.in> References: <20031218091118.GA3296@mrna.tn.nic.in> <20031218120515.GA2564@nl.linux.org> <20031218130743.GA3646@mrna.tn.nic.in> Message-ID: <20031218132946.GA3681@nl.linux.org> km wrote: > unfortunately none of these works. Pydoc should be in the pythos distribution, in the library dir. You can create a symlink from /usr/local/bin. Try: python /usr/lib/python2.3/pydoc.py pyvar (or wherever it is) help(pyvar) should work at the interactive prompt, if pyvar is defined, of course, else it should be 'pyvar', e.g. help('modules'), just try it out... Gerrit. -- 266. If the animal be killed in the stable by God (an accident), or if a lion kill it, the herdsman shall declare his innocence before God, and the owner bears the accident in the stable. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From dennis.posadas at intel.com Mon Dec 1 02:18:37 2003 From: dennis.posadas at intel.com (Posadas, Dennis) Date: Mon, 1 Dec 2003 15:18:37 +0800 Subject: I just want to say that python is a COOL language Message-ID: Complete Object Oriented Language. COOL ! After years of not doing any programming, I've fallen in love w/programming again. Dennis From douglist at anize.org Wed Dec 3 17:01:46 2003 From: douglist at anize.org (Douglas F. Calvert) Date: Wed, 03 Dec 2003 17:01:46 -0500 Subject: graphs in python... Message-ID: <1070488905.1453.9.camel@liberate.imissjerry.org> Hello, I read "Python Patterns: Implementing Graphs" document on the website and was impressed with doing graphs in this fashion. Is this still the best documented way to do graphs. The document alludes to a follow up article tuned for speed but I have not found it. Can anyone suggest other ways that might be faster? I am looking to implement a graph with over 11k nodes and I am afraid that the speed might begin to wither. I have implemented a test version with this code and a set of 5k nodes and the speed could be quicker:) Thanks a lot... -- Douglas F. Calvert From markus_wankus at hotmail.com Mon Dec 15 12:17:25 2003 From: markus_wankus at hotmail.com (Markus Wankus) Date: Mon, 15 Dec 2003 12:17:25 -0500 Subject: SWT and Python (was: Re: What GUI toolkit looks the best?) References: <20031211190954.GA54939@hishome.net> <05f701c3c026$5eb9c8f0$7401a8c0@voidmk9> Message-ID: On Fri, 12 Dec 2003 15:32:35 GMT, Michael Hudson wrote: > Oren Tirosh writes: > >> SWT has been ported from Java to C# for the SharpDevelop project. I >> wonder >> how difficult it would be to port SWT to Python. > > Is SWT the framework that was developed for Eclipse? > > I realise I could look this up myself, but well, that involves NN4 for > the moment... > I believe that's what he means...and I have been wondering about this for awhile. SWT is very wxWindows-ish in it's parent-child relationships - and I think it just looks and feels really cool. You can easily do it all in Python/Jython - provided you use the .dll and .jar file. A pure Python wrapping of the .dll (i.e. replacing the .jar file) would be seriously cool. -- Markus From exarkun at intarweb.us Tue Dec 23 13:11:58 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 23 Dec 2003 13:11:58 -0500 Subject: return statement in functions In-Reply-To: References: <93f5c5e9.0312221718.23e42dac@posting.google.com> <3fe86429$0$186$e4fe514c@news.xs4all.nl> Message-ID: <20031223181158.GA25399@intarweb.us> On Tue, Dec 23, 2003 at 11:44:39AM -0500, hokieghal99 wrote: > [snip] > > That works, but it only returns the first item in the list. The > functions are returning a list of paths or of files/dirs. For example, > the function 'clean_dir_names' should return a complete list of > directory names that it has removed bad characters from. > > def clean_dir_names(path): > for root, dirs, files in os.walk(path, topdown=False): > for dname in dirs: > new_dname = re.sub(bad,'-' ,dname) > if new_dname != dname: > newpath = os.path.join(root, new_dname) > oldpath = os.path.join(root, dname) > os.renames(oldpath, newpath) > return new_dname > > How do I make the report function see all of the contents of the list > and not just the first item of the list? > No. "return new_dname" terminates execution of the function. If you want many results, you need to collect them in a list and return the list, or use a generator. Jp > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Dec 1 18:44:15 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 02 Dec 2003 00:44:15 +0100 Subject: Shared Memory Modules In-Reply-To: <3fcbd6b8$1@nntp0.pdx.net> References: <3FC390AA.3DFDE27F@engcorp.com> <65h89urq.fsf@python.net> <3fc3aa8a$0$1494$e4fe514c@news.xs4all.nl> <3fcbd6b8$1@nntp0.pdx.net> Message-ID: <3fcbd24f$0$1502$e4fe514c@news.xs4all.nl> Scott David Daniels wrote: > Irmen de Jong wrote: > >> However, I've just tried it, and managed to crash Python in mmap.pyd >> with an application exception... twice. But trying to reproduce it >> now fails-- Python keeps running. >> I did this: >> >>> import mmap >> >>> mem=mmap.mmap(0,3000000,'irmen') >> >>> mem[0]='a' >> >>> mem[2000000]='a' >> and initially, it crashed......... Python 2.3.2 on win xp) >> --Irmen > > > Probably not enough actual memory hanging around. Some systems > (and from this I'd guess XP) allocate virtual memory by reserving > address space, not actually allocating the RAM and/or backing > store for that memory. Over-commit is that called, right? I'm sorry but that certainly wasn't the case here. My machine has 512 Mb RAM and about 250 Mb of them allocated when I tried it. (physical RAM that is) Very weird, I cannot reproduce the initial crash I experienced. --Irmen From fortepianissimo at yahoo.com.tw Sun Dec 7 20:42:00 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 7 Dec 2003 17:42:00 -0800 Subject: timeout in socket.gethostbyname()? References: Message-ID: Ok so for now I use a separate thread to run gethostbyname, and stop waiting for the result if time is running up. But would be interested in knowing a simpler way doing this. Thanks! fortepianissimo at yahoo.com.tw (Fortepianissimo) wrote in message news:... > I've tried using > > socket.setdefaulttimeout(timeout) > > to set the default timeout to 'timeout' for all sockets. The part > that's not clear to me, is that if this will affect > socket.gethostbyname(). In my observation the timeout setting did not > affect the DNS lookup. > > It might be my misunderstanding of the semantics here: would > setdefaulttimeout() only applies to any socket object newly created? > So gethostbyname() doesn't create a new socket (explicitly at least) > so timeout doesn't apply there? What should I do to get the intended > behavior? > > Thanks a bunch! From bokr at oz.net Thu Dec 18 00:07:23 2003 From: bokr at oz.net (Bengt Richter) Date: 18 Dec 2003 05:07:23 GMT Subject: Converting integer to binary representation References: Message-ID: On Tue, 16 Dec 2003 16:29:50 +0100, Mark Dufour wrote: >On Tuesday 16 December 2003 15:48, Fredrik Lundh wrote: >> "Mark Dufour" wrote: >> > I need to convert an integer into some binary representation. I found the >> > following code in the online cookbook (adapted to return a list): >> > >> > binary = lambda n: n>0 and [n&1]+binary(n>>1) or [] >> > >> > This is sure nice, but I'm wondering why something like this doesn't seem >> > to be in the standard library, for example by formatting with '%b' % >> > number. I can't think of a any reason for not doing it this way, as >> > working with binary representations is quite common in programming, >> >> really? what kind of programs are you writing? > >I want to loop over the binary representation of numbers, for use in some >algorithm dealing with prime numbers. Of course, there are multiple ways of >doing this, but I like the clean: 'for power, bit in >enumerate(binary(number))', possible with the above code. > >> (in my experience, binary numbers only appear in programming text >> books. humans tend to use decimal numbers, and programmers use >> octal or hexadecimal numbers when they need to "access the bits"). > >I've seen several attempts on the web for implementing this functionality in >Python, so I guess I'm not the only one needing or wanting it.. ;-) Some >programmers actually do work a lot with bits and prefer binary representation >sometimes, so why not add a simple provision to the language? Like, int() >takes a base argument, why not have str() take one as well?? If only just for >consistency :-) > Below is a class subclassing long to repr-show bits as bigendian strings and letting you iterate through the bits from the little end. The values may be signed, with the most significant bit being the sign bit (which logically extends left as far as you like), and the literal form has a 'b' appended. This repr format "round-trips" -- i.e., you can give it back to the constructor and get the same number. (not tested beyond what you see here ;-) ====< lbits.py >================================================ class LBits(long): """ Class acting like long, but showing bits for grins. 2003-12-17 alpha version by Bengt Richter """ class __metaclass__(type): """Wrap long methods to return LBits objects""" def __new__(cls, name, bases, cdict): exclude = [ '__class__', '__cmp__', '__coerce__', '__delattr__', '__divmod__', '__doc__', '__float__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__new__', '__nonzero__', '__oct__', '__pos__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rtruediv__', '__setattr__', '__str__', '__truediv__'] for k, v in vars(long).items(): if k in exclude: continue exec """\ def %s(self,*args,**kw): return self.__class__(long.%s(self,*args,**kw)) """ % (k, k) in cdict return type.__new__(cls, name, bases, cdict) def __new__(cls, v): """Handle additional string literal format with 'b' suffix and sign as leading bit""" if isinstance(v, str) and v[-1:].lower()=='b': if v[0]=='1': return long.__new__(cls, long(v[1:-1] or '0', 2)-(1L<<(len(v)-2))) else: return long.__new__(cls, v[1:-1] or '0', 2) return long.__new__(cls, v) def __repr__(self): """Show self in round-trip literal format, with leading bit as sign bit and 'b' suffix""" val = long(self) absval = abs(val) s=[chr(((val>>b)&1)+48) for b in xrange(len(hex(val))*4) if not b or absval>>(b-1)] s.reverse() return ''.join(s+['b']) def __iter__(self): """Return little-endian iterator through bits, including sign bit last""" return self.bitgen() def bitgen(self): """Little-endian bit sequence generator""" bits = long(self) sign = bits<0 while bits>0 or sign and bits!=-1L: yield int(bits&1) bits >>= 1 yield int(sign) ================================================================ >>> from lbits import LBits >>> b = LBits(11) >>> b, -b, ~b, b&5, b^5, b*4, b/2, str(b), repr(b) (01011b, 10101b, -12L, 01b, 01110b, 0101100b, 0101b, '11', '01011b') >>> int(b), long(b), float(b), str(b), repr(b) (11, 11L, 11.0, '11', '01011b') >>> [bit for bit in b] [1, 1, 0, 1, 0] >>> [bit for bit in -b] [1, 0, 1, 0, 1] >>> print b,`b`,'str(b)=%s, repr(b)=%r'%(b,b) 11 01011b str(b)=11, repr(b)=01011b >>> for i in xrange(-8,9): ... print '%3s => %6r => %3s %s' %(i,LBits(i), LBits(repr(LBits(i))),[x for x in LBits(i)]) ... -8 => 11000b => -8 [0, 0, 0, 1] -7 => 1001b => -7 [1, 0, 0, 1] -6 => 1010b => -6 [0, 1, 0, 1] -5 => 1011b => -5 [1, 1, 0, 1] -4 => 1100b => -4 [0, 0, 1] -3 => 101b => -3 [1, 0, 1] -2 => 110b => -2 [0, 1] -1 => 11b => -1 [1] 0 => 0b => 0 [0] 1 => 01b => 1 [1, 0] 2 => 010b => 2 [0, 1, 0] 3 => 011b => 3 [1, 1, 0] 4 => 0100b => 4 [0, 0, 1, 0] 5 => 0101b => 5 [1, 0, 1, 0] 6 => 0110b => 6 [0, 1, 1, 0] 7 => 0111b => 7 [1, 1, 1, 0] 8 => 01000b => 8 [0, 0, 0, 1, 0] >>> [LBits(s) for s in '10b 1b 0b'.split()] [110b, 11b, 0b] >>> b 01011b >>> sum([bit*2**pow for pow,bit in enumerate(b)]) 11 >>> sum([bit*2**pow for pow,bit in enumerate(LBits(1023))]) 1023 (of course that sum has to be spelled an alternate way for negative numbers) I wouldn't think it would be a big mod to get the current int and long to accept 'b'-suffixed binary literals, BTW. And a %b in string formatting could work like LBits.__repr__ here. Maybe with %b for lower case suffix and %B for upper case, to follow %x and %X usage. Obviously this class is going to impose a performance hit over plain longs, but maybe it's useful to you? I'll leave full testing and better error messages and adding a divmod method and such as an exercise ;-) Regards, Bengt Richter From mwilson at the-wire.com Thu Dec 11 17:17:15 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 11 Dec 2003 17:17:15 -0500 Subject: optimization pointers? References: Message-ID: In article , "r.e.s." wrote: >Would anyone care to offer pointers on how the following code >might be optimized? Or alternatives? ... > >--- >def lz(string): > """ Return the Lempel-Ziv complexity (LZ78) of string. """ > > vocabulary = [] > word = '' > for char in string: > word += char > if word not in vocabulary: > vocabulary.append(word) > word = '' > return len(vocabulary) >--- > >On my 2 GHz system running PythonWin, the above code averages >about 1.3 hrs to process a 1 MB string. I'd hoped to compute >LZ78 for multi-GB files, but it seems infeasible. (?) One simple improvement is to get rid of if an_item not in a_list which does a linear search over the list. A dictionary is faster. Without a full benchmark, it seems that appending def lz_complexity (s): voc = {} word = '' for c in s: word += c if not voc.get (word, False): voc[word] = True word = '' return len (voc.keys()) if __name__ == '__main__': import time text = file ('lzc.py', 'rt').read() t0 = time.clock() t0 = time.clock() - t0 c = lz (text) t1 = time.clock() c = lz (text) t1 = time.clock() - t1 c = lz_complexity (text) t2 = time.clock() c = lz_complexity (text) t2 = time.clock() - t2 print 'T1:', t1 - t0 print 'T2:', t2 - t0 will show about a x6 speedup. Avoiding a_string += another_string is a traditional speedup, but it seems you'll be needing the string form for every character processed, so it may not buy much in this case. Regards. Mel. From joconnor at cybermesa.com Tue Dec 2 10:48:41 2003 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 02 Dec 2003 08:48:41 -0700 Subject: python's threading has no "interrupt"? In-Reply-To: References: Message-ID: Dave Brueck wrote: >What's your actual use case (IOW, what programming problem are you trying to >solve)? Maybe there is a Python solution that will work for you, but in order >to help you find it, people here will need to better understand what you're >trying to do. > >You've noticed that there isn't an identical construct for what you were doing >in Java, so it may be that the Python way will be a completely different >approach to the problem rather than just a direct conversion from Java to >Python syntax. > > Well, I'll give an example from something I tried to do a few years ago which I couldn't translate to Python, though I took a stab at it. The language in question was a VM language with it's own internal process model. The process model was all inteneral to on eOS process to it was a cooperative model of multi-threading The application I wrote was a web server on the front of an application so that web requests were all handled in the application. IOW, the application had a web server interface) The language process model had both the ability to set process priorities, as well as allow processes to sleep and cede control to other processes. When a web request would come in, the handling of the request would be forked as a seperate process so that the server could accept the next request. Both the server process and the handling process(es) were at the same priority level so in theory each process would run to completion before allowing another process to run. For this reason, both the server process and the handling processes would issue a 'yield' at periodic strategic points, allowing themselves to temporarily halt and for the next process of equal priority that was waiting to run. This allowed both the server to remain responsive and all handling processes to run efficiently. Behind all of this was a higher priority process running, but it basically would sleep for several minutes (sleeping allowed lower priority process, like the server process to run). When the background process would wake up, since it was a higher priority, it would immediately take control. It's main job was to check the list of handling processes for any that had been running too long (long running processes in a web server meant that something had gone wrong) and terminate them (freeing up the process and socket resources, etc..). Then it (the cleanup process) would go back to sleep and let the lower priority processes run. At one point I attempted to translate this all into Python, but the lack of the ability to set process priorities, or for processes to yield control to other processes, or an effective way to terminate proceses, kept me from doing this. The Python threading model seemed very primitve compared to what I was used to in regards to how threads can be controlled. Rather than being a knock on Python, I would prefer to know how to do all this, if it can be done. From engsolnom at ipns.com Tue Dec 30 14:44:05 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Tue, 30 Dec 2003 11:44:05 -0800 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: On Tue, 30 Dec 2003 18:30:56 +0100, Irmen de Jong wrote: >Hi >I have this dict that maps a name to a sequence of other names. >I want to have it reversed, i.e., map the other names each to >the key they belong to (yes, the other names are unique and >they only occur once). Like this: > >{ "key1": ("value1", "value2"), "key2": ("value3,) } > >--> > >{ "value1": "key1", "value2": "key1", "value3": "key2" } > >What I'm doing is using a nested loop: > >dict2={} >for (key,value) in dict1.items(): > for name in value: > dict2[name] = key > >which is simple enough, but I'm hearing this little voice in >the back of my head saying "there's a simpler solution". >Is there? What is it? ;-) > >Thanks >--Irmen. I had a need for a 'reverse' dictionary also. This is how I approached it: source_dict = {'A': 1,'B': 2,'C': 3,'D': 4} target_dict = {} for item in source_dict.iteritems(): target_dict[item[1]] = item[0] Or, a bit more contrived.... source_dict = {'A': [[1,2,3],100],'B': [[4,5,6],200],'C': [[7,8,9],300]} target_dict = {} for item in source_dict.iteritems(): target_dict[item[1][1]] = item[0] Disclaimer: I'm a newbie Norm From martin at v.loewis.de Tue Dec 23 04:47:30 2003 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 23 Dec 2003 10:47:30 +0100 Subject: global and None In-Reply-To: References: Message-ID: Leo Yee wrote: > Does anyone know what I should do to solve this problem? Thanks in advance. The global declaration must go in each function that uses the global variable, and not in the global namespace defining the variable (in the global namespace, it is clear that the variable is global, so no need to declare that). Regards, Martin From imbosol at aerojockey.invalid Sat Dec 20 12:55:27 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 17:55:27 GMT Subject: Default parameters References: <7xad5qqjg4.fsf@ruckus.brouhaha.com> Message-ID: Rainer Deyke wrote: > > > Carl Banks wrote: >> Now, do have any evidence that non-constant, default arguments (as >> they are now) are USEFUL? > > def draw_pixel(x, y, color, surface=screen): > screen[y][x] = color Was that so hard? (Although this would still work if surface was evaluated call time.) >> (I don't agree with your "consistent" theory, anyways. The function >> would be treating all arguments consistently: it's just that it'd get >> a fresh copy of the default arguments each call.) > > A function that mutates its arguments should not be called with "fresh" > arguments, implicitly or explicitly. If the purpose of the function is to > modify its arguments, then doing so would throw away the effect of the > function. If the purpose of the function is not to modify its arguments, > then it shouldn't do so. In the function: def a(b=[]): pass b=c is either part of the function, or part of the definition. If it's part of the definition, it gets evaulated once, and the function gets the same object each time. If it's part of the function, it gets evaluated every call, and b gets a new list every time. Either way is consistent. You ideas about what a function's purpose is are just not relevant to whether the time of evaluation is consistent. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From peri12345 at poczta.onet.pl Sat Dec 27 08:09:21 2003 From: peri12345 at poczta.onet.pl (Peri) Date: 27 Dec 2003 05:09:21 -0800 Subject: recursion in grammar? Message-ID: <34ea966a.0312270509.5ecc2095@posting.google.com> I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this: or_expr: xor_expr { "\|" xor_expr }, or rather or_expr: xor_expr ( "\|" xor_expr )* Do I think good? ANyone heard of Python grammar for ANTLR? From shuvit at 127.0.0.1 Tue Dec 2 11:07:43 2003 From: shuvit at 127.0.0.1 (David MacQuigg) Date: Tue, 02 Dec 2003 09:07:43 -0700 Subject: language learning vs. process References: Message-ID: On Tue, 2 Dec 2003 12:39:11 +0800, "Posadas, Dennis" wrote: [...] >To some extent Ryan may be right. Let's not get overboard >however and even have directions on how to turn on the computer. >We can strike a balance somewhere. I would not worry about going "overboard" for beginners, as long as it doesn't distract users who are beyond that stage. Python had its beginnings as a language for "everyone", meaning liberal arts majors, and others who might be new to computers. It is still the best language for that purpose, especially for students who might go on to more serious programming. We could avoid the distraction, and also help folks like the OP find the right stuff, by better organization of the materials that are already available, and perhaps adding one item, a beginner's page, where we can share code snippets, clarifications of difficult points, etc. When you look now at www.python.org, you see some nicely organized links, including "Beginner's Guide" Clicking on that link takes you to a full page of links with a brief description of each. So far, so good. Clicking on the "Examples and Sample Code" link takes you to a very sparse page with three links, including a Google search, the Python Cookbook, and the Python Standard Library. At this point, the beginner might start to feel overwhelmed. What we need is a bunch of *simple* examples, organized by topic, and searchable by keyword or author, and contributed by the people who care the most about these things, beginners who have just learned something interesting and would like to share it. Maybe this exists already, and I have just not found it. I must confess, I haven't done a thorough search. --Dave From dw-google.com at botanicus.net Sat Dec 20 12:19:42 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 20 Dec 2003 09:19:42 -0800 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: <99dce321.0312200919.3dd4af66@posting.google.com> "John Roth" wrote... > What I'm missing, however, is any *thoughtful* > discussion of the issues involved. Your [perjoritive > adverb deleted] response makes it clear that you > didn't think of the issues, you just reacted. The point he was making (in a rather convoluted way) is that optional parens is against the Python philosophy. "Explicit rather than implicit" being line 2. I would rather be forced to use empty parens after a function call - it shows you/others exactly what you are trying to do. On the other hand, I would detest Python if by simply referring to an object with a __call__ method caused it to be executed. I'd say that's closer to braindead. a = sys.exit a Unless you design some silly rules to determine when empty parenthesis should be allowed - did a get assigned the return value of sys.exit()? (yes I know it doesn't have one), or did some silly unclear (implicit) rules stop that from happening. Did sys.exit() run on the second line? I think if you can't understand why this option isn't provided for you, then you misunderstand some of the most fundamental Python concepts. import this. David. From mbabcock at fibrespeed.net Mon Dec 8 11:54:14 2003 From: mbabcock at fibrespeed.net (Michael T. Babcock) Date: Mon, 08 Dec 2003 11:54:14 -0500 Subject: Efficient MD5 (or similar) hashes In-Reply-To: References: Message-ID: <3FD4ACB6.4000608@fibrespeed.net> > I have large files I'm dealing with. Some 600MB -1.2 GB in size, over > a slow network. Transfer of one of these files can take 40 minutes or > an hour. > > I want to check the integrity of the files after transfer. I can > check the obvious - date, file size - quickly, but what if I want an > MD5 hash? > > From reading the python docs, md5 reads the entire file as a string. > That's not practical on a 1 GB file that's network mounted. The *obvious* answer is that the MD5's have to be available as files on the network mount, made by whatever / whoever put the files there in the first place, much like those available for large / secure downloads online in many places. That is to say, you use an MD5 tool (md5sum / Python / etc.) to calculate the MD5 hashes *locally* to the files, then download both the file and the MD5 hash to your machine and re-check the hash and compare. I'm not sure if I'm missing something in what you intend to do here ... if you've got a an NFS mount of ISO files for RedHat 9, you'd have: /mnt/remote: redhat9-disc1.iso redhat9-disc1.iso.md5 redhat9-disc2.iso redhat9-disc2.iso.md5 redhat9-disc3.iso redhat9-disc3.iso.md5 You could do: $ (cat /mnt/remote/redhat9-disc$i.iso.md5; md5sum /mnt/remote/redhat9-disc$i.iso) ... and compare the two output lines (or use Python to compare, to keep this on-topic). But you're complaining this would be slow. If you could explain what you'd *like* to have happen, that would be great -- are you going to copy the files locally before comparing the MD5 hashes? That makes the above quite simple. PS, You need realize that calculating a hash on a file *requires* reading every byte of data in the file since otherwise it would be a pretty useless hash function and wouldn't actually detect errors. -- Michael T. Babcock C.T.O., FibreSpeed Ltd. http://www.fibrespeed.net/~mbabcock From fortepianissimo at yahoo.com.tw Sun Dec 21 20:24:24 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 21 Dec 2003 17:24:24 -0800 Subject: test if a file is locked? Message-ID: I can lock a file using the following snippet: --- import fcntl f=open('flock.txt','w') fcntl.lockf(f.fileno(),fcntl.LOCK_EX) --- If some other script tries to open 'flock.txt', it'll wait until the file is unlocked/closed. My question is, I'd like to tell a script to quit *immediately* if it cannot open the file, or, if it knows the file is locked. The reason I need this is I want to serialize parallel processes using a lock file. Any suggestion is welcome! From km at mrna.tn.nic.in Mon Dec 22 12:47:03 2003 From: km at mrna.tn.nic.in (km) Date: Mon, 22 Dec 2003 23:17:03 +0530 Subject: manpage of python 2.3? In-Reply-To: <3FE728A7.7030608@none.net> References: <3fe63429$0$242$e4fe514c@news.xs4all.nl> <3FE728A7.7030608@none.net> Message-ID: <20031222174703.GA16062@mrna.tn.nic.in> On Mon, Dec 22, 2003 at 06:23:51PM +0100, Iwan van der Kleyn wrote: > >so, is there a real manpage for python2.3. around? > > Python doesn't come with extensive man pages like for example Perl (man > perintro etc). On Debian Linux there's a rather rudementary man page, > showing possible command line options. > > http://www.die.net/doc/linux/man/man1/python.1.html > > Of course, you could use links/lynx to view Python's excellent html > documentation from the console. may be excellent but not as comfortable as of Perl documentation on the system. well thats a poor feature of Python. KM From jan at jandecaluwe.com Tue Dec 9 15:41:08 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Tue, 09 Dec 2003 21:41:08 +0100 Subject: cell object dereferencing In-Reply-To: References: <3FD5FD4A.9060406@jandecaluwe.com> Message-ID: <3FD63364.2040605@jandecaluwe.com> Terry Reedy wrote: > "Jan Decaluwe" wrote in message > news:3FD5FD4A.9060406 at jandecaluwe.com... > >>Is there a way to dereference a cell object (that is, get >>the object that it references to) in Python? > > > [Background: a cell is an undefined internal implementation object used to > make nested scoping work as advertised. One might think of it as a means > for persisting cross-scope name-binding of objects in intermediate nested > scopes of nested functions. Alternatively, a cell is 'persistent read-only > shadow of an outer local'. For nested functions that access intermediate > locals, .func_closure is a tuple of 'cells'.] > > Yes and no, depending on what you mean be 'dereference'. Within the nested > function, you 'dereference' the variable the same way you do any bound > ame -- write it! Outside the function, where the variable has no > conceptual existence, you can grab a cell from the func_closure tuple, but I > know of no way to access its value. This is what is mean - so I guess the answer is no. >Both repr() and str() return a xxx: type at yyy> description. If you want a globally accessible value, use > a global variable. The background is that I am writing a small compiler that translates a (small) subset of Python into another language. I would like to be able to support free variables as they are likely to be useful in the kind of code I'm targetting. However, I need to be able to inspect the corresponding objects for their type etc. Conceptually this should be possible, just as with globals and locals of functions and frames, but in practice it seems it isn't - a real pity for which I hope to find a workaround. Regards, Jan -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From mfranklin1 at gatwick.westerngeco.slb.com Tue Dec 2 03:19:52 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 02 Dec 2003 08:19:52 +0000 Subject: NumTut corrupted In-Reply-To: References: <3FCBFD55.52A43F03@engcorp.com> Message-ID: <1070353192.1239.3.camel@m-franklin> On Tue, 2003-12-02 at 04:34, r.e.s. wrote: > "Peter Hansen" wrote ... > > "r.e.s." wrote: > > > > > > No matter which site I download it from, > > > NumTut.tgz appears to be corrupted. > > > Anyone else having this problem? > > > > Always describe the symptoms of a problem... what precise > > behaviour (i.e. what extraction program, platform etc.) are > > you encountering that leads you to believe it's corrupted? > > Quite right, sorry. > > I resolved the problem, but will explain what happened > in case others encounter something similar ... > > The file called NumTut.tgz at the SourceForge.net > download server is, when downloaded, automatically > receiving the wrong file extension by winXP . > (WinZip then produces a file that looks like a .py > file corrupted by lots of 'unprintable' characters.) > > That is, clicking NumTut.tgz for download results in > "You are requesting file: /numpy/NumTut.tgz > Please select a mirror" > > but the winXP File Download window that comes up says > File name: NumTut.gz (sic) > File type: WinZip File > > If renamed back to .tgz, WinZip decompresses it > properly, and I see that it's actually a number of > files which are python-importable when placed in > the folder ...\Numerical\NumTut. > > (Also for other files from that site, I've sometimes > had to re-download when the file is found not to be > in recognizable format. This problem seems to occur > only for files downloaded from SourceForge, btw.) > > ===== > A related python question, if I may ... > > With the various .py files in \Numerical\NumTut, > *none* of which are named NumTut.py, why does this > work? ... > > >>> from NumTut import * > > Surely import doesn't use the folder name? As you > can see, I'm a beginner at python. > Yes it is using the folder name. In this case there would be a file named __init__.py inside the NumTut folder and the existance of this file makes that folder a python package. For more on python packages (and more): http://www.python.org/doc/current/tut/node8.html#SECTION008400000000000000000 (Above link may get wrapped by some news/mail readers) Regards Martin From usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org Sat Dec 27 21:07:16 2003 From: usenet-86956bd8eeb44fe359b60bcf1ff099d4 at juvonen.org (Sami Juvonen) Date: Sun, 28 Dec 2003 02:07:16 GMT Subject: Project dream References: <7xwu8jp1xr.fsf@ruckus.brouhaha.com> Message-ID: On 26 Dec 2003 15:57:36 -0800, Paul Rubin <> blurted: > hwlgw at hotmail.com (Will Stuyvesant) writes: > > What would your favorite be? > > A CVS-like system for email. You'd receive all your messages on a > server somewhere. You'd then be able to connect your laptop to the > internet, download ("check out") your mail, and read and reply to it You might be interested in OfflineIMAP. http://gopher.quux.org:70/devel/offlineimap -- "...you want a .sig with that?" From frobozz_electric at hotmail.com Wed Dec 3 13:36:54 2003 From: frobozz_electric at hotmail.com (Sean Ross) Date: 3 Dec 2003 18:36:54 GMT Subject: Adding method to object References: <72krsvcpeur8hhu74s4bhlsq3bf60fu055@4ax.com> Message-ID: "marco" wrote in message news:bql820$uka$1 at s1.read.news.oleane.net... > > > Is it possible to do the same thing for an attribut, instead of a method > ? > > > > > > i'd like to wrap an newAttribute to an oldAttribute one : > > > example: > > > i've got an instance "n" of an "xmlNode" class > > > i'd like to use "n.parentNode" instead of "n.parent" ... > > [snip] > > > > # try this ... > > n.parentNode = n.parent > > i'll try, > but ... it s not dynamic .... > > if n.parent change .... n.parentNode will not change ... it must be > re-affected ... not ? > You're right. Sorry about that. Maybe you could use a property? n.__class__.parentNode = property(lambda self: self.parent, ... etc ... ) This way you can get/set/del n.parent using n.parentNode, and changes to n.parent will be reflect in n.parentNode. There's probably another way, but I can't think of it at the moment... Hope that's a little more helpful than the last suggestion, Sean From imbosol at aerojockey.invalid Fri Dec 19 22:18:26 2003 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 20 Dec 2003 03:18:26 GMT Subject: semi-OT: DNS issues for python.org (re-send) References: Message-ID: <6cPEb.22794$031.13001@fe3.columbus.rr.com> Ben wrote: > Hi all, > I'm seeing a lot of "lame server" messages from my name server > when trying to resolve mail.python.org and neither my name server > (devious.adversary.org) nor those of my upstream > (yarrina.connect.com.au & warrane.connect.com.au). In fact, one of my > upstream's caches (yalumba.connect.com.au) is locating what appears to > be invalid nameservers for python.org. > > Yalumba believes python.org's nameservers are ns53.worldnic.com & > ns54.worldnic.com. While tracking back from UltraDNS points to > ns.xs4all.nl & ns2.xs4all.nl. > > So does anyone know if there are currently any registration or > delegation issues with python.org or if they are seeing similar things > elsewhere? Creepy. A whois search said that python.org wasn't registered.... Good thing Python's trademarked. As a workaround, the web page is accessible at pythonlabs.com. Not sure if mail is. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From nessus at mit.edu Sun Dec 7 10:31:13 2003 From: nessus at mit.edu (Douglas Alan) Date: Sun, 07 Dec 2003 10:31:13 -0500 Subject: Lists and Tuples References: <7x7k1b4yqn.fsf@ruckus.brouhaha.com> Message-ID: "Fredrik Lundh" writes: > as expected, you spent that thread attacking everyone who dis- > agreed with you, misrepresented other people's arguments, referred > to implementation artifacts and design mistakes as "proof", and used > the same muddled thinking as you've shown in this thread. heck, > Tim even introduced the term "douglas-sequences" in contrast to > "python-sequences" in order to make any sense of what you were > arguing about that time. not the kind of behaviour I'd expect from > anyone who wants to be taken seriously. Your characterization of the past debate is not only a self-serving caricature, but it is disingenuous as well. I never attacked or misrepresented anyone -- I merely disagreed with them. Only you attacked anyone, Fredrik. As you chose to do again. And misrepresent. > two years later, you haven't learned a thing; that's pretty tragic. And you still resort to insults, rather than reason. Yes, tragic, especially for someone who is apparently an icon of the Python community. And speaking of "proof" for one's point -- you never provided a single iota of evidence, much less proof, for the idea that tuples should only be used as records, except for that you and Guido say so. |>oug From jjl at pobox.com Tue Dec 23 10:01:33 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Dec 2003 15:01:33 +0000 Subject: Naming conventions for iterator methods? References: <87fzfch0bu.fsf@pobox.com> Message-ID: <87fzfbefxu.fsf@pobox.com> Peter Otten <__peter__ at web.de> writes: > John J. Lee wrote: [...] > My personal naming convention is not yet stable, but I currently favour > foos(). I think iterkeys() etc. were only introduced because there already > were methods like keys() returning the corresponding list. > These I now tend to omit and instead make it explicit when I need a list, e. > g. > > alltags = list(parser.tags()) Yeah, I think you're right on both counts. > and instead of parser.filtertags(pred): > > sometags = [t for t in parser.tags() if pred(t)] Yes. Also, I have keyword arguments to some .foos() methods. > When all returned sequences are iterators, a special prefix/suffix seems > pointless and you may wonder how to name the few exceptions: > > list_foo(), foo_list(), listfoo(), foolist(), foos(), ... But a sequence is not an iterator, IIRC, because it doesn't have a .next() method. It just "supports the iterator protocol" by virtue of having an .__iter__() method that returns an iterator (which has both .next() and .__iter__()). John From shalabh at gameboard.org Mon Dec 15 23:27:39 2003 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: 15 Dec 2003 20:27:39 -0800 Subject: Jumping around when assigning elements References: <1e963607.0312151408.583221e6@posting.google.com> Message-ID: matt at killermookie.org (Matthew Sims) wrote in message news:<1e963607.0312151408.583221e6 at posting.google.com>... > For lists, I understand this: > C=["need","some","help"] > print C[1] > some > > But I can't seem to do this: > C[3]="here" > > I know about C.append("here") but this brings me to my question... > > Is there anyway to assign to an element that wasn't defined in the > beginning? Like if I wanted element 5 assigned but not element 4 > without using "" or None? You could try using a dictionary instead of a list. You could even initialize the dict from the list: l = ["just", "a", "suggestion"] d = {} for k,v in enumerate(l): d[k] = v d[10] = "here" Of course, to get at the values now, you would need to iterate over d.values(). Note that you won't necessarily get the values in sorted order of keys. You would have to do that explicitly if you want. -- Shalabh From andymac at bullseye.apana.org.au Sun Dec 28 17:56:37 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 29 Dec 2003 09:56:37 +1100 (EST) Subject: 2.3 list reverse() bug? In-Reply-To: References: <27umuvkmnbnk6qsdgbh7em35ekga1od1jv@4ax.com> <7xbrpt6698.fsf@ruckus.brouhaha.com> Message-ID: <20031229094739.D27277@bullseye.apana.org.au> > Apparently, these miniscule extra bits of overhead appear to be enough > for Andrew to reject the "essentially equivalent" evaluation. You have misconstrued the intent of my observation, which was simply to highlight that there may be a reason other than aesthetics to choose one of the 3 alternatives. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From martin at v.loewis.de Thu Dec 18 16:33:52 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 18 Dec 2003 22:33:52 +0100 Subject: [Python-Dev] rexec.py unuseable In-Reply-To: <20031218092922.GF6324@lkcl.net> References: <20031215173156.GC25203@lkcl.net> <16349.63203.797449.677617@montanaro.dyndns.org> <20031215191023.GB26055@lkcl.net> <1071524194.15985.660.camel@localhost.localdomain> <20031215233639.GE26055@lkcl.net> <20031216195525.GJ17021@lkcl.net> <20031216212312.GL17021@lkcl.net> <20031218092922.GF6324@lkcl.net> Message-ID: Luke Kenneth Casson Leighton writes: > so, with the correct codebase reordering, a simple capabilities > based system can be added, the problem goes away. > > yes? I still don't see how it could, and I believe I understand pretty well what kind of feature you propose. Restricted execution is just something completely different. Regards, Martin From bmgz at dev.null Wed Dec 24 04:01:06 2003 From: bmgz at dev.null (bmgz) Date: Wed, 24 Dec 2003 11:01:06 +0200 Subject: replace line #1 with "newline\n" in text file Message-ID: <3fe955b8.0@news1.mweb.co.za> Hiya, I am trying to replace the first line of a config file.. with a new string been googlizing and reading the python manual.. but can't find what I need.. it's all rubbish about bits and bytes etc.. From bokr at oz.net Wed Dec 3 19:43:22 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Dec 2003 00:43:22 GMT Subject: In a function, how to get the caller object ? References: <7eecf173.0312030656.7aaf405e@posting.google.com> Message-ID: On 3 Dec 2003 06:56:06 -0800, google at evpopov.com (popov) wrote: >Look at this code: > >class C: > def func(): > .my_attrib = 1 > func = staticmethod(func) > >C.func() > >c = C() >c.func() > >In func, I would like to get C for the first call, and c for the >second one, to be able to add a new attribute to this object (so that >would add the attribute either to the class object or to the >instance). How can I do this ? >I tried to give a look to the inspect module with no luck. You need something other than staticmethod, that delivers an ordinary method or an effective classmethod depending on access via the class or an instance, e.g., (not tested beyond what you see): (BTW, I added a value parameter to your func, for less ambiguous example results) >>> class SpecialMethod(object): ... def __get__(self, obj, cls): ... if obj is None: return self.fun.__get__(cls, cls) ... else: return self.fun.__get__(obj, type(obj)) ... def __init__(self, fun): ... self.fun = fun ... >>> class C(object): ... def func(caller_of_func, value=1): ... caller_of_func.my_attrib = value ... func = SpecialMethod(func) ... >>> C >>> C.func > >>> vars(C) >>> vars(C).keys() ['__dict__', '__module__', '__weakref__', '__doc__', 'func'] The above shows not my_attrib >>> C.func() >>> vars(C).keys() ['__module__', 'my_attrib', 'func', '__dict__', '__weakref__', '__doc__'] But after C.func() it is there >>> C.my_attrib 1 now we make an instance >>> c=C() >>> c.func > looks like an ordinary bound method (though defined with "caller_of_func" in place of "self"). >>> c.func('another value') >>> c.my_attrib 'another value' >>> C.my_attrib 1 The instance attribute shadows the class attribute, so we can uncover the latter by deleting the former: >>> del c.my_attrib >>> c.my_attrib 1 That's really C.my_attrib found through standard attribute search. To get more info, read about descriptors. Regards, Bengt Richter From vivek at cs.unipune.ernet.in Tue Dec 23 05:09:20 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Tue, 23 Dec 2003 15:39:20 +0530 Subject: font list on current OS In-Reply-To: <20031223081007.91982.qmail@web21324.mail.yahoo.com>; from quiteblack@yahoo.com on Tue, Dec 23, 2003 at 12:10:07AM -0800 References: <20031223112447.A23202@cs.unipune.ernet.in> <20031223081007.91982.qmail@web21324.mail.yahoo.com> Message-ID: <20031223153920.A27970@cs.unipune.ernet.in> On Tue, Dec 23, 2003 at 12:10:07AM -0800, black wrote: > i searched tkFileDialog module but found no font dialog prototypes, just savedialog and opendialog etc. > > Regards~ I thought you asked for __File Dialog__ :-). Anyway to get the list of all the available fonts on the system use the tkFont.families() function. It will return a list of all the available font families/names on the machine. Regards Vivek Kumar > > vivek at cs.unipune.ernet.in wrote: > On Mon, Dec 22, 2003 at 08:00:51PM -0800, black wrote: > > Hi all~ > > > > Ooops when i was diving into Tkinter widgets just found no File Dialog avai ^^^^^^^^^^^ > > open the module docs (pydoc) and look at tkFileDialog. It provides you with various functions for opening file dialogs of different types. > > Regards > Vivek Kumar > > --------------------------------- > Do you Yahoo!? > Free Pop-Up Blocker - Get it now From hokiegal99 at hotmail.com Mon Dec 22 12:41:03 2003 From: hokiegal99 at hotmail.com (hokieghal99) Date: Mon, 22 Dec 2003 12:41:03 -0500 Subject: Count Files in a Directory In-Reply-To: References: <93f5c5e9.0312211545.363b91a6@posting.google.com> Message-ID: hokieghal99 wrote: > def fs_object_count(setpath): > file_count = 0 > dir_count = 0 > for root, dirs, files in os.walk(setpath): > file_count += len(files) > dir_count += len(dirs) > return file_count, dir_count > > I'm using this. Thanks to all for the tips and corrections! It works > very well on small sets of data (<= 5GB) it is very accurate on this > data. On largeer (> 20GB) filesystems, the count will be off by 30 to 40 > objects. For example on one 22GB filesystem the OS thinks there are > 100,222 objects in the path, Python thinks there are 100,260... Any > ideas on this difference? > > Thanks!!! > Woops... I spoke too soon. Just caught this difference on 4.4GB of data. The os thinks there are 12,204 objects in the path while Python thinks there are 12,205 objects. From andrew-pythonlist at puzzling.org Wed Dec 3 08:50:44 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 4 Dec 2003 00:50:44 +1100 Subject: Asynchronous SimpleXMLRpcServer In-Reply-To: <3fcdd76e$0$251$4d4ebb8e@news.nl.uu.net> References: <3fcdd76e$0$251$4d4ebb8e@news.nl.uu.net> Message-ID: <20031203135044.GA24258@frobozz> On Wed, Dec 03, 2003 at 01:30:40PM +0100, Guyon Mor?e wrote: > hi all, > > maybe this is a stupid question, but I'll ask it anyway. > > does the SimpleXMLRpcServer handle connection asynchronous? I don't think it does, as it just uses SocketServer. > if not, how can I make it asynchronous? This isn't exactly what you asked, but you can do asynchronous XML-RPC easily with Twisted. Here's some example code: http://twistedmatrix.com/documents/examples/xmlrpc.py The docs for the XML-RPC support are here: http://twistedmatrix.com/documents/howto/xmlrpc -Andrew. From max at theslimmers.net Sun Dec 21 13:48:23 2003 From: max at theslimmers.net (max) Date: 21 Dec 2003 10:48:23 -0800 Subject: Problem mapping VB com code to Python References: <4f55e45a.0312191451.73b8f84b@posting.google.com> Message-ID: <4f55e45a.0312211048.4fc090a@posting.google.com> No luck, I have tried all possible case combinations and permutations of what I see in the com brouser. The only place I have found references to the com module qbFC2_1Lib is in the "Registered Type Libraries". Is there another way to access the com module then client.Dispatch()? What is the mapping of the VB statememnt " Dim sessionManager As New QBFC2_1Lib.QBSessionManager" does this imply something other than late binding. When I ran makepy it generated a file containing lots of information about the module, I don't know how to figure out what it means. How is the output of makepy used, can it tell me something about how to connect to the corresponding COM module> I am really at a loss here, I don't understand enough about COM or VB to figure this out. max "Ahmed MOHAMED ALI" wrote in message news:... > Hello, > > try this > > obj = win32com.client.Dispatch("QBFC2_1.QBSessionManager") > > Ahmed > > "max" wrote in message > news:4f55e45a.0312191451.73b8f84b at posting.google.com... > > I am trying to use a sdk to access quickbooks, the sdk provided a COM > > interface and I think it installed the com server files/dlls. A VB > > code example is provided, but I can't figure out how to map "Dim > > sessionManager As New QBFC2_1Lib.QBSessionManager" > > into a corresponding Python statement, when I try > > obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get > > traceback Shown below. > > > > I have been able to run makepy and it generates a lovely file. I can > > find a Type Library, but need a little help mapping this to be able to > > access the com object and call its methods. > > > > I have included a snipit of the sample VB code and the traceback from > > my attempt to create a client com object ? > > > > Any help much appreciated, > > > > max > > > > > > > > =======Traceback ============= > > >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > > line 95, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 84, in _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 72, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147221005, 'Invalid class string', None, None) > > > > > > > > > > ========= Sample VB code ========== > > Option Explicit > > > > Public Sub Main() > > > > On Error GoTo ErrHandler > > > > 'Establish a communication channel with QuickBooks > > > > 'Create the session manager object, and initiate a conversation > > with QuickBooks > > Dim sessionManager As New QBFC2_1Lib.QBSessionManager > > sessionManager.OpenConnection " ", "QBFC Developer's Guide" > > sessionManager.BeginSession "", omDontCare > > > > > > 'Build a set of requests - in this case, containing only one > > request > > > > 'Create the request set (the message set request object) > > Dim requestSet As QBFC2_1Lib.IMsgSetRequest > > 'Create a qbXML version 2.1 message > > Set requestSet = sessionManager.CreateMsgSetRequest(2, 1) > > > > 'Add a request to the request set. > > Dim customerAdd As QBFC2_1Lib.ICustomerAdd > > 'AppendCustomerAddRq is called only once here, even though two > > values are being set. > > Set customerAdd = requestSet.AppendCustomerAddRq > > customerAdd.Name.SetValue "Joe" > > customerAdd.CustomerTypeRef.FullName.SetValue "East Coast" > > > > 'Indicate that all requests should be processed, even if one has > > an error > > requestSet.Attributes.OnError = roeContinue > > > > > > 'Send the request set to QuickBooks > > > > Dim responseSet As QBFC2_1Lib.IMsgSetResponse > > Set responseSet = sessionManager.DoRequests(requestSet) From gautam at cins.unipune.ernet.in Mon Dec 15 05:08:50 2003 From: gautam at cins.unipune.ernet.in (Gautam Pagedar) Date: Mon, 15 Dec 2003 10:08:50 -0000 Subject: ouput redirection..a newbie question Message-ID: <1008670585.21577.4.camel@gautam> Hello, i am new to python and need a basic answer. Hope someone would help me solve this. I want to execute a command ls -l and sore its result in a file. >>import sys >>import os >>os.system("ls -al") executes the command how can i redirect the to a file like we do in shell script using a redirection operator. Waiting for reply. Regards, Gautam Pagedar. From timr at probo.com Sun Dec 14 23:34:34 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 14 Dec 2003 20:34:34 -0800 Subject: Simple question from Python Newbie References: Message-ID: <83eqtvgdadtv80564iiv8t83ubqts4fh7e@4ax.com> "Phil D." wrote: > >Hello Python Hackers! > >I just started working with Python a few days ago and have a simple >question that I can't seem to figure out. I am trying to build an >application to monitor my mouse moving habits while I'm surfing >the web for a project at MIT and I can't seem to figure out how >to capture mouse clicks. Actually, this is not a particularly simple question. The issue is that it isn't related to Python at all: this is an operating system issue. An application is expected to be interested only the events that relate directly to that application. Doing so on a system wide basis is usually only interesting for toy apps, such as the one you want to build. Fortunately, Windows provides a way to do that: it's called a "hook". In this case, what you want is the "journal record hook" (WH_JOURNALRECORD), which gets all key and mouse events in the system. This requires a callback, which means it needs C help. I don't know if it is implemented in any of the Win32 extensions; I will have to investigate that (and hope someone like Mark Hammond posts the canned answer). >Thoughts anyone? What's the easiest way to get mouse clicks outside of a GUI? Your terminology is a bit confusing. The entire desktop is "a GUI". What you really want is to get mouse clicks outside of your own process. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jdhunter at ace.bsd.uchicago.edu Mon Dec 8 18:20:27 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 08 Dec 2003 17:20:27 -0600 Subject: How to graph two columns of x,y numbers? In-Reply-To: ("Colin J. Williams"'s message of "Mon, 08 Dec 2003 14:03:51 -0500") References: <9b849915.0312071252.6af171db@posting.google.com> <3FD3E423.B53D23DE@engcorp.com> <9b849915.0312072230.5cab87b0@posting.google.com> Message-ID: >>>>> "Colin" == Colin J Williams writes: Colin> Todd, If you are using wxPython, you might consider Colin> wxPyPlot: Colin> http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html Also matplotlib has a wxpython backend now. It's about a week away from being ready, but there is a reasonably good development version at http://matplotlib.sourceforge.net. JDH From robert_dodier at yahoo.com Mon Dec 29 11:59:09 2003 From: robert_dodier at yahoo.com (Robert Dodier) Date: 29 Dec 2003 08:59:09 -0800 Subject: Special-purpose extension of Python -- new kinds of objects References: <6714766d.0312281442.78cd0a4b@posting.google.com> Message-ID: <6714766d.0312290859.280530d5@posting.google.com> Jeff Epler wrote: > In your case, you could re-cast the "decision network" in terms of class > definitions, and get pretty similar behavior if those classes have the > right behavior in metaclasses: [...] I'd rather not try to shoehorn the decision model description into a description in terms of Python classes. I'd like to try to keep the description as natural as possible. > If you're very fond of your syntax, then consider using strings > as the easiest way. Docstring abuse has been seen before, and > would look something like this: [...] I've implemented similar systems by loading files in one format or another -- XML was the latest attempt; I won't be trying that again -- and, to explore just how far the integration with Python can be taken, I'm wondering what it would take to merge the model description with Python. I'd like to have Python in the model (to return probability & utility values) as well as model in the Python. > There is a languishing PEP about exposing the Python parser generator to > Python code, so that you could write your own grammar with the same > level of power as Python's grammar. There are lots of other package, > such as yapps and spark which are also suitable for writing parsers. Yes, I've seen the PEP in question (PEP 269), I'll take a closer look. I'll look at yapps and spark too. > Once you have a parser and use external files, it's possible to extend > Python's import system to load files of your type automatically with > the import statement. This is an advanced topic, though. Well, that's not out of the question. Can you give a reference to a starting point for hacking on the import system? Thanks for your interest. I appreciate your help. Robert Dodier -- ``Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony.'' -- Dennis (MP&THG) From newsgroups at jhrothjr.com Sun Dec 21 17:37:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 21 Dec 2003 17:37:10 -0500 Subject: UserLinux chooses Python as "interpretive language" of choice References: Message-ID: "Bengt Richter" wrote in message news:bs541e$8l2$0 at 216.39.172.122... > On Sun, 21 Dec 2003 07:41:40 -0500, "John Roth" wrote: > > > > >"Bengt Richter" wrote in message > >news:bs2j3b$fc5$0 at 216.39.172.122... > >> On Sat, 20 Dec 2003 06:38:20 -0500, "John Roth" > >wrote: > >> What would be the syntax you would like to use, with what effect? > > > >Well, the basic idea was simply to make the () optional for functions > >with no parameters. No particular syntax there but it would require some > >major jump through hoops gyrations from the virtual machine, and there > >would have to be some way of getting the function object when you > >wanted it, and I suspect the difference between a function object and > >a more general 'callable' would totally confuse most people. And of > >course, does a function/method with only keywords count as a function > >with no parameters? > > > >Ruby can get away with it because, as far as I know, functions are not > >first class objects. They certainly aren't in Perl which was Ruby's > >inspiration. > > Really? Perl was Ruby's inspiration?? One of them. There's a bit of this and that, but overall it seems a bit more Perlish than Pythonish. I've never gotten a satisfactory answer about how it's "more object-oriented" than Python, unless they mean that it uses methods instead of built-in functions. > >It's a non-starter for Python, though. > Seems so. OTTOMH I guess you could have the tokenizer generate two kinds of names, > names_as_now, and bare_names (tagged so with lookahead determining no trailers). > Then you could dynamically check if a bare_name was referring to a callable, and > call it with no params if so, and for all other name usage do as now. Except that as > you point out, you'd need a way to inhibit the effect. But since this thing would be > unusual (and would cause major breakage), maybe it could be enabled only for references > to objects with an __autocall__ alias to their __call__ attribute. And then, since the > auto-call would only happen for bare names, you could pass it as a function by using > name.__call__ instead of name. Or use vars()['name']. I think that's getting a bit baroque. In fact, after my previous post, I realized that I had an unnecessary complexity: it's simpler to just auto-execute "all" functions, and let the ones that require parameters and don't have them fail like they do today, rather than try to make a distinction. It puts the VM through quite a few less hoops: all that really has to be done is duplicate the various opcodes that can fetch a function object, so that one of each pair autoexecutes and the other doesn't. Then the parser can decide which to generate based on whether there is a parameter list following, and also on whether the "magic" syntax for retreiving the function object without auto-executing it is present. I suspect it's also easier to explain: funtions and methods are what are declared with def and lambda, and if it's not that, then it's not going to autoexecute regardless of whether it has a __call__ method. Adding classes to the list might be useful as well, but anything more would lead, I suspect, to too much confusion. It's still a non-starter, though John Roth > Not that I am proposing this ;-) > > Regards, > Bengt Richter From nospam at nowhere.com Mon Dec 8 22:25:46 2003 From: nospam at nowhere.com (Courageous) Date: Tue, 09 Dec 2003 03:25:46 GMT Subject: Why Python won't work on .net References: <20031207112217.14343.00000306@mb-m14.aol.com> <4redncaHtOe2LEmiRVn-ig@comcast.com> Message-ID: >> The main problem is that functions are first class objects in Python, but >> not in the CLS. Functions are only addresses in C, the (main) language Python is implemented in. C// From exarkun at intarweb.us Tue Dec 23 09:23:24 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 23 Dec 2003 09:23:24 -0500 Subject: Naming conventions for iterator methods? In-Reply-To: References: <87fzfch0bu.fsf@pobox.com> <20031223021642.GA15171@titan.progiciels-bpi.ca> Message-ID: <20031223142324.GA24802@intarweb.us> On Tue, Dec 23, 2003 at 01:14:19PM +0000, John J Lee wrote: > [snip] > > I just realised some of these methods of mine don't actually return > iterators, but merely objects supporting the iterator protocol. In other > words, the returned objects have an .__iter__() method, but not a .next() > method (usually because I've quickly implemented the method by returning a > sequence, leaving the way open for a later reimplementation that, eg., > returns a lazy iterator). Would that surprise people from a method named > .iter_foo()? > Yes. return "iter(something)" instead of just "something". Jp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From image9n at hotmail.com Sat Dec 6 18:23:54 2003 From: image9n at hotmail.com (Agency) Date: 6 Dec 2003 15:23:54 -0800 Subject: Nub needs help withTkinter Message-ID: <1cca69c7.0312061523.6b73b4fa@posting.google.com> I'm trying to program a utility that counts the beats per minute in a song by tapping the spacebar. I already have a program that does this, but I wanted to make my own. The "enter" key resets the counter to zero along with one of two displays. I'm importing Tkinter and this is what I have so far. I get a syntax error at this spot -----> Any thoughts how to get the keypress to increase the counter better? Is it possible to convert it to an int or something? ------------------------------------------------------------------ from Tkinter import * root = Tk() w = Label(root, text="The BPM Counter") w.pack() class display1: def beat(): beat = 0 if beat > 10000: beat += root.mainloop() ------------------------------------------------------------------- From mwh at python.net Mon Dec 29 16:19:47 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Dec 2003 21:19:47 GMT Subject: [Mailman-Developers] python is slow References: <3FE20578.7060402@gmx.at> <1072458360.4458.13.camel@anthem> Message-ID: "John Roth" writes: [1.5.2 v 2.3 performance] > You're probably right. Now that you mention it, I believe > I've heard that 2.0 was the big slowdown, I think rich comparisons in 2.1 gave a bit of a hit, too. > and then it's improved from there. 2.3, for example, is quite a bit > faster than 2.2. I know -- I'm partially responsible for that :-) (although only if you don't run python -O). Cheers, mwh -- ... but I'd rather not reinvent the wheel if I don't have to. On the other hand, if the currently instantiated version of the wheel consists of a square rock covered with moss, I might as well just start fresh. -- Roy Smith, comp.lang.python From fredrik at pythonware.com Thu Dec 11 10:34:51 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Dec 2003 16:34:51 +0100 Subject: Preview of a Stackless Zope Application References: Message-ID: Istvan Albert wrote > > Let me know your thoughts... > > > > http://www.centera.de/tismer/stackless/zope_demo > > Seems to work only of I allow the site to set > a cookie and thus retrieve a session. But if so > doing the same thing the old fashioned way is > also very simple. your lack of imagination is rather stunning. From cookedm+news at physics.mcmaster.ca Fri Dec 5 16:50:36 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 05 Dec 2003 16:50:36 -0500 Subject: Creating a List of Empty Lists References: <8089854e.0312040649.4a7f1715@posting.google.com> <8089854e.0312050419.2cf36e34@posting.google.com> Message-ID: At some point, "r.e.s." wrote: > But something's wrong with that explanation, because > of the following: > > >>> a = 'gobble' > >>> a is 'gobble' > True > > Surely `'gobble'` is not the name of an already-existing > object, so I expected exactly the same result as for > `100` and `[]`. What's going on there? Actually, your second use of 'gobble' *is* an already-existing object. Python 'interns' string constants, i.e., reuses them. Check this out >>> a = 'gobble' >>> a is 'gobble' True >>> a is ('gob' + 'ble') False >>> a = 'gob' + 'ble' >>> a is 'gobble' False Here, the constants 'gobble', 'gob', and 'ble' are interned. Computed strings are not looked up and replaced, so 'gob' + 'ble' is not 'gobble'. Compare with (in a new interpreter!) >>> a = 'gob' + 'ble' >>> intern(a) 'gobble' >>> a is 'gobble' True Here, we've explicitly interned the result of 'gob' + 'ble', so it is the same as 'gobble'. But, don't depend on interning. Use == to compare strings. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From max at cNvOiSsiPoAnMtech.com Tue Dec 9 16:50:27 2003 From: max at cNvOiSsiPoAnMtech.com (Maxim Khesin) Date: Tue, 09 Dec 2003 21:50:27 GMT Subject: closing file opened by csv reader In-Reply-To: References: Message-ID: How about f = open('bla') csv_reader = reader(f) for row in csv_reader: process(row) f.close() ? Paul Phillabaum wrote: > I'd like to close the file the "reader" opens, but I can't figure out how to > reference it. > > example: > reader2=csv.reader(file('blah.csv')) > > if reader2 was a normal file, I would do "reader2.close()" but that doesn't > work. > > I won't show any of the more wacky attempts I made based on my limited > experience as they'd just reveal my total ignorance of this part of python. > I did look through the dictionary for the reader object but couldn't find > what I needed. > > Thanks! > > Paul > > > > > > From bmgz at dev.null Sun Dec 14 04:15:04 2003 From: bmgz at dev.null (bmgz) Date: Sun, 14 Dec 2003 11:15:04 +0200 Subject: gzip module - help! Message-ID: <3fdc2a06.0@news1.mweb.co.za> I am having problems trying to use the gzip module, I do the followig >>>import gzip >>>file = gzip.GzipFile("testfile.txt") >>>file.write() -which params does this accept?, archive name? I get this ERROR: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/gzip.py", line 139, in write self.size = self.size + len(data) AttributeError: GzipFile instance has no attribute 'size' But if I include a mode in "gzip.GzipFile("testfile.txt", 'wb')" or something like that I don't get an error and then I manage to do >>>file.close() but still I can't find any compressed file? From gh at ghaering.de Tue Dec 2 09:50:24 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 02 Dec 2003 15:50:24 +0100 Subject: slightly OT: how do you do that? In-Reply-To: References: Message-ID: <3FCCA6B0.8020308@ghaering.de> dan wrote: > I recall reading somewhere that posts to c.l.p are crossposted to a > python mailing list. Does anyone have a pointer to the technical > information on how this is set up? I'm involved in a newsgroup > proposal and this issue has come up. python-list is managed by Mailman, so I suppose the Mailman docs will describe how to set up the mail-news gateway. -- Gerhard From bokr at oz.net Tue Dec 16 21:21:07 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Dec 2003 02:21:07 GMT Subject: I see advice on how to debug a python module that hangs up the process References: <5WLDb.12709$aw2.6791056@newssrv26.news.prodigy.com> Message-ID: On Tue, 16 Dec 2003 20:51:31 -0500, Jeff Schwab wrote: > > >Bengt Richter wrote: No I didn't. Please trim more carefully. > >>>Then, we have to do a "kill -9" the process. > >Did you try it without -9? > Regards, Bengt Richter From dw-google.com at botanicus.net Tue Dec 30 08:38:41 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 30 Dec 2003 05:38:41 -0800 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> <99dce321.0312282146.3c2c78ea@posting.google.com> Message-ID: <99dce321.0312300538.6d9493b6@posting.google.com> bokr at oz.net (Bengt Richter) wrote... > But that will accept '0x55' which I doubt the OP will like ;-) I should really learn to try my own code out on some inputs before posting. :) Another alternative for doing this test is a regular expression.. one of the few times I would actually use them: def is_hex(s): return re.match('^[a-fA-F0-9]{4}$', s) is not None Using a compiled regex would be faster, but since I can't currently figure out a way of storing such an 'implementation internal' object without using a global, callable instance, or default argument, I'm not going do it that way. :) David. From jsbenson at bensonsystems.com Wed Dec 24 15:24:37 2003 From: jsbenson at bensonsystems.com (John Benson) Date: Wed, 24 Dec 2003 12:24:37 -0800 Subject: Unicode from Web to MySQL Message-ID: <000201c3ca86$ca92e9c0$f60c7c43@jsbwxp3> Making my way through the list, I was very happy to see Francis Avila's discussion of Unicode. I was trying to work up enough courage to ask for something like this, and was very happy to see it appear spontaneously. My only quibble would be to characterize Unicode as a mapping from numbers to glyphs (instead of letters), since symbols from foreign alphabets sometimes look more like squashed bugs than letters. Some of us are old enough to have dealt at oscilloscope level with devices where a 7- or 8-bit number comes in from the wire and then hits the screen or the paper as a two-dimensional symbol, making the generalization of ASCII to Unicode easy to get. But I was completely in the dark about the status/visibility/nature of the internal Unicode representation and it's connection to the encode and decode operations. Thanks for the help. From gerrit at nl.linux.org Mon Dec 1 06:39:21 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 1 Dec 2003 12:39:21 +0100 Subject: How to delete this file ??? In-Reply-To: References: Message-ID: <20031201113921.GA2952@nl.linux.org> DCK wrote: > I've path to file, which look like this: > \\COMPUTER\D$\C++\FILE_TO_DELETE.JPG What do you mean exactly by: 'looks like'? Is it the full path to the file? How did you find out? > This path was generated by os.path.walk() function. When i try to delete > this file, os.remove() can't find it, os.path.fileexists() can't find it :( Does the directory exist, e.g., what does 'os.path.exists('\\computer\d$\c++') give as result? And 'os.path.exists('\\computer\d$')? I think a 'd$' is usually a share in Windows (not sure), maybe you haven't turned the share on (I'm not sure what 'mounting' is called in Windows)? > I can delete other files (i.e. \\COMPUTER\D$\C\FILE_TO_DELETE.JPG). I guess > there's a problem with this C++ directory (++ exacly). I tried to change it > to C\+\+, but this still not work. I've no idea how to delete this file. > > I work under WinNT 4.0 with sp6, python 2.3 with unicode support. I have > adminstrator rights. > Can somebody help me ? Maybe. Can you give some more precise information? What is your os.path.walk command? How does it reach this path? yours, Gerrit. -- 169. If he be guilty of a grave fault, which should rightfully deprive him of the filial relationship, the father shall forgive him the first time; but if he be guilty of a grave fault a second time the father may deprive his son of all filial relation. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jzgoda at gazeta.usun.pl Fri Dec 19 17:20:39 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 19 Dec 2003 22:20:39 +0000 (UTC) Subject: dynamic typing question References: Message-ID: Jason Tesser pisze: > I work for at a college where I am one of 2 full-time developers and > we are looking to program a new software package fro the campus. This > is a huge project as it will include everything from registration to > business office. We are considering useing Java or Python. I for one > don't like Java because I feel the GUI is clunky. I also think that > we could produce quality programs faster in Python. > > The other programmer here is very concerned about dynamic typing > though in Python. He feels like this would be too much of a > hinderance on us and too easy for us to make a mistake and not catch > it until runtime making debugging harder. > > OK what are your guys thoughts here? How have you all overcome the > lack of static typing? Is Python a bad decision here? By the way we > will be using Postgres in the back if that matters to anyone. If Python is good for banks[1], insurance companies[2], guys that do big booms[3] and other significant parties, why colleges are worry? [1]. This month I heard that some bank in Spain decided to use Pyro (Python Remote Objects). [2]. I work in one of them. [3]. Lawrence Livermoore National Laboratory. You know. These guys that made the Bikini Islands disappeared. Dynamic typing (with all other flexibility that Python offers) is a wonderful thing. I'm really sick when I must write anything in ObjectPascal. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ NP: Metallica - Helpless From gherron at islandtraining.com Thu Dec 4 04:17:25 2003 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 4 Dec 2003 01:17:25 -0800 Subject: How to I get the exception message as string in GUI In-Reply-To: <905257750.20031204100108@anonym.hu> References: <905257750.20031204100108@anonym.hu> Message-ID: <200312040117.26692.gherron@islandtraining.com> On Thursday 04 December 2003 01:01 am, fowlertrainer at anonym.hu wrote: > Hello , > > I want to get the exception error msg in string, but I don't want to > save to file, or print. > I want to show it in memo. > > How to I do it ? > > gd=GTMain.GameDatas > s=self.Msg > log="Log:\nStart loading" > s.SetLabel(log) > try: > gd.LoadGamesDatas() > log=log+"\nGame datas succesfully loaded." > except: > import traceback > traceback.print_exc() <--------- what I must write ? > log=log+"\An error occured while loading !" > s.SetLabel(log) > > Thanx. > > -- > Best regards, > fowlertrainer mailto:fowlertrainer at anonym.hu The manual is your friend. From the man page for traceback you can find a number of things you might want here including these four: format_list(list) Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. format_exception_only(type, value) Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. format_exception(type, value, tb[, limit]) Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). format_tb(tb[, limit]) A shorthand for format_list(extract_tb(tb, limit)). Gary Herron From jroznfgre at jngpugbjreQBGbet.cy Mon Dec 8 04:11:59 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 08 Dec 2003 10:11:59 +0100 Subject: Python on web with mod_python References: Message-ID: On Sun, 7 Dec 2003 17:47:55 -0600, "Jason Tesser" wrote: >I am thinking about developing a CMS with Python and Postgres. Look at Plone http://www.plone.org. It is ready to use, powerfull CMS system based on Zope http://www.zope.org >1. Is it best to just develop in all Pyhton or to use a mixture of PHP and Python? >Why other than personal feelings? There is no need for such mixture. Python should be enough. >2. What is the best way to template using Python for me to seperate content >from logic? All the data that will be displayed in dynamic so I am not sure >what the best way to template it would be in Python. I am also a PHP programmer and I had the same problem some times ago. I think, the best solution is an application serwer Webware http://webware.sourceforge.net and Cheetah http://www.cheetahtemplate.org as a template system. -- JZ From rdsteph at earthlink.net Thu Dec 25 11:34:17 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 25 Dec 2003 08:34:17 -0800 Subject: Python on Max osx and tkinter References: Message-ID: <8e6e8e5d.0312250834.29357710@posting.google.com> Ralf Wieseler wrote in message news:... > Hello! I'm quite new to Python. > > I wrote some little scripts using the "import from tkinter" Statemant > that work well on Windows and Linux. but if i try to execute them in my > Powerbook with Mac OSX 10.2.8 i get only Errors. I imorted the TKinter > Module with the Package Manager of MacPython 2.3 but it doesn't work. > My Macphython has no idea of TKinter. > Whats wrong? > > Thanks for any help! > > Greetz Ralf Hmm, I also had problems gettign Tkinter properly installed on early versions of Mac OS X. I finally did succeed, but it was difficult and I'm not sure I can tell you what the secret was ;-((( My best advice is to install the latest version of Mac OS X10.3 (Panther). I was successful installing Tkinter on Panther the first time with no difficulties. From andymac at bullseye.apana.org.au Mon Dec 29 21:42:06 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 30 Dec 2003 13:42:06 +1100 (EST) Subject: make test segfaults with "--enable-shared" on Python 2.3.3 In-Reply-To: References: Message-ID: <20031230111138.Y32845@bullseye.apana.org.au> On Mon, 29 Dec 2003, Berthold H?llmann wrote: > make distclean > env CFLAGS= CXXFLAGS= ./configure --with-thread --with-fpectl \ > --with-signal-module --with-pymalloc --enable-shared --with-cxx=g++ > env LANG=C CFLAGS= CXXFLAGS= make test > > gave: > > test_quopri > test_random > test_re > make: *** [test] Segmentation fault 1. Just to confirm that the configure generated Makefile is what it should be, what are the OPT and BASECFLAGS values? 2. Do a verbose run of the test_re test with the interpreter you built above (ie with the default optimisations): ./python Lib/test/regrtest.py -v test_re >test_re.log 2>&1 3. If it coredumps (which I expect it to based on your advice above), use gdb to get the backtrace. The test log and the gdb backtrace should help isolate where things are going astray. BTW, I'm not sure why you're explicitly using --with-thread, --with-signal-module and --with-pymalloc as they are all enabled by default. I'm also unsure as to whether you really need to specify --with-cxx; it might be worth a try configure'ing without it. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From paul_rudin at scientia.com Tue Dec 9 05:14:43 2003 From: paul_rudin at scientia.com (Paul Rudin) Date: 09 Dec 2003 10:14:43 +0000 Subject: python com wrappers Message-ID: I'm having a problem with the python wrappers generated from a type library. The symptom is that I get failures to find connections points inside the wrappers when called from DispatchWithEvents or WithEvents - e.g. "com_error: (-2147220992, 'CONNECT_E_NOCONNECTION', None, None)" It seems that the coclass_clsid property of some classes is incorrect. It seems that when a coclass in the type library has multiple "[source] dispinterface" it can happen that this coclass can end up as the one referenced by each of the corresponding DispatchBaseClass subclasses via the coclass_clsid property, whereas probably what should happen is that only ones that are default should be so treated. But maybe I'm misdiagnosing the problem; has anyone else seen this and/or know what the problem is? From harry.g.george at boeing.com Tue Dec 16 04:19:17 2003 From: harry.g.george at boeing.com (Harry George) Date: Tue, 16 Dec 2003 09:19:17 GMT Subject: Converting integer to binary representation References: <200312161526.25612.m.dufour@student.tudelft.nl> Message-ID: "Fredrik Lundh" writes: > "Mark Dufour" wrote: > > > I need to convert an integer into some binary representation. I found the > > following code in the online cookbook (adapted to return a list): > > > > binary = lambda n: n>0 and [n&1]+binary(n>>1) or [] > > > > This is sure nice, but I'm wondering why something like this doesn't seem to > > be in the standard library, for example by formatting with '%b' % number. I > > can't think of a any reason for not doing it this way, as working with binary > > representations is quite common in programming, > > really? what kind of programs are you writing? > > (in my experience, binary numbers only appear in programming text > books. humans tend to use decimal numbers, and programmers use > octal or hexadecimal numbers when they need to "access the bits"). > > > > > > In my experience, binaries are used in a) hardware, e.g., setting port values, and b) data format conversions (e.g., IEEE vs EBCDIC floats). In both cases, an occassional literal shows up in the program, but more importantly, it helps to see the binaries in debug statements. Yes, programmers use octal or hex to access bits, but only because that is what they have available. Modula-3 has a fine (though verbose) set of functions for the task which do not require mentally juggling octal and hex. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From peterm at resmed.com.au Wed Dec 10 15:13:23 2003 From: peterm at resmed.com.au (Peter Milliken) Date: Thu, 11 Dec 2003 07:13:23 +1100 Subject: Anyone use ELSE minor-mode in Emacs? References: Message-ID: I use it - but then I'm the author :-) I am hopeful that the "time to learn it" is very short. Probably the quickest way to get to learn it is to use the "tokens" i.e. enable the else-mode minor mode in a .py file and type in "def" and then run the else-expand-placeholder command (C-c / e - this key encoding is "forced" on Emacs minor mode authors by Emacs expansion conventions - I use F3 personally :-)). and you should get the appropriate code structure. Similarly, type in "classC-c / e" and you'll get a class structure. Then just "expand" every "placeholder" until you start to get a feel for where it leads. If you stick with just the "tokens" at first, then you'll quickly get an idea of what ELSE can do. Using "placeholders" follows fairly naturally from token expansions. If you don't want to handle the menus etc of using placeholders straight off the bat then that's no problem, just type directly into a placeholder and it will disappear and get out of your face :-) Once you have used it for a while and (hopefully :-)) find it useful, then perhaps venture into the users manual. I hope I have laid it out reasonably well, so you can focus in on the areas that interest you. Please do not stay with the minor mode key-bindings as the idea of ELSE is to reduce typing - having to type C-c / x all the time where "x" is "e, p, n, or k" defeats the entire purpose - but those are the "rules" for minor mode creators in Emacs :-) That is why the ELSE manual recommends that one of the first priorities is the creating of a convenient key-binding. I use: F3 - else-expand-placeholder F4 - else-next-placeholder F5 - else-previous-placeholder F6 - else-kill-placeholder I have a version of else-mode.el that has a command else-show-tokens - this is useful to quickly see what "tokens" are available for expansion using this mechanism. At the moment with the current released version of ELSE, you have to browse the individual language file to see what strings are defined as tokens. Token definitions are always at the end of the file, BTW :-) Let me know if you want a copy of that version - I am behind a firewall at work, so updating the web-site always has to wait for when I have the time to get on the Internet at home - something that can take weeks to do sometimes :-) As a general rule, any "keyword" is defined as a token i.e. return, if, def, try, while etc etc - try them to see what you get :-) It is very easy to define your own "tokens" (shortcuts for want of a better term), the manual describes all of this or you could just look at the language template files for examples. As for what it does for me - it saves me typing (use it properly and your main coding experience is the entry of variable names etc) and with more syntactically strict languages such as C etc it saves me having to type in {}'s and ;'s :-) If you use ELSE for a language like C then you never get a compiler error saying you have missed a } or a ; - surely a big time saving :-) The whole idea behind ELSE is to save typing - which means higher productivity and allows the programmer to focus on the problem at hand - writing a program to meet a need. The programmer shouldn't be distracted from the job at hand worrying about whether they got the language syntax correct or not :-) Hope this helps, Peter "Christian Seberino" wrote in message news:bf23f78f.0312091603.f91c1e7 at posting.google.com... > I am looking at the ELSE home page and trying to figure out if I should > invest the time to learn about the ELSE minor mode for Emacs. > > Is there any programmer out there using ELSE that is getting great > benefit from it? > > What does ELSE minor-mode for Emacs do that is so great for you? > > Chris From miki.tebeka at zoran.com Mon Dec 15 04:40:35 2003 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 15 Dec 2003 01:40:35 -0800 Subject: Using PIL with py2exe References: <6c7qtv0blppda689cpjbv9mi175sdpql2a@4ax.com> Message-ID: <4f0a9fdb.0312150140.7902cc2e@posting.google.com> Hello David, > >Does anyone know how to embed PIL into a py2exe program. > > > >As far as I can tell PIL is not finding its plugins for Image I/O, > >they are imported dynamically as required. So I cant load or save > >pictures > PIL imports the drivers dynamically, so py2exe doesn't find them. > Including these lines should solve your problem. > > ## Static imports from PIL for py2exe > from PIL import GifImagePlugin > from PIL import JpegImagePlugin I had the same problem, created a script call pil2exe which I import in my modules. --- pil2exe.py --- '''Fix allowing PIL to work under py2exe''' __author__ = "Miki Tebeka " # $Id: pil2exe.py,v 1.2 2003/10/20 11:35:38 mikit Exp $ #FIXME: # Hand pick only the modules you need (currently all *Plugin.py from PIL # directory are imported) #FIXME: Find who's the criminal and why, currently disable warnings import warnings warnings.filterwarnings("ignore") import ArgImagePlugin import BmpImagePlugin import CurImagePlugin import DcxImagePlugin import EpsImagePlugin import FliImagePlugin import FpxImagePlugin import GbrImagePlugin import GifImagePlugin import IcoImagePlugin import ImImagePlugin import ImtImagePlugin import IptcImagePlugin import JpegImagePlugin import McIdasImagePlugin import MicImagePlugin import MpegImagePlugin import MspImagePlugin import PalmImagePlugin import PcdImagePlugin import PcxImagePlugin import PdfImagePlugin import PixarImagePlugin import PngImagePlugin import PpmImagePlugin import PsdImagePlugin import SgiImagePlugin import SunImagePlugin import TgaImagePlugin import TiffImagePlugin import WmfImagePlugin import XVThumbImagePlugin import XbmImagePlugin import XpmImagePlugin --- pil2exe.py --- Use at your own risk :-) HTH. Miki From gerrit at nl.linux.org Tue Dec 16 13:38:52 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 16 Dec 2003 19:38:52 +0100 Subject: Zen of ... Message-ID: <20031216183852.GA4318@nl.linux.org> Hi, shouldn't the Zen of Python really be called the Zen of Programming? (asks someone who knows Python and only Python) The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! yours, Gerrit. -- 242. If any one hire oxen for a year, he shall pay four gur of corn for plow-oxen. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From 9974331 at cvm.qc.ca Wed Dec 31 08:30:11 2003 From: 9974331 at cvm.qc.ca (Askari) Date: Wed, 31 Dec 2003 13:30:11 GMT Subject: Try except - bug? References: <104c369a.0312300851.4f23759e@posting.google.com> <1ne3vvobhp2u6mqar4khk84h64hcmu8h1o@4ax.com> <104c369a.0312301901.3e4f8207@posting.google.com> Message-ID: Rene Pijlman wrote in news:gg95vvs4ni6poiht2siml0htcg9qo73j91 at 4ax.com: > Askari: >>OSError: [Errno 2] No such file or directory: '' > > If I'm not mistaken this is another exception!? > >>at line 355 you have : "fileDest.close()" > > No, line 355 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: > > > #afficher confirmation > >>and at line 363 you have : "os.remove(destination)" > > No, line 363 of http://www.cvm.qc.ca/9974331/Temp/crypte.py is: > > pass > >>What is your version of python? (I have 2.3.2) > > I use UltraEdit 8.0 on Windows XP to count the line numbers. > euh.... I use UltraEdit 10.10 and "#afficher confirmation" is at line 349 (it's the same numero in IDLE). Are you sure that your UltraEdit is correct? Check the line in IDLE, it's the same? From bokr at oz.net Fri Dec 5 13:20:20 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Dec 2003 18:20:20 GMT Subject: How to tell the difference between string and list References: <877k1bmc2g.fsf@pobox.com> Message-ID: On 05 Dec 2003 17:03:35 +0000, jjl at pobox.com (John J. Lee) wrote: >Jan Kokoska writes: > >> I need to recognize 'var' and ['var'], usually I would use: >[...] > >All the other solutions posted are bad because they fail for >user-defined string-like classes (unless those classes use the new 2.2 >features by deriving from str or unicode). As long as your strings >aren't huge: > >def isstringlike(x): > try: x+"" > except TypeError: return False > else: return True > > >I think I stole this off Alex Martelli. > There are some caveats in using that re side effects and unanticipated semantics, e.g., a contrived example of both: >>> class Slist(list): ... def __add__(s, o): ... if isinstance(o, str): print '<>'; return list.__add__(s,[o]) ... return list.__add__(s,o) ... >>> sl = Slist(['abc','def']) >>> sl ['abc', 'def'] >>> sl + 'ghi' <> ['abc', 'def', 'ghi'] >>> def isstringlike(x): ... try: x+"" ... except TypeError: return False ... else: return True ... >>> sl ['abc', 'def'] >>> isstringlike(sl) <> True Is it? IMO, no. Accepting addition of strings does not a string make. You can't assume anything about the result or the object except that string addition is defined. The side effect here is contrived, but adding a string to a list could be handy if you have a list-like object that deals with strings and might not want the behavior of an ordinary list, which is: >>> s2 = ['abc','def'] >>> s2 + 'ghi' Traceback (most recent call last): File "", line 1, in ? TypeError: can only concatenate list (not "str") to list >>> s2 += 'ghi' >>> s2 ['abc', 'def', 'g', 'h', 'i'] Regards, Bengt Richter From fumanchu at amor.org Thu Dec 4 11:29:02 2003 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 4 Dec 2003 08:29:02 -0800 Subject: Simple newbie question Message-ID: Or, simply iterate through the list backwards. FuManChu > -----Original Message----- > From: Duncan Booth [mailto:duncan at NOSPAMrcp.co.uk] > Sent: Thursday, December 04, 2003 7:51 AM > To: python-list at python.org > Subject: Re: Simple newbie question > > > Angelo Secchi wrote in > news:mailman.107.1070547952.16879.python-list at python.org: > > > The code i'm using is the following: > > > > for line in lista: > > if sum(line == 0) > 0: > > lista.remove(line) > > > > > > The problem is that the loop stops at the first line with > zeros and it > > doesn't remove the other lines with zeros (at least if I do > not re-run > > the loop). Probably I do not understand how the loop works. > > The loop will assign the first element of lista to line, then > the second, > then the third, and so on. > > The problem is that, if you remove an element everything > after it shifts up > one place. Say you are looking at the first element and > remove it, what was > the second element now becomes the first element, but the > next time round > the loop you will look at the new second element and the one that was > originally second (and is now first) will be skipped. > > The solution is never to work on the list you are modifying. > Just make a > copy of the list and iterate over the copy, that means you can safely > modify the original. To copy a list, use the 'list' builtin. > > for line in list(lista): > if condition: > lista.remove(line) > > Alternatively turn your brain around and instead of deleting specific > elements from the list just build a new list with the > elements you want to > keep. In this case you could do that using a list comprehension: > > lista = [ line for line in lista if not condition ] > > (Obviously in both these cases replace condition with the correct > expression, which as Gerhard pointed out may not be the > condition in your > original posting.) > > The list comprehension rebinds the lista variable, whereas > your original > attempt was modifying the list inplace. This might be > significant if there > are other references to the same list elsewhere in your code. > If it does > matter, then you can still use a list comprehension to mutate > the original > list: > > lista[:] = [ line for line in lista if not condition ] > > Unlike the original 'for' loop, this works by building a complete > replacement list then mutating the original list in one go. > > -- > Duncan Booth > duncan at rcp.co.uk > int month(char > *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" > "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at ferg.org Fri Dec 19 14:37:26 2003 From: steve at ferg.org (Stephen Ferg) Date: 19 Dec 2003 11:37:26 -0800 Subject: The Truth? References: Message-ID: I tried to send you a file, but... ----- The following addresses had permanent fatal errors ----- (reason: 550 5.1.1 unknown or illegal alias: TyBriD at si.rr.com) From hat at se-126.se.wtb.tue.nl Thu Dec 18 09:46:20 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Thu, 18 Dec 2003 14:46:20 +0000 (UTC) Subject: Using python with SSH? References: <3fe0dfd7$1@clarion.carno.net.au> Message-ID: On Thu, 18 Dec 2003 10:06:02 +0000, Martin Franklin wrote: > On Wed, 2003-12-17 at 23:00, Steve wrote: >> Hi, >> >> I need to run a remote program from a server that I have access rights >> to. I want to be able to do this from within in my python script and I >> want to use ssh (or anything else that will work). However, doing >> something like: >> >> ssh -l user host "/path/to/program" >> >> prompts for a password and I don't know how to supply one via a python >> script. Is there an easy way out? Can I log onto to the other machine If your sysadmin allows it, you can configure ssh to connect to another machine without prompting for a password, at least at Linux systems. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From garabik-news-2002-02 at kassiopeia.juls.savba.sk Wed Dec 17 03:08:34 2003 From: garabik-news-2002-02 at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 17 Dec 2003 08:08:34 GMT Subject: A GUI toolkit for Python that is NOT x-windows dependent References: <88f9e356.0312162305.58718893@posting.google.com> Message-ID: Andre Brightway wrote: > I need a script to draw a keyboard to the screen and animate the > marking each key when the key is pressed (among other things like > being able to draw menus). This script is for testing keyboards and > needs to be run by people who may never have touched a computer before > so it needs to have an easy to follow GUI interface. But the Linux > boxes these will be runned on are very low-end, 'diskless' terminals > where running a full X-Windows system would be very slow. Does anybody > know of a GUI toolkit (or a way to draw to the screen) that can be > used from Python script in Linux without having to run X-Windows? pygame, of course it runs nicely on framebuffer, and seems to be ideal for the task you describe -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From timr at probo.com Wed Dec 3 01:27:06 2003 From: timr at probo.com (Tim Roberts) Date: Tue, 02 Dec 2003 22:27:06 -0800 Subject: Binary number manipulation References: Message-ID: <350rsvkbsht8rgs1fsjjc7vkktf87sahi7@4ax.com> SBrunning at trisystems.co.uk wrote: > >> 2. If 1 is no, does that mean that I need to do all the manipulation in >> some icky string format and then go back? > >I use: > >((high << 16) | low) ...which, unfortunately, gives a FutureWarning in Python 2.3 if high happens to be larger than 32767. I think we're all going to be using a lot more of the struct module in the future. For example, this is the equivalent of what you posted: struct.unpack('>L',struct.pack('>2H',high,low))[0] I may have to start using things like: def MAKELONG(high,low): return struct.unpack('>L',struct.pack('>2H',high,low))[0] Is there a smarter way to do this kind of thing? This also works: ((high << 16L) | low) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dck at nospam.gazeta.pl Mon Dec 1 16:23:23 2003 From: dck at nospam.gazeta.pl (DCK) Date: Mon, 1 Dec 2003 22:23:23 +0100 Subject: How to delete this file ??? References: Message-ID: Hello again Really sorry for long time between me letters. All problem gone, after i've used raw string (r"\\path\to\any\file") Really thanks for all answers :) Thank's again ! From fredrik at pythonware.com Mon Dec 8 12:55:51 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 Dec 2003 18:55:51 +0100 Subject: diferences between 22 and python 23 References: <001001c3b9c1$053a4f40$7a010a0a@epalomo><3FCE44AE.C415D6FA@engcorp.com> <3FCE48CD.8010908@rogers.com> Message-ID: Martin v. L?wis wrote: > > having written Python's Unicode string type, I'm now thinking that > > it might have been better to use a polymorphic "text" type with > > either UTF-8 or encoded char or wchar buffers, and do dynamic > > translation based on usage patterns. I've been playing with this > > idea in Pytte, but as usual, there's so much code, and so little > > time... > > "Better" in what sense? less code, better performance. the usual stuff. > Would it even be better if you had to preserve all the C-level API > that we currently have? I don't think it can be done without changing the API. maybe in Python 3000? From http Sun Dec 7 17:53:50 2003 From: http (Paul Rubin) Date: 07 Dec 2003 14:53:50 -0800 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: <7xsmjwz1c1.fsf@ruckus.brouhaha.com> Douglas Alan writes: > > This doesn't make sense to me as an explanation. Smalltalk didn't reach > > much of a mass audience until Goldberg's book was published in 1983, and > > other object-oriented languages (e.g. C++) did not immediately adopt > > CamelCase (I see none in Stroustroup's 1986 C++ book). In the meantime, > > CamelCase (with or without the initial capital) was certainly used prior > > to 1983 in languages such as Pascal. > > Someone else in this thread claimed that CamelCase came to Pascal via > Apple. And we know that Apple was lapping at the time from the font > of Xerox Parc. This would explain how CamelCase made it from > Smalltalk to Pascal. Yes, that sounds plausible to me. While Smalltalk may not have had a mass audience pre-1983, hacker culture at the time centered around academia and places like PARC, which didn't need mass audiences. The MixedCase thing seemed cult-like even at the time, which fits in with Apple taking it up. From try_vanevery_at_mycompanyname at yahoo.com Fri Dec 26 17:59:34 2003 From: try_vanevery_at_mycompanyname at yahoo.com (Brandon J. Van Every) Date: Fri, 26 Dec 2003 14:59:34 -0800 Subject: Project dream References: Message-ID: "Will Stuyvesant" wrote in message news:cb035744.0312261236.11d785ac at posting.google.com... > Suppose you have the time and the money to start a new project in > Python. What would you like to do? > > I can think of: > > - A civilization like game in Python, with multiplayer support via > twisted. Will, are you aware that I'm beginning exactly this project? Well, not the twisted bit, I don't even know what that is or why one would want it. Please see my post "ProtoCiv: porting Freeciv to Python." I'd be interested in your feedback even if my project goals don't match yours. > - A roguelike in Python. Since there is still no portable curses, it > needs WConio or something like that, and also multiplayer would be > great. There's Umbra. http://kuoi.asui.uidaho.edu/~kamikaze/Umbra/ Graphics and gameplay aren't great, but it is something to start with. If you go to http://www.thangorodrim.net/ and search with the keyword "Python," you will find some roguelikes that claim to have various amounts of Python support in them. I haven't chased any of these down myself though. At some point I gave up on the "do a RPG" project excuse, opting instead for 4X TBS because it's more directly applicable to my Ocean Mars project. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA 20% of the world is real. 80% is gobbledygook we make up inside our own heads. From __peter__ at web.de Sun Dec 21 04:23:29 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Dec 2003 10:23:29 +0100 Subject: UserLinux chooses Python as "interpretive language" of choice References: <99dce321.0312200919.3dd4af66@posting.google.com> Message-ID: Jarek Zgoda wrote: > Anyway, isn't that function always returns value, even without explicit > "return" statement? >>> import dis >>> def f(): ... return 123 ... >>> dis.dis(f) 2 0 LOAD_CONST 1 (123) 3 RETURN_VALUE 4 LOAD_CONST 0 (None) 7 RETURN_VALUE >>> def g(): ... raise Exception ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (Exception) 3 RAISE_VARARGS 1 6 LOAD_CONST 0 (None) 9 RETURN_VALUE >>> def h(): pass ... >>> dis.dis(h) 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE >>> So Python always appends a return None statement at the end of a function. Of course that doesn't mean that it will be executed. Peter From spiffy at worldnet.att.net Tue Dec 9 17:53:08 2003 From: spiffy at worldnet.att.net (Spiffy) Date: Tue, 09 Dec 2003 22:53:08 GMT Subject: running non-python progs from python References: <_RfBb.420211$0v4.20322033@bgtnsc04-news.ops.worldnet.att.net> Message-ID: Fredrik Lundh" wrote in message news:mailman.261.1070970251.16879.python-list at python.org... > "Spiffy" wrote: > > > > How can I run this other program from a python script and pass the > > filename > > > as a parameter? > > > > import os > > > > filename = "myfile" > > os.system("program %s" % filename) > > > > > > > > Fredrik, the example you provided is virtually the same as the one from the > > "Learning Python" book. > > that indicates that it's supposed to work, don't you think? IT COULD HAVE BEEN A MISPRINT, DON'T YOU THINK? > > When I run it, the dos command line appears with the message 'Bad command > > or file name". > > that indicates that Windows cannot find the command, don't you think? > > > Both the .exe and the .mid file are in the python path and the spelling has > > been checked. > > you mean sys.path? IF I HAD MEANT sys.path, I WOULD HAVE SAID sys.path, DON'T YOU THINK? that's the problem, most likely. As mentioned in the > documentation, os.system() executes the command just as if you've typed > it in a "DOS box". Windows doesn't look at the Python path when you do > that, so to make sure Windows finds the command, you have to add it to > the Windows path (the PATH environment variable), or provide the full path > to os.system(). > > program = r"x:\full\path\to\program" > filename = "..." > os.system("%s %s" % (program, filename)) > > the os.path.abspath() function can be useful in cases like this; it makes sure > that if your program can find a file, another program can also find it: > > program = os.path.abspath("x:/somewhere/program") > filename = os.path.abspath("somefile") > os.system("%s %s" % (program, filename)) > > (if the filename may contain spaces, you may have to add quotes around > the second %s) TYPING THE FULL PATH GIVES ME THE SAME RESULT: NOTHING. THE ABOVE CODE USING os.path.abspath CAUSES A DOS BOX TO APPEAR AND DO NOTHING WHILE PYTHON CRASHES. > the relevant manual page contains more information on os.system, and > mentions a couple of alternatives (os.startfile, os.spawnlp, etc): > > ?http://www.python.org/doc/current/lib/os-process.html > > > Pardon me for being a newbie, but if you don't have an answer, why do you > > have to give me attitude? > > os.system() is still the answer; the problem is in how you used it and what > you expected from it, not in the function itself. You cannot expect people > to read your mind, and then complain when they fail. I DID NOT ASK ANYONE TO READ MY MIND, NOR DID I COMPLAIN THAT ANYONE COULD NOT READ MY MIND. I DO NOT THINK THE PROBLEM IS IN HOW I USED THE FUNCTION NOR WHAT I EXPECTED FROM IT. > From mensanator at aol.compost Mon Dec 8 23:57:18 2003 From: mensanator at aol.compost (Mensanator) Date: 09 Dec 2003 04:57:18 GMT Subject: Base conversion method or module References: <0b88tvo38l9ca8fhc3127mskqegdpfocn7@4ax.com> Message-ID: <20031208235718.01860.00000479@mb-m18.aol.com> >Subject: Re: Base conversion method or module >From: Jeff Wagner JWagner at hotmail.com >Date: 12/8/2003 1:01 AM Central Standard Time >Message-id: <0b88tvo38l9ca8fhc3127mskqegdpfocn7 at 4ax.com> > >On 08 Dec 2003 04:45:17 GMT, mensanator at aol.compost (Mensanator) wrotf: > >>>Subject: Re: Base conversion method or module >>>From: "Francis Avila" francisgavila at yahoo.com >>>Date: 12/7/2003 8:52 PM Central Standard Time >>>Message-id: >>> >>> >>>Jeff Wagner wrote in message ... >>>>On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" > >>>wrotf: >>>> >>>>>Jeff Wagner wrote: >>>>> >>>>>> I found the Python cookbook recipe you were referring to. It is as >>>follows: >>>>> >>>>>(what's wrong with just posting an URL?) >>>> >>>>What a great idea ;) ... >>>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 >>> >>>Hey, I found another one which is the more general "inverse of int/long" >>>function I was pining for (and thus learning for the n-th time that one >>>should check the cookbook first before reinventing the wheel): >>> >>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/222109 >> >>These are nice, but they're very slow: >> >>For i=2**177149 - 1 >> >>224.797000051 sec for baseconvert >>202.733999968 sec for dec2bin (my routine) >>137.735000014 sec for radix >> >>Compare those to the .digits function that is part of GMPY >> >>0.59399998188 sec >> >>That can make quite a difference when you're running through a couple >million >>iterations. > >So I decide to go and try out this GMPY and download the win32 binaries. It >consists of two files, >gmpy.pyd and pysymbolicext.pyd ... what do I do with them, just copy them to >the lib folder? Yes. Did you get the documentation files also? You'll want gmpydoc.txt as it lists all the functions. Unfortunately, it's a Unix test file (no carraige returns) making it useless for Windows Notepad unless you convert the line feeds to carraige return/line feed. > >Then it says I need GMP-4.x so I get that, too. It's like nothing I've ever >seen before. How can I >install that on my WinXP box? You only need that if you are going to compile from the source files. The Windows binaries are already compiled, so you shouldn't need to do that step. > >Thanks, Jeff -- Mensanator Ace of Clubs From howard at eegsoftware.com Thu Dec 4 00:58:13 2003 From: howard at eegsoftware.com (Howard Lightstone) Date: Thu, 04 Dec 2003 05:58:13 GMT Subject: customize Tkinter window button~ References: Message-ID: black wrote in news:mailman.89.1070511965.16879.python-list at python.org: > i am with Win2k and had built a window with Tkinter, it has 3 button > on its topright corner as common window, but what i want is just one > or tow of them. ie, is there any way i can configure the appearance > of minimize, maximize and close button ? Basically, no. Those buttons are a function of the Windows standard window creation logic. It is possible to add to or change those buttons (using ctypes) - but you are looking at some pretty hairy and poorly documented routines (such as the required callbacks for each button). What you CAN do is use the overrideredirect method to turn off the entire top bar and instead put one of your own (Tkinter) buttons there. Just don't forget to handle the (closing, moving the window, etc.,) events for the window. From eppstein at ics.uci.edu Sun Dec 7 17:16:12 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 07 Dec 2003 14:16:12 -0800 Subject: Case sensitive and ludicrous statements References: <20031110065915.07735.00000461@mb-m07.aol.com> <2259b0e2.0311112319.8eba857@posting.google.com> <2259b0e2.0311120620.2ce4384b@posting.google.com> <3FD0A3B2.4DD3B518@engcorp.com> <7xk758iaso.fsf@ruckus.brouhaha.com> Message-ID: In article <7xk758iaso.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > > You will notice that CamelCase was extremely uncommon (if used at all) > > before the advent of case-sensitive languages, and there is good > > reason for this. It didn't make sense then, and it doesn't make sense > > now! (In a case-insensitive language.) > > The convention always annoyed me, but I think it was customary in the > old days of Smalltalk. When object-oriented programming became a fad > in the 80's, it spread into other languages from there. This doesn't make sense to me as an explanation. Smalltalk didn't reach much of a mass audience until Goldberg's book was published in 1983, and other object-oriented languages (e.g. C++) did not immediately adopt CamelCase (I see none in Stroustroup's 1986 C++ book). In the meantime, CamelCase (with or without the initial capital) was certainly used prior to 1983 in languages such as Pascal. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mwh at python.net Wed Dec 24 05:59:32 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 24 Dec 2003 10:59:32 GMT Subject: OT: Why -g when compiling References: <4f0a9fdb.0312230733.736d124d@posting.google.com> <4f0a9fdb.0312231526.394a518e@posting.google.com> Message-ID: miki.tebeka at zoran.com (Miki Tebeka) writes: > Hello Michael, > > > > Can anyone tell me why when builiding Python gcc gets "-g" option as well as "-O3"? > > > Apart from bigger objects what does "-g" gives a non-developer of Python? > > > > It means if you manage to core python, we can hold your hands to find > > out with gdb where it's crashed. Why do you ask? > Just out of curiosity. Seen it in many apps when building and always > wondered. > > > Disk space is cheap. > Yes but memory sometimes isn't. True. I don't know if the various linkers around are smart enough to not load debugging information until it's asked for... > On my cygwin installation the libpython2.3.dll goes from 2.9MB to > 1.1MB. On machines with little RAM (embdded ...) this matters a lot. Oh sure, but if you're in an embedded situation, I would *hope* that you don't just blindly use the default compile options! Cheers, mwh -- My first thought was someone should offer Mr. Bush elocution lessons. But he'd probably say he knew how to work them chairs already. -- Internet Oracularity #1294-01 From bwglitch at hotpop.com Sat Dec 13 23:16:46 2003 From: bwglitch at hotpop.com (BW Glitch) Date: Sat, 13 Dec 2003 23:16:46 -0500 Subject: Strip HTML tags? In-Reply-To: <7b454334.0312131911.70647953@posting.google.com> References: <7b454334.0312131911.70647953@posting.google.com> Message-ID: Fazer wrote: > Hello, > > I was wondering what would be the easiest way to strip away HTML tags from a string? > > Or how would I remove everything between < and > also the < , > as well using regex? You could use the SGMLparser for that also. Check the Python Cookbook at ASPN ( http://aspn.activestate.com/ASPN/Python/Cookbook/ ) for a recipe that uses it ( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52281 ). -- Glitch -----BEGIN TF FAN CODE BLOCK----- G+++ G1 G2+ BW++++ MW++ BM+ Rid+ Arm-- FR+ FW- #3 D+ ADA N++ W OQP MUSH- BC- CN++ OM P75 -----END TF FAN CODE BLOCK----- "Waspinator negative negative negative! I am Shrapnel, Decepticon hero-o-o-o!" "Shrapnel? That was a Decepticon from the Great War three centuries ago! ..." -- A loopy Waspinator and Blackarachnia, "Dark Designs" From jepler at unpythonic.net Sun Dec 7 22:35:27 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 7 Dec 2003 21:35:27 -0600 Subject: how to determine if files are on same or different file systems In-Reply-To: References: Message-ID: <20031208033527.GE7517@unpythonic.net> You can find the device a file is on using the .st_dev field of its stat information: >>> os.stat("/").st_dev see the stat manpage for more details. You can find the magic number for a particular filesystem using statfs(2), but as far as I can tell this is not exposed in Python. If it were, you'd write something like >>> os.statfs("/").f_type to get the type of the filesystem where / resides. Some f_type values are mentioned in my statfs(2) manpage, including NFS_SUPER_MAGIC 0x6969 os.statvfs() seems to be unrelated, though my system lacks a manpage for it. Jeff From Andreas.Ames at tenovis.com Mon Dec 1 15:33:47 2003 From: Andreas.Ames at tenovis.com (Ames Andreas (MPA/DF)) Date: Mon, 1 Dec 2003 21:33:47 +0100 Subject: notes on compilation Python with MinGW gcc Message-ID: <788E231C269961418F38D3E360D1652526C9E5@tndefr-ws00021.tenovis.corp.lan> Hi Oleg, usenet at xmlhack.ru (Oleg A. Paraschenko) writes: > recently I compiled Python with MinGW gcc under Windows. > If there are some interest, you can look at log of process at > > http://uucode.com/texts/python-mingw/python-mingw.html > > In short, about compiling with MinGW gcc: > > * it is possible; > * result works; > * you must not do it unless you know for sure that you must do it; > * you must have a good knowledge of C and of debugging; > * in most cases all you need is to compile an extension module. I've recently taken a slitely different way to accomplish a native mingw32 build. You can get a patch from https://sourceforge.net/tracker/?func=detail&aid=841454&group_id=5470&at id=305470 As I haven't used msys yet and my real goal was to build a mingw32-python on linux (without the adventures of installing VC6 under wine, which reportedly works either). Thus it had to be a crosscompile, but you should be able to use cygwin (but you must edit xbuild-py.sh to do so and you must --build and --host on cygwin too, I've started the crossbuild on cygwin). The build still has quite a few 'rough edges' ;-): 1) The resource files (*.rc) are not yet compiled/linked in. Given that they are rather simple I wouldn't expect significant difficulties using windres. There would need to happen some changes to Makefile.pre.in though. 2) pythonw.exe is not yet built. Similar changes as above needed. 3) I couldn't yet convince scons that it would be a good idea to have a build directory seperate from the source tree. I have tried both the BuildDir function and the build_dir parameter to the SConscrript function but to no avail. It could either be a bug in scons or my own inability. As this was my first scons-script, I guess it's the latter. Some scons knowledgeable person might be able to fix this within seconds. Before you get a useful environment you must copy the Lib/ subdirectory from source- to the buildtree as well as all the *.pyd files from /Modules and /PC to /DLLs or something. Note that running the testcases from a samba-share isn't good because the tests use filenames with an '@' sign which samba doesn't seem to like. You might be better off copying the complete buildtree to a native windows partition (if you build from linux anyway). The patch applies to 2.3.2 because I have no easy way to access the cvs repository. If there was interest in a native mingw32-python I would like to help to solve the above issues (and others I haven't found yet). But it doesn't appear that there is much interest in this, so I'd guess you can take the above as a toy project. cheers, andreas From __peter__ at web.de Mon Dec 15 14:59:40 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Dec 2003 20:59:40 +0100 Subject: Dynamically create classes for spark-parser-framework References: Message-ID: Diez B. Roggisch wrote: > I've got to create some spark-based parsers during runtime. For people not > familiar with spark, a parser looks like this: > > class MixFixParser(spark.GenericParser): > def __init__(self, start='p_start'): > spark.GenericParser.__init__(self, start) > > def p_rules(_, args): > """ > p_start ::= p_op p_start > p_start ::= > p_op ::= p_start lbracket p_start rbracket > """ > return args > > The framework looks for methods beginning with p_ and inspects its > docstring for grammar rules. > > I hope that the body of my p_rules will be uniform, so until now I'd like > to have one paser baseclass like MixFixParser above, and then modify the > docstring accordingly - only for one specified instance! > > My first attempts failed due to > > AttributeError: 'instancemethod' object attribute '__doc__' is read-only If a writable __doc__ really is sufficient (which I doubt, while I know nothing about spark): >>> class T: ... def demo(self, x): ... print "demo(%r)" % x ... >>> class Method: ... def __init__(self, func): ... self.func = func ... def __call__(self, *args): ... self.func(*args) ... >>> t = T() >>> t.demo = Method(t.demo) >>> t.demo.__doc__ = "so what" >>> t.demo.__doc__ 'so what' >>> t.demo("abc") demo('abc') >>> t.demo.__doc__ = "something else" >>> t.demo.__doc__ 'something else' Maybe you can expand on this, e. g. doing self.method = Method(self.method) for every method starting with "p_" in the constructor. Peter From bhan at andrew.cmu.edu Sat Dec 27 19:12:06 2003 From: bhan at andrew.cmu.edu (Benjamin Han) Date: Sat, 27 Dec 2003 19:12:06 -0500 (EST) Subject: Simple way to get the full path of a running script? In-Reply-To: References: Message-ID: Should be: pathToScript=\ os.path.normpath(os.path.join(os.getcwd(),os.path.split(sys.argv[0])[0])) On Sat, 27 Dec 2003, Benjamin Han wrote: > Duh - the way I described seems to be simple enough: > > pathToScript=os.join(os.getcwd(),os.path.split(sys.argv[0])[0]) > > > On Sat, 27 Dec 2003, Benjamin Han wrote: > > > I know I can do this by get sys.argv[0], tell if it's a full path, and if not, > > somehow join the relative path with getcwd(). Just wondering if there's a > > simpler way to do this. Thanks! > > > From harry.g.george at boeing.com Wed Dec 17 05:16:35 2003 From: harry.g.george at boeing.com (Harry George) Date: Wed, 17 Dec 2003 10:16:35 GMT Subject: Standalone client database for Python? References: Message-ID: Gustavo Campanelli writes: > What are our options for a standalone (that is one that's not > client/server) easily accesible from Python? > I'm not going to ask for special features as this is only to see what > is avaiable and used (most used most probably meaning well maintained > project). > > Thanks in advance > > Gedece For embedded dbms's, you can get bindings for gdbm, dbm, sqlite. Maybe you could use a client server after all. E.g., you could set up postgresql so that only a particular user on the local box can access the database. In terms of access authorization this is equiv of an embedded dbms. For "most maintained", mysql and postgresql would be hard to beat in client/server space. For embedded dbms's, I'd guess Berkeley DB would be the winner (http://www.sleepycat.com/) -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From jurgenex at hotmail.com Sun Dec 21 10:32:58 2003 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 21 Dec 2003 15:32:58 GMT Subject: replacing two EOL chars by one References: <7fe97cc4.0312201204.7accda32@posting.google.com> <7fe97cc4.0312210106.5a72c199@posting.google.com> Message-ID: Xah Lee wrote: [...] > -- [246 lines of signature snipped] That even beats any spammer I know of. If your foul language wasn't reason enough yet, this really does it: *PLONK* jue From jjl at pobox.com Sat Dec 13 20:03:53 2003 From: jjl at pobox.com (John J. Lee) Date: 14 Dec 2003 01:03:53 +0000 Subject: ANN: lunatic-python 0.1 References: <7xd6atgnwx.fsf@ruckus.brouhaha.com> Message-ID: <87d6asjjly.fsf@pobox.com> mlh at furu.idi.ntnu.no (Magnus Lie Hetland) writes: > In article <7xd6atgnwx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >Gustavo Niemeyer writes: > > > [snip] > >But you left out the most important question: WHY? > > Not the reason cited on the page, but: Python is great for writing > apps (that is, for _me_), and Lua is great for simple (even easier > than Python) scripting of apps (that is, for the _user_). So that's > one possible use... Just wanted to say "me too", in defence of Gustavo (even though his justification on the lunatic-python web page is quite sufficient!). John From buzzard at urubu.freeserve.co.uk Thu Dec 11 20:41:38 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 12 Dec 2003 01:41:38 -0000 Subject: Kinda newb-ish question References: <5c27220b.0312111650.7f0a128d@posting.google.com> Message-ID: "ChocoboMog123" wrote in message news:5c27220b.0312111650.7f0a128d at posting.google.com... > What's wrong with line 8 in this code? > x=1 > while 1==1: > x=x+1 > y=range(1,x) > z=0 > q=9 > for count in y: > q=x%y > if q==0: > z=z+1 > if z<1: > print x > It keeps giving me > Traceback (most recent call last): > File "C:\Python23\Prime Number.py", line 8, in -toplevel- > q=x%y > TypeError: unsupported operand type(s) for %: 'int' and 'list' > The clue is in the traceback. 'y' is a list. Presumably you meant q = x % count. Duncan From deets_noospaam at web.de Wed Dec 3 15:53:00 2003 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Wed, 03 Dec 2003 21:53:00 +0100 Subject: Turning f(callback) into a generator References: Message-ID: > def path_gen(start): > res = [] > def cb(r, dir, names): > for n in names: > r.append(n) > > os.path.walk(start, cb, res) > for n in res: > yield n > > > g = path_gen("/etc") > > for n in g: > print n Just found out that lists support extend, which allows the ugly loop for appending names in cb to be written this way: r.extend(names) Diez From arjen.dijkstra%no%-%spam% at hccnet.nl Sun Dec 21 15:45:03 2003 From: arjen.dijkstra%no%-%spam% at hccnet.nl (duikboot) Date: Sun, 21 Dec 2003 21:45:03 +0100 Subject: linux wine py2exe ?? References: Message-ID: Hi A friend of mine runs windows, and asked me to write a little script. He has no Python installed though, and istalling it, is no option. So I really wanted to make an executable for windows. So I Installed wine: [arjen at localhost]$ rpm -qa | grep wine wine-devel-20031212-1fc1winehq wine-20031212-1fc1winehq Then I created the scripts he needed, and tried to make it an executable. I'll throw all the code in and the errors I hope you can help me. Thanks anyway for your trouble Greetings, Arjen ####code script###### from glob import glob from string import strip lijst=glob("*.txt") for bestand in lijst: o=open(bestand).read()[1:] b=open(bestand,'w') b.write(o) b.close() ###setup.py### from distutils.core import setup import py2exe setup(name="vervang", scripts=["vervang.py"], ) [arjen at localhost Python23]$ wine python.exe setup.py py2exe fixme:console:SetConsoleCtrlHandler (0x7800f03e,1) - no error checking or testing yet running py2exe running build running build_scripts running install_scripts fixme:imagehlp:BindImageEx (7, "C:\\Python23\\DLLs\\_sre.pyd", "C:\\Python23\\DLLs;C:\\Python23;C:\\WINDOWS\\SYSTEM;C:\\WINDOWS;c:\\windows;c:\\windows\\"..., (null), 0x10001570): stub Traceback (most recent call last): File "setup.py", line 6, in ? scripts=["vervang.py"], File "C:\Python23\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Python23\lib\distutils\dist.py", line 907, in run_commands self.run_command(cmd) File "C:\Python23\lib\distutils\dist.py", line 927, in run_command cmd_obj.run() File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 698, in run extra_path + sys.path) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 842, in find_dependend_dlls alldlls, warnings = bin_depends(loadpath, images) File "C:\PYTHON23\Lib\site-packages\py2exe\build_exe.py", line 1154, in bin_depends for result in py2exe_util.depends(image, loadpath).items(): py2exe_util.bind_error: C:\Python23\DLLs\_sre.pyd From dw-google.com at botanicus.net Wed Dec 31 14:30:18 2003 From: dw-google.com at botanicus.net (David M. Wilson) Date: 31 Dec 2003 11:30:18 -0800 Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> Message-ID: <99dce321.0312311130.5b7c7c8a@posting.google.com> "Aubrey Hutchison" wrote... > In older days before they had mature designs for automobiles you needed to > get under the hood and tinker with it to make it work. > Why do we need to do some tinkering with IDLE if is a mature design? There > should never be a need for special names of program files for it to work > otherwise it requires tinkering. Hey, how about using Py2Exe to build explorer.exe from your select.py, sticking that in your PATH, and rebooting. Is Windows suddenly not a mature design? You are a part of what is known as a naming conflict. That is when two things are referred to by the same name. The built-in select module is of vital importance to a lot of programs. You should not be naming your modules something as meaningless as 'select' and sticking that in the Python path anyway.. What does your module do? What is it a part of? Consider building a package containing your module instead, if you insist on naming it select. eg: DB.SQL.select, or Shopping.CustomerChoice.select, etc. In any case, I think you may have missed some useful information when you first read the Python documentation. (You have read the Python documentation, right? ;) David. From ahmedmo at wanadoo.fr Fri Dec 19 13:01:18 2003 From: ahmedmo at wanadoo.fr (Ahmed MOHAMED ALI) Date: Fri, 19 Dec 2003 19:01:18 +0100 Subject: Problem mapping VB com code to Python References: <4f55e45a.0312191451.73b8f84b@posting.google.com> Message-ID: Hello, try this obj = win32com.client.Dispatch("QBFC2_1.QBSessionManager") Ahmed "max" wrote in message news:4f55e45a.0312191451.73b8f84b at posting.google.com... > I am trying to use a sdk to access quickbooks, the sdk provided a COM > interface and I think it installed the com server files/dlls. A VB > code example is provided, but I can't figure out how to map "Dim > sessionManager As New QBFC2_1Lib.QBSessionManager" > into a corresponding Python statement, when I try > obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get > traceback Shown below. > > I have been able to run makepy and it generates a lovely file. I can > find a Type Library, but need a little help mapping this to be able to > access the com object and call its methods. > > I have included a snipit of the sample VB code and the traceback from > my attempt to create a client com object ? > > Any help much appreciated, > > max > > > > =======Traceback ============= > >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > line 95, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > line 84, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > line 72, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > com_error: (-2147221005, 'Invalid class string', None, None) > > > > > ========= Sample VB code ========== > Option Explicit > > Public Sub Main() > > On Error GoTo ErrHandler > > 'Establish a communication channel with QuickBooks > > 'Create the session manager object, and initiate a conversation > with QuickBooks > Dim sessionManager As New QBFC2_1Lib.QBSessionManager > sessionManager.OpenConnection " ", "QBFC Developer's Guide" > sessionManager.BeginSession "", omDontCare > > > 'Build a set of requests - in this case, containing only one > request > > 'Create the request set (the message set request object) > Dim requestSet As QBFC2_1Lib.IMsgSetRequest > 'Create a qbXML version 2.1 message > Set requestSet = sessionManager.CreateMsgSetRequest(2, 1) > > 'Add a request to the request set. > Dim customerAdd As QBFC2_1Lib.ICustomerAdd > 'AppendCustomerAddRq is called only once here, even though two > values are being set. > Set customerAdd = requestSet.AppendCustomerAddRq > customerAdd.Name.SetValue "Joe" > customerAdd.CustomerTypeRef.FullName.SetValue "East Coast" > > 'Indicate that all requests should be processed, even if one has > an error > requestSet.Attributes.OnError = roeContinue > > > 'Send the request set to QuickBooks > > Dim responseSet As QBFC2_1Lib.IMsgSetResponse > Set responseSet = sessionManager.DoRequests(requestSet) From bdesth.nospam at removeme.free.fr Mon Dec 15 17:02:34 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 15 Dec 2003 23:02:34 +0100 Subject: Small languages (was Re: Lua, Lunatic and Python In-Reply-To: References: <005101c3c1b8$8bcb5e10$210110ac@jsbwxp3> Message-ID: <3fde2b38$0$19276$626a54ce@news.free.fr> Cameron Laird wrote: > In article , > Gustavo Niemeyer wrote: > . > . > . > >>Guile's static library is about 1MB in size. In that case I'd >>choose Python, not Guile. I don't remember about Scheme, but while >>looking for some embeddable language I've gone trough that path, >>and ended up in Lua as the best option. Let me know if you find >>something better. > > . > . > . > I think your decision in favor of Lua's a good one. > Guile and Scheme, from the last I saw of them, are > *not* slender enough to compete. Forth is the one > other serious language that can be tiny enough to > make Lua look stout; Not sure this one could make it but : http://www.iolanguage.com/Comparisons/Size.html I only played a few minutes with it so far, but Io might be something interesting... Bruno From danb_83 at yahoo.com Mon Dec 29 03:36:09 2003 From: danb_83 at yahoo.com (Dan Bishop) Date: 29 Dec 2003 00:36:09 -0800 Subject: NEWBIE: What's the instance name? References: <6q2vuv45lsah3epo9loa7l2tp9517makk4@4ax.com> Message-ID: engsolnom at ipns.com wrote in message news:<6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com>... > Hi, > I've been using constructs(?) like the below. > > def display(instance, start = None, end = None): > if instance.__class__.__name__ == 'UPCA': You might want to try the isinstance function. > do some UPCA stuff > if instance.__class__.__name__ == 'UPCE': > do some UPCE stuff > > launched by: > > lx = UPCA(sx), where sx is a string > then: > display(lx) > > This all works well. > > What I'd like to do is display is the instance name. Is it hiding > somewhere? You mean you'd like display(lx) to print "lx"? What would you expect the folowing code to do? a = b = MyClass() display(a) # "a" or "b"? display(a + b) # Creates an instance without a name. display(2) # Literals have no names either. Now do you see why the functionality you want isn't implemented? > Also, if I have a string 4 chars long, representing two bytes of hex, > how can I *validate* the string as a *legal* hex string? > > isdigit works until string = '001A', for example > isalnum works, but then allows 'foob' > > Is there a 'ishexdigit'? I could parse the string, but that seems > "un-Pythonish" Unfortunately, no, but you can use "ch in string.hexdigits", at least until Python 3.0 (or whenever the string module is going away). From jzgoda at gazeta.usun.pl Mon Dec 22 14:47:30 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 22 Dec 2003 19:47:30 +0000 (UTC) Subject: any one used googles api? References: Message-ID: Bill Sneddon pisze: > Like a lot of modules in Python. It reduces the problem to a trivial > level. Great way to be productive quickly but does not convey much > understanding of problem. For understanding, go to Google API documentation, than later check http://effbot.org for Python implementation. -- Jarek Zgoda Unregistered Linux User # -1 http://www.zgoda.biz/ JID:zgoda at chrome.pl http://zgoda.jogger.pl/ From matt at pollenation.net Tue Dec 30 10:38:15 2003 From: matt at pollenation.net (Matt Goodall) Date: Tue, 30 Dec 2003 15:38:15 +0000 Subject: Storing objects required by functions. In-Reply-To: <99dce321.0312300655.14c5a8db@posting.google.com> References: <99dce321.0312300655.14c5a8db@posting.google.com> Message-ID: <3FF19BE7.3020109@pollenation.net> David M. Wilson wrote: >Further to my last post here, I was playing some more with building a >regex object and storing it somewhere for use internally by a >function. I'm not happy with any of my solutions: > > ># I don't like this, but the fact that you can modify the procedure's ># function via a named argument seems neat in a hacky sort of way. > >def uses_default_parm_yuck(x, r = re.compile("...")): > pass > > >g = re.compile('...') > >def uses_global_yuck(x): > global g > pass > > There is no need to define g as global unless you actually need to rebind g inside the function. > ># This is horrible and probably slow. > >class is_hex: > def __init__(self): > self.r = re.compile('...') > > def __call__(self, x): > r = self.r > pass > >is_hex = is_hex() > > I doubt it's that much slower (if at all). You should profile it to check. > ># This mucks up scoping so that your procedure can't access it's ># parent scope like it could normally. Since I never do this, ># it's my favourite. > >def is_hex(): > r = re.compile('...') > def is_hex(s): > return r.match(s) is not None > return is_hex > >is_hex = is_hex() > > > >Am I missing something? Is there a nicer way of doing this? On a day >to day basis I find myself in this situation quite regularly, and now >I come to think of it today, it is something that I would like to >improve. > >It is funny that in private it has never bothered me much, but when >posting on comp.lang.python I find that the code is unacceptable. >Maybe I have two modes of programming, idealist and practical? *shrug* >:) > > >David. > > Another alternative relies on the fact that functions themselves are objects so you could do this: def is_hex(s): return is_hex.r.match(s) is not None is_hex.r = re.compile(...) Although, for simplicity, I would probably just make the compiled regex a module scope variable with a sensible name, maybe even using the _ prefix to hint that noone should touch it: _is_hex_regex = re.compile(...) def is_hex(s): return _is_hex_regex.match(s) is not None Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenationinternet.com e: matt at pollenation.net From peter at engcorp.com Thu Dec 4 17:10:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Dec 2003 17:10:09 -0500 Subject: ISO to Gregorian, strptime madness References: <3FCF562A.23E44C27@engcorp.com> Message-ID: <3FCFB0C1.1AC5311A@engcorp.com> Afanasiy wrote: > > On Thu, 04 Dec 2003 10:43:38 -0500, Peter Hansen > wrote: > > >Afanasiy wrote: > >> > >> While I'm posting, how about this old dilemma... from the 2.3 modules. > >> strptime exists in time, but not in datetime, while strftime exists in > >> both. > > > >Uh, really? > > > >Looks to me like strptime and strftime are both in time and not in datetime. > > Yeah I didn't remember the specifics, but it's something like that. > Something that I needed to have strptime does not have it, but has > strftime. I am a sorry for that mistake now, because of your reply. > > This is not the primary concern of the post, and not even secondary, > so please ignore the silly mistake and help with the other things. I wish I could help, but I don't know anything about this area. I was just struck by the seeming irregularity, but upon investigating I didn't see the same thing you did so I pointed it out. (To be honest, I don't see the problem with a two-line solution, which could easily be encapsulated in a simple function if it looks too ugly for you.) -Peter From martin at v.loewis.de Mon Dec 1 01:53:33 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Dec 2003 07:53:33 +0100 Subject: Unicode output to file References: Message-ID: =?windows-1251?b?xeLj5e3o6SDK7vHl7eru?= writes: > I use here Russian letters, and need special encoding for them. The > property 'encoding' is read-only, and is None by default. How to > cast the encoding for a file? You should use codecs.open instead of the builtin open function; this allows you to pass an encoding for the file stream. HTH, Martin From amk at amk.ca Fri Dec 12 10:35:58 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 12 Dec 2003 09:35:58 -0600 Subject: ANN: Twisted 1.1.1 References: <8765gowgp7.fsf@mobile.foo> <3fd788bd$0$204$e4fe514c@news.xs4all.nl> Message-ID: On Wed, 10 Dec 2003 21:57:33 +0100, Irmen de Jong wrote: > While you're at it-- is there somewhere a *recent* tutorial on > using asyncore/asynchat? Sam Rushing's one (found via Google) > is from 1999... Not really; I've been thinking of writing one, though, given that there are still people using asyncore and the existing material is so sparse. --amk From swalters_usenet at yahoo.com Wed Dec 31 21:59:02 2003 From: swalters_usenet at yahoo.com (Samuel Walters) Date: Thu, 01 Jan 2004 02:59:02 GMT Subject: Python Job Market References: Message-ID: |Thus Spake Dave Brueck On the now historical date of Wed, 31 Dec 2003 09:47:31 -0700| > From what I've seen the market is definitely growing, but if you're > hunting job > listings for an all-Python job the pickings are pretty slim. *sigh* I know. I didn't ask my question here without first searching around to see what was being asked for. It was not encouraging. > The easiest > way to use Python in your job will probably be if you introduce it to > the company yourself and then use it as the opportunities arise, but not > try to force it - if it's not the right tool for a particular job then > using it anyway will hurt its acceptance in cases when it _is_ the right > tool. > > An easy entry point is on small tasks that don't _appear_ to be that > important, such as automating your build/release process, writing test > harnesses, and any other internal dev/QA utilities. From there it's an > easy migration to tools used in production but aren't outward (customer) > facing, such as tools that process log files and load them into the > database or generate reports, or monitoring scripts for production > systems - behind-the-scenes stuff. Write a few utilities to make the > lives of the IT / Operations staff easier, and they'll defend Python to > the death. :) I have a funny story about this type of python advocacy. Forgive me if I bellyache for a while. I think this is the first time I can describe this situation to people who can understand where I'm coming from. I'm sure a few of you have gone through this too. I picked up python while at my last development job. We processed medical insurance claims, which come in a scadzillion different formats. The one thing that all these formats have in common is that they're designed to be mainframe friendly. That means fixed width fields in lines of uniform length. The basic process was to get the file, archive it, do some basic validity checking and log some information to a database before concatenating everything into a big file for ftp'ing to the mainframe. It was a batch process, so essentially a set of daemons watched a directory for new files, grabbed them, performed some transformation, then dumped it to another directory for the next daemon to process. I was sold on Python the moment I learned how to slice a string. I started simple. "Hey guys, you all used to be cobol programmers. I found this new language that's really easy to learn and can handle records almost like cobol does, and it will talk to our database!" "That's nice Sam, but we're a C++ shop." (Side Note: The only object in our code was a crude dictionary class I slipped into the all C code base a few months after starting work there. My entire team was baffled by the linked list inside of it, but eventually they just accepted that it did what they wanted it to do.) The only person I can get to listen to me is my old boss, Jason, the team leader of the computer operators. He's voraciously curious about all things computer-related and we had a ball exploring the language. We start scripting all kinds of things, big and small. I don't think I've ever had so much fun learning a language. So, in an effort just to learn python and apply it to a domain I know well, I develop some classes that allow me to parse our files by almost directly transliterating the file definition formats into some simple calls. Essentially the classes allowed you to retrieve a byte range in a string via a name, and defined legal variations of those slices. In a nutshell, I implemented cobol data structures in Python. This took me a grand total of a week. The next week I implemented a set of tools that could identify what format a particular file was if I had already transcribed the structure. The week after, I had the class able to build the standard format reference sheet documentation and a complete set of regression files for error checking. On the fourth week, I implemented a simple class to pull data out of our logging database and check that it matched a file that was supposed to have been processed. I show this to Jason, and we both declare "There is a god, and his name is Guido, pronounced with a 'Ch.'" We figured that all we'd have to do is wait for the something to go wrong, use the new tools to diagnose the problem faster than we ever could before, and then when asked how it was solved so fast, they'll be eager to see our new toy. Well, that opportunity came several times. Each time noone had time to look at any of the scripts I had written. Each time I was told never to use any of it in a production system. Nevermind that I wasn't trying to put python code into production. I was just using it to identify where our existing code was failing. It went on this way for about a month and a half. Meanwhile, several of the mainframe cobol programmers, including their team lead, said that they want to learn some PC programming. I love to teach, especially programming, so I thought "Excellent! I've got some tools that work in a paradigm they already know and we can ease them into the PC world with it." We all start meeting once a week to talk about python. They loved it. All of them agreed that this is the first PC programming experience they'd had that made sense. (I also learned a *lot* about mainframes from that.) Then an odd opportunity came up. We had just been awarded a big new contract. We were taking it over from a company that had very different ideas than us on how to process claims, so there were about a hundred or so new formats to process. Each one had to be redocumented and a regression suite developed for it. About a week into the affair, I go visit Charles, our lead QA man, and he remarks that it's horribly tedious documenting and editing each of the test files by hand. That's when I find out that they've been building their regression suites by hand with a hex editor for years. It dawns on me. I've developed exactly the sort of tool these guys need. I tell Charles that I built a tool that might be able to help him, but he'll have to help me test it and make sure it does what he wants it to do. This was a bald-faced lie. I knew it did exactly what he wanted it to do. I had tested it against the files he sent me for phase 1 QA. I just wanted an excuse to get him to browse the code with me. That night, we stayed late to hash things out. The first thing I did is open a format definition module. His reaction: "That looks almost exactly like we document it! If I had that, I'll I'd have to do is cut and paste parts of it into an excel." So, I double click the icon labeled "documenter" It prompts me for a format name, I type one in. An excel icon appears on my desktop. I double-click it. Charles stutters: "D..did it just make that? From the synopsis? That takes me an hour to type up!" (the beauty of csv's) Charles and I spent a couple of weeks double and triple checking that the regression suite is exactly as it should be. We didn't change a single lick of the code. The QA people still had to verify that the regression sweet matched the expected output, but now they didn't have to edit it in hex, and they only had to write the documents once to have it exported to the other formats they wanted. Two weeks later, QA people started to show up at our python meetings. Somewhere between six months and a year passed. It seemed that I was able to get everyone but the people who would most benefit to look at python. For reasons completely unrelated to the job, I had to move. They replaced me with a perl programmer (who's apparently a pretty good coder.) In the absence of my close working relationship with Charles, the QA guy, it was decided that they needed a liason between the pc team and the QA team. Jason, the first person to take an interest in my python craze, was promoted into that position. My contacts there tell me that they're in the process of switching to being a python shop. Even the perl guy converted. It seems that every time my old team floundered with a problem, someone would mention that I had written a program to check for errors of type Foo. They'd dig it up. I guess what I did wrong in being a python advocate was that I didn't stop being right. They didn't notice the difference those tools made until I wasn't around to use them. I think python might possibly become *the* killer app for that company. It handles everything they do so naturally, especially once I got that library there to abstract the data. *sigh* I just wish I had been around to enjoy things running smoothly. I don't think I've ever felt like a language let me work with a data format so naturally. Thank you for putting up with that very loquacious rant. It's been pent up a long time and I feel better I feel better thinking that someone, somewhere probably understands how I feel. You know. I never thought about this before. Maybe I could find a niche reformatting old cobol records and systems. Is there any demand for that sort of thing? While a mainframe can be an absolutely wonderful tool if it's the type of thing you require (nothing beats the data integrity of a well run mainframe) they're expensive. I imagine that a lot of companies are looking to cut the expense of maintaining big iron. I can't say that I understand mainframes and cobol, but I do understand how they like to talk about data. I spent a long time making sure a mainframe got what it wanted. > Another entry point is through web development, e.g. using Zope or > Webware or Quixote first for an intranet, and later for actual > production websites. In all cases it seems to be a matter of the new > technology getting a foothold, an opportunity where it can prove its > usefulness. Having a meeting and deciding e.g. "will we use Java or > Python?" is IMO the worst possible route: you can argue forever on > theoretical problems that may arise, whereas most critics are silenced > when faced with a real, working, and reliable example that's already in > use. I am definitely looking at web development. That's the other thing I did at that job. I wrote cgi in c to get our database to talk to the web. While developing cgi from scratch in c is not an experience I'd like to repeat, I enjoyed developing it. It was nice to build a system from the ground up and grin to myself about the uptime. > If you're introducting Python (or any new technology, for that matter), > it seems to be easiest in really big companies or really small companies > (YMMV as I'm basing this on only 3 or 4 data points for which I've had > first-hand experience :-) ) where the initial number of people affected > is small. In a big company development is likely divided into teams for > different areas of functionality or different products, so using Python > locally isn't likely to ruffle many feathers. In a medium-sized company > I've seen a single product with sub-teams, and higher resistance to do > anything different (sadly, at one such company there was enough > agreement to prototype a new system in Python, but even though the > prototype was robust, fast, and _fully-functioning_, too many developers > refused to see it as anything but a prototype, and insisted on > reimplementing it in Java. The result was slow, flaky, and was never > completed. Grrr.). I think people tend to over-estimate the the value of compile-time type checking. That's a big minus in the heads of a lot of people. I know it was one of the hardest things for me to get over. Then I realized that I can check the type and structure of a data-item in Python any time I please as often as I please. I can make it as stringent as I like rather than convincing a compiler that I want less strict typing. Of course, I may be wrong. I haven't really coded anything where interactivity is an issue. The fact that python was not a big name language also made a difference in it's consideration for the company I used to work for. Turnover was high on my team, and they were always wondering "who are we going to get to replace you when you're gone." I don't blame them. I'm very glad they picked up someone with enough culture to have learned perl. I think he came into the situation with a lot of good mental models for the type of processing they do. I understand that he's the one maintaining my cgi scripts and database, and probably does a good job of it. > The most success I've had with Python is in a small company where there > is _way_ too much work to get done. Here there are fewer people to cry > foul when you do something different, a much greater emphasis on results > (so any tool that boosts productivity is favored), and generally fewer > layers in the decision-making hierarchy. That's the current situation > I'm in, doing server, web, database, and Win32 client development all in > Python (with very occasional work in C/C++). We didn't have a big > meeting to set a mandate that we're an all-Python company, but over time > the projects in Python flourished because the initial versions got done > so quickly, bugs have been few with fixes coming quickly, the cost of > adding new features has been low, and the developers have been able to > take on additional projects. The non-Python projects have gained a > reputation of being slow-moving, complex resource gluts (in terms of > developers needed) and have fallen by the wayside. I can't count the times I've hashed out a bit of pseudo-code on a napkin, gotten it home and realized that I almost wrote out the entire program in python. If I have three weeks to accomplish a task, I would rather spend one week coding and two weeks testing than two weeks coding and one week testing. Especially considering that with python, it's easier to develop a reusable testing suite. Okay. Now I think I've finally crossed the line where I'm just preaching to the choir. > It's funny to sit in on a sales call because now even our sales guys > "brag" that Python-based technology is part of our competitive advantage > as if it's our secret sauce or something, whereas initially it was more > "Shh, lest people find our we're using some weird scripting language". I imagine it's funny. It was odd to see who became allied with me and who didn't. In my naivety, I thought the hard-core code monkeys would be the first to recognize how much time and energy python could save them. Instead, it was the normals who saw it. I remember when Charles and I decided to see if tech-support could make use of any of the scripts. It saved them a whole step of searching a six-inch thick document for what might betray one offensive character in a 3 meg file. I showed them how modify the messages thrown and they even went through and put page numbers into each error message so that they didn't have to bother with the index. Though, I think the most wonderful part about doing all this was that, after having helped all these people in "other" departments, I had an army of people eager to help me. The few times when I did royally screw up, people were not only eager to help clean up the mess I made, they had the time to help. That, if nothing else, is what I learned about life in the corporate world. Well, I'll be surprised if anyone has read this far into my rant. Sorry, I guess I just had a lot of pent-up frustration to get out. And, well. Ranting is not exactly a novelty on usenet, now is it? As far as my original question goes. I'm at a stable place in my life. I'm doing work in the first field I ever truly loved: teaching math. I have about six months to a year to prepare for where I'm going from here. I've run linux at home for around 4 years. While I'm pretty comfortable in it, I need to focus on learning what it takes to run a mission-critical server well. Running your home 'puter on a 1337 05 is a far cry from a maintaining a system for others. I've also begun poking around the internals of python with the intent of becoming more competent with it and comfortable with the python-c api. I'd love to end up doing sysadmin/web dev/python dev work somewhere. I've also started mapping out where I might be able to help the community since, *gasp*, I finally have spare time. Any advice how to get there from here is most welcome. Sam Walters -- Never forget the halloween documents. http://www.opensource.org/halloween/ """ Where will Microsoft try to drag you today? Do you really want to go there?""" From tzot at sil-tec.gr Wed Dec 31 19:08:15 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 02:08:15 +0200 Subject: Maybe a stupid idea References: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: On 31 Dec 2003 09:49:55 -0800, rumours say that sebb at linuxcult.com (sebb) might have written: >Here is a simple example : > >b=0 > >while b < 50: > b+=1 > print "*" * b > >while b > 0: > b-= 1 > print "*" * b > >It takes two while blocks to do a cycle. Another way to do the above in a single block: for a in xrange(-49, 50): b= 50-abs(a) print "*" * b or the more cryptic (which you really should ignore): from itertools import imap for a in imap(50 .__sub__, imap(abs, xrange(-49, 50))): print "*" * b Note that significant space between "50" and "." :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From gamasutra1000 at yahoo.com Wed Dec 31 19:14:33 2003 From: gamasutra1000 at yahoo.com (Julia Osip) Date: 31 Dec 2003 16:14:33 -0800 Subject: newbie question Message-ID: <4ebabbc5.0312311614.2446e31c@posting.google.com> Hi, just started fiddling around with python, having some difficulty getting the following small play program to execute. Furious searching in the docs, manual, newsgroup did not avail me, does anyone have any ideas what might be the problem? Some sort of whitespace issue (im still unsure of whitespace rules)? I'm running Mac OS 10.2.8, with MacPython 2.3. Thanks for any help you can give... the code ...snip... #!/usr/bin/env python class World: """contains everything""" def __init__(self): self.name = "world" self.locations = [] # list of all locations in the world self.dist_locations = [] # the amount of travel time required between locations self.actors = [] # list of all actors in the world self.organizations = [] # list of all organizations in the world self.time = 0 # current moment in the world return ...snip... the error ...snip... File "", line 7 def __init__(self): ^ SyntaxError: invalid syntax ...snip... From shaleh at speakeasy.net Wed Dec 31 20:24:24 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed, 31 Dec 2003 17:24:24 -0800 Subject: newbie question In-Reply-To: References: <4ebabbc5.0312311614.2446e31c@posting.google.com> Message-ID: <200312311724.24605.shaleh@speakeasy.net> On Wednesday 31 December 2003 16:51, engsolnom at ipns.com wrote: > Try getting rid of the 'return' > Norm > you are right, the return here is not needed. A return statement is only required when: a) you want to leave a function early b) you actually want to return something From elainejackson7355 at home.com Wed Dec 31 19:30:00 2003 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 01 Jan 2004 00:30:00 GMT Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: dict2=dict([(a,b) for b in dict1.keys() for a in dict1[b]]) HTH "Irmen de Jong" wrote in message news:3ff1b688$0$319$e4fe514c at news.xs4all.nl... | Hi | I have this dict that maps a name to a sequence of other names. | I want to have it reversed, i.e., map the other names each to | the key they belong to (yes, the other names are unique and | they only occur once). Like this: | | { "key1": ("value1", "value2"), "key2": ("value3,) } | | --> | | { "value1": "key1", "value2": "key1", "value3": "key2" } | | What I'm doing is using a nested loop: | | dict2={} | for (key,value) in dict1.items(): | for name in value: | dict2[name] = key | | which is simple enough, but I'm hearing this little voice in | the back of my head saying "there's a simpler solution". | Is there? What is it? ;-) | | Thanks | --Irmen. | From vvikram at stanford.edu Wed Dec 31 18:40:28 2003 From: vvikram at stanford.edu (Vikram) Date: Wed, 31 Dec 2003 15:40:28 -0800 Subject: fatal error: GC object already tracked Message-ID: hi, i have a program which uses multiple threads and downloads pages using pycurl and processes these pages among other things. the program works fine with python 2.2 and pycurl 7.10.8 ; with python 2.3 i get two kinds of errors maybe related? a) python dumps core and prints out "Fatal Python error: GC object already tracked" b) the program just waits at update_refs() function inside the python GC code path and doesn't append anything to the logs nor perform any activity. any idea why or suggestions ? Vikram ps: the Fatal Python error: GC object already tracked" error seems to be an open bug filed by someone else in october 2003. --- (gdb) bt #0 0x8819082c in kill () from /usr/lib/libc_r.so.4 #1 0x881dea8a in abort () from /usr/lib/libc_r.so.4 #2 0x80d4eb5 in Py_FatalError () #3 0x80855b4 in PyTuple_New () #4 0x80b340a in load_args () #5 0x80b2dc8 in call_function () #6 0x80b02ac in eval_frame () #7 0x80b3054 in fast_function () #8 0x80b2eb5 in call_function () #9 0x80b02ac in eval_frame () #10 0x80b3054 in fast_function () #11 0x80b2eb5 in call_function () #12 0x80b02ac in eval_frame () #13 0x80b3054 in fast_function () #14 0x80b2eb5 in call_function () #15 0x80b02ac in eval_frame () #16 0x80b1821 in PyEval_EvalCodeEx () #17 0x80b30fd in fast_function () #18 0x80b2eb5 in call_function () #19 0x80b02ac in eval_frame () #20 0x80b1821 in PyEval_EvalCodeEx () #21 0x80b30fd in fast_function () #22 0x80b2eb5 in call_function () #23 0x80b02ac in eval_frame () #24 0x80b1821 in PyEval_EvalCodeEx () #25 0x80f6fc6 in function_call () #26 0x805ad0f in PyObject_Call () #27 0x80b3750 in ext_do_call () #28 0x80b03d1 in eval_frame () #29 0x80b3054 in fast_function () #30 0x80b2eb5 in call_function () #31 0x80b02ac in eval_frame () #32 0x80b1821 in PyEval_EvalCodeEx () #33 0x80f6fc6 in function_call () #34 0x805ad0f in PyObject_Call () #35 0x8061b7d in instancemethod_call () #36 0x805ad0f in PyObject_Call () #37 0x80b2a80 in PyEval_CallObjectWithKeywords () #38 0x80db217 in t_bootstrap () #39 0x8816b0a8 in _thread_start () from /usr/lib/libc_r.so.4 #40 0x0 in ?? () From http Wed Dec 31 20:34:18 2003 From: http (Paul Rubin) Date: 31 Dec 2003 17:34:18 -0800 Subject: Maybe a stupid idea References: <56f42e53.0312310949.39826ffd@posting.google.com> Message-ID: <7xhdzgmoyt.fsf@ruckus.brouhaha.com> sebb at linuxcult.com (sebb) writes: > I know that cycles is not a structure of any programming language, Maybe there's a reason for that. > but I want some opinions the know if my idea is stupid or not. Well, why would you want such a feature? What real programming situations would you use it in? From engsolnom at ipns.com Wed Dec 31 19:51:13 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Wed, 31 Dec 2003 16:51:13 -0800 Subject: newbie question References: <4ebabbc5.0312311614.2446e31c@posting.google.com> Message-ID: Try getting rid of the 'return' Norm On 31 Dec 2003 16:14:33 -0800, gamasutra1000 at yahoo.com (Julia Osip) wrote: >Hi, just started fiddling around with python, having some difficulty >getting the following small play program to execute. Furious >searching in the docs, manual, newsgroup did not avail me, does anyone >have any ideas what might be the problem? Some sort of whitespace >issue (im still unsure of whitespace rules)? I'm running Mac OS >10.2.8, with MacPython 2.3. > >Thanks for any help you can give... > >the code >...snip... >#!/usr/bin/env python > >class World: > > """contains everything""" > > def __init__(self): > self.name = "world" > self.locations = [] # list of all locations in >the world > self.dist_locations = [] # the amount of travel time required >between locations > self.actors = [] # list of all actors in the world > self.organizations = [] # list of all organizations in the world > self.time = 0 # current moment in the world > return > >...snip... > >the error >...snip... > File "", line 7 > def __init__(self): > ^ >SyntaxError: invalid syntax >...snip... From shaleh at speakeasy.net Wed Dec 31 19:54:48 2003 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Wed, 31 Dec 2003 16:54:48 -0800 Subject: newbie question In-Reply-To: <4ebabbc5.0312311614.2446e31c@posting.google.com> References: <4ebabbc5.0312311614.2446e31c@posting.google.com> Message-ID: <200312311654.48596.shaleh@speakeasy.net> On Wednesday 31 December 2003 16:14, Julia Osip wrote: > Hi, just started fiddling around with python, having some difficulty > getting the following small play program to execute. Furious > searching in the docs, manual, newsgroup did not avail me, does anyone > have any ideas what might be the problem? Some sort of whitespace > issue (im still unsure of whitespace rules)? I'm running Mac OS > 10.2.8, with MacPython 2.3. > you might consider joining the tutor at python.org mailing list. It is meant to help people new to python. > Thanks for any help you can give... > > the code > ...snip... > > the error > ...snip... > File "", line 7 > def __init__(self): > ^ > SyntaxError: invalid syntax > ...snip... As you guessed it is a whitespace problem. So, let's clear up the whitespace rules for you. There is one key rule -- be consistent. Python does not really care if you use 4 space indents or 8. It does care if you try to use both. Same goes for mixing spaces and tabs. As Python reads your code it figures out what your indent style is and then enforces that for the rest of the block. When Python read your class definition the first indentation it found was for the docstring which was 4 spaces. Then it went to the next line of code and found an indentation of 8. This is what caused the error. Now, maybe this is because you hand indented the docstring by four spaces and then used a tab on the line starting with 'def'. Or maybe you thought you needed to indent again (you don't). From tzot at sil-tec.gr Wed Dec 31 19:24:39 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 02:24:39 +0200 Subject: Uplevel functionality References: Message-ID: On Wed, 31 Dec 2003 12:41:02 -0500, rumours say that "Terry Reedy" might have written: >> This allows me to do: >> >> repeat 5 {puts "hello"} >> >> prints: >> hello >> hello >> hello >> hello >> hello > >for i in range(5): print 'hello' # does same thing. >repeat(5, "print 'hello'") # even if possible, saves all of 5 key >strokes >repeat(5, lambda: print 'hello') # possible, without uplevel, takes 2 more print is invalid in a lambda (like other statements) as you most surely know. I would guess the champagne is to blame? :-) Happy new year! -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From bokr at oz.net Wed Dec 31 18:50:03 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Dec 2003 23:50:03 GMT Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> <3ff30f2f.674586974@news.blueyonder.co.uk> Message-ID: On Wed, 31 Dec 2003 20:04:24 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >Aubrey Hutchison wrote: >> Why do I need to tinker with it? >> >> You don't need to tinker with mature programs. > >I readily admit that IDLE is not a >"mature program". > >Happy now? Perhaps Aubrey is fishing for suggestions he can't think of himself? Or maybe he just enjoys the chiding role, who knows? ;-) Anyway, there might be some use in thinking about the underlying issue, which ISTM is occasional failures in robust handling of name clashes (which one could suspect Aubrey might have contrived to demostrate with select.py, or maybe he just bumped into it). One could program checks before importing, I suppose. Or, if being able to filter out non-suitable modules on the import path were generally valuable, one could consider inventing an optional check in the import mechanism itself. E.g., if __import__ had an optional keyword argument like __import__(..., checkmeta=('cookie', 'some string')) and file metadata could be declared with e.g. # -*- cookie: 'some string' -*- in the first few lines, and if metadata were also stored in .pyc and .pyo files for easy access without importing, then import could see the checkmeta optional arg and do a pre-check for equality and if no match, continue searching per the path, or raise an exception (perhaps an "assertmeta" spelling of the option to do that). With this sort of thing in place, idle could presumably import what it really wanted, and if Aubrey put # -*- cookie: 'some string' -*- in his select.py file, we could tell him we think he intended the end result ;-) One could also allow a sequence of tuples for multiple required checks, e.g., __import__(..., checkmeta=( ('cookie','something'), ('coding','latin-1'))) (Don't tell Guido that some people might start putting # -*- version: 'xxx' -*- in their files, and importing with checkmeta=('version','xxx') ;-) Regards, Bengt Richter From python at rcn.com Wed Dec 31 23:40:45 2003 From: python at rcn.com (Raymond Hettinger) Date: 31 Dec 2003 20:40:45 -0800 Subject: 'inverting' a dict References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> <5b4785ee.0312301604.4934c96@posting.google.com> <3ff2cba6$0$316$e4fe514c@news.xs4all.nl> Message-ID: <5d83790c.0312312040.760a5ae4@posting.google.com> Irmen de Jong wrote in message news:<3ff2cba6$0$316$e4fe514c at news.xs4all.nl>... > Wade Leftwich wrote: > > > def invert_dict(D): > > return dict([(y,x) for (x,y) in D.items()]) > > No, this one only works for non-sequence-type values. > I wanted to map every item of a value (a sequence) > to the corresponding key. > > --Irmen Try a nested list comprehension: >>> data = { "key1": ("value1", "value2"), "key2": ("value3",) } >>> dict([(v,k) for k,vlist in data.iteritems() for v in vlist]) {'value3': 'key2', 'value2': 'key1', 'value1': 'key1'} Raymond Hettinger P.S. In Py2.4, it will be possible to write this without the brackets. The resulting generator expression is faster and more memory friendly: >>> dict((v,k) for k,vlist in data.iteritems() for v in vlist) {'value3': 'key2', 'value2': 'key1', 'value1': 'key1'} From tzot at sil-tec.gr Wed Dec 31 19:41:40 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 02:41:40 +0200 Subject: Test if IDLE is a mature program References: <7ti4vvoburp4k4o4a0v5p4shae7o5uhotb@4ax.com> <99dce321.0312311130.5b7c7c8a@posting.google.com> Message-ID: On Wed, 31 Dec 2003 22:43:44 GMT, rumours say that Lee Harr might have written: >(please no one bring up those two _particular_ >editors at this point :o) there is no such thing as a bad time to mention vi and that other editor... And btw IDLE is not mature, and that explains why it's cute! (hic! happy new year) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From newsgroups at jhrothjr.com Wed Dec 31 18:58:35 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 31 Dec 2003 18:58:35 -0500 Subject: PythonWin problems References: Message-ID: "Colin J. Williams" wrote in message news:z5GIb.10324$Vl6.2031681 at news20.bellglobal.com... > PythonWin has been my favourite IDE for quite a while. > > When one right clicks on a .py file in the Windows Explorer, among the > options are Open and Edit. The former is the default and executes > Python, with the selected script. The latter activates the PythonWin > editor, with the selected script. > > Since, most frequently, I wish to edit the script, or execute it with > the debugger, I tried changing the default to Edit, using the Edit File > Type menu. > > Unfortunately, this leads to a couple of problems: > > 1. Any activity becomes horrendously slow, and > 2. The following message appears: > LoadBarState failed - LoadBarState failed (with win32 exception!) > [Dbg]>>> > > Does anyone have a workaround suggestion? You're going to have to get down and dirty with the registry, I'm afraid. This is the way my registry looks for Python 2.2 (I don't have 2.3 installed yet.) This is in registry patch format which is imported and exported by regedit. Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\Python.File] @="Python File" [HKEY_CLASSES_ROOT\Python.File\AutoRegister] @="C:\\WINDOWS\\System32\\PythonCOM22.dll" [HKEY_CLASSES_ROOT\Python.File\DefaultIcon] @="C:\\PROGRA~1\\PYTHON22\\Py.ico" [HKEY_CLASSES_ROOT\Python.File\shell] [HKEY_CLASSES_ROOT\Python.File\shell\Edit] [HKEY_CLASSES_ROOT\Python.File\shell\Edit\command] @="C:\\PROGRA~1\\PYTHON22\\lib\\site-packages\\Pythonwin\\pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE] [HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command] @="C:\\PROGRA~1\\PYTHON22\\pythonw.exe C:\\PROGRA~1\\PYTHON22\\Tools\\idle\\idle.pyw -e \"%1\"" [HKEY_CLASSES_ROOT\Python.File\shell\open] [HKEY_CLASSES_ROOT\Python.File\shell\open\command] @="C:\\PROGRA~1\\PYTHON22\\python.exe \"%1\" %*" [end of registry patch] Restore yours to look something like this (and make sure you don't put my values into your system - they probably won't work!) Once you do that, change (or add) the default value of the [HKEY_CLASSES_ROOT\Python.File\shell] key to say "Edit". That's all there is to it. Remember to back up your registry first, or at least save the key your playing with. If you're reluctant to get that close to the registry, there are a large number of resources on the net, and I heartily recommend "Windows XP annoyances" by David Karp (O'Reilly). The information on file types and associations is the same for all Windows versions. John Roth > > Thanks. > > Colin W. > From bvdpoel at kootenay.com Wed Dec 31 21:23:04 2003 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Wed, 31 Dec 2003 19:23:04 -0700 Subject: 'inverting' a dict In-Reply-To: References: <3ff1b688$0$319$e4fe514c@news.xs4all.nl> Message-ID: <3ff3848f_1@dns.sd54.bc.ca> This is sort of off topic for the thread, but I've got a similar problem. In this case I have a dict like: { 'key1': 'value1', 'key2': value2} and I sometimes need to find the key for the value. All values/keys are unique. I just use a loop: for a in dict: if dict[a]== targ: return a return None But it'd be nice to have something faster, etc. Elaine Jackson wrote: > dict2=dict([(a,b) for b in dict1.keys() for a in dict1[b]]) > > HTH > > > "Irmen de Jong" wrote in message > news:3ff1b688$0$319$e4fe514c at news.xs4all.nl... > | Hi > | I have this dict that maps a name to a sequence of other names. > | I want to have it reversed, i.e., map the other names each to > | the key they belong to (yes, the other names are unique and > | they only occur once). Like this: > | > | { "key1": ("value1", "value2"), "key2": ("value3,) } > | > | --> > | > | { "value1": "key1", "value2": "key1", "value3": "key2" } > | > | What I'm doing is using a nested loop: > | > | dict2={} > | for (key,value) in dict1.items(): > | for name in value: > | dict2[name] = key > | > | which is simple enough, but I'm hearing this little voice in > | the back of my head saying "there's a simpler solution". > | Is there? What is it? ;-) > | > | Thanks > | --Irmen. > | > > -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From okyoon at stanford.edu Wed Dec 31 22:31:15 2003 From: okyoon at stanford.edu (Oh Kyu Yoon) Date: Wed, 31 Dec 2003 19:31:15 -0800 Subject: Graph in wxPython Message-ID: Does anyone know how to implement plots from scipy, chaco, etc into wxPython widget? Thank you From tzot at sil-tec.gr Wed Dec 31 19:43:45 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 02:43:45 +0200 Subject: Tkinter References: Message-ID: On Wed, 31 Dec 2003 13:02:18 +0530, rumours say that km might have written: >Hi all, >I am in need of some sample scripts which cover vital issues of starting Tkinter with Python. Can somebody provide me with such links ? Start with your installation's idle.py (assuming it's there :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From tzot at sil-tec.gr Wed Dec 31 18:55:07 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 01 Jan 2004 01:55:07 +0200 Subject: ...And a happy new year btw (NT :) Message-ID: -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From engsolnom at ipns.com Wed Dec 31 18:47:06 2003 From: engsolnom at ipns.com (engsolnom at ipns.com) Date: Wed, 31 Dec 2003 15:47:06 -0800 Subject: NEWBIE: Sub-classes revisited Message-ID: Thanks for the patient help. My preconcieved notions about sub-classes were wrong. After re-reading the tutorial, and the responses to my postings, I think I've learned a bit. (Hope so, anyway) In the case of: # IN MOD_1.PY class B: def __init__ (self): self.B_init_var = 1 def B_meth(self): self.B_meth_var = 2 # IN MOD_2.PY import mod_1 class A(mod_1.B): # B needs to be qualified def __init__(self): mod_1.B.__init__(self) # Needs to be qualified self.B_meth() # But B's method doesn't print self.B_init_var # Just to be sure print self.B_meth_var # Ditto obj = A() Is the following true? 1. When A is instantiated, B's name space is exposed to A. 2. B is not instantiated when A is, therefore B's init is not run. 3. If A can't find B_meth in it's own namespace, it looks in B's namespace. 4. If one attempts to run B's init in A's init, using self.__init__(), one is in for a long wait...:) 5. B's init in A's init must be qualified to prevent #4 6. The proper terminology is: 'A inherits B's methods and attributes' 7. An init in B is of limited usefulness. 8. If all one needs is to 'declare and inialize' variables common to a number of classes, one really doesn't need a base class, just a module containing the 'constants'. But if there are methods which are semi-common to all sub-classes, and can be overidden or extended to do the job, then it makes sense to use inheritance. 9. Inheriting variables (only), then (always) over riding their values in the sub-classes doesn't save memory. All comments welcome. Thanks....Norm From a.schmolck at gmx.net Wed Dec 31 23:30:11 2003 From: a.schmolck at gmx.net (Alexander Schmolck) Date: 01 Jan 2004 04:30:11 +0000 Subject: RELEASED: allout-vim 031229 References: Message-ID: Fran?ois Pinard writes: > There are a few words which are dangerous, as having very > different meanings in French and English, this sometimes yield to > misunderstandings. For example, English "to deceive" is much, much > stronger than French "decevoir". In French, we easily use "formidable" > to describe a girl who is wonderfully sympathetic and/or attractive. I think sympathetic is another of those false friends :) 'as From bokr at oz.net Wed Dec 31 18:57:12 2003 From: bokr at oz.net (Bengt Richter) Date: 31 Dec 2003 23:57:12 GMT Subject: Test if IDLE is a mature program References: Message-ID: On Wed, 31 Dec 2003 11:46:25 -0800 (PST), Rob Boyd wrote: >--- Aubrey Hutchison wrote: >> Why do I need to tinker with it? >> >> You don't need to tinker with mature programs. >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > >I have _never_ had to tinker with IDLE in order to use >it. Please read the Python tutorial, 6.1.1, the Module >Search Path, before making uninformed assertions. Your >experience has nothing to do with IDLE or really even >Python. You wouldn't get far in C development if you >wrote a garbage file named stdio.h and saved it within >the library search path. OTOH, you don't expect #include or #include to do the same as #include "stdio.h" Regards, Bengt Richter