From aahz at pythoncraft.com Wed Feb 4 14:57:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 Feb 2004 14:57:59 -0500 Subject: counting references to an instance References: Message-ID: In article , Brian wrote: > >Is it possible to get an object to return the number of references there >are to itself? > >Ex: > >class test(object): > pass > >a = test() >b = a > ># Should print "2", if I knew the name of the method. >print a.refCount() sys.getrefcount(a) will do the trick -- but it will print 3. Can you figure out why? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From ketulp_baroda at yahoo.com Thu Feb 12 09:27:00 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 12 Feb 2004 06:27:00 -0800 Subject: does python support mvc architecture Message-ID: Hi Does python support MVC architecture? Java has register & notify obsever methods in javax.util . Does python has these functions. If not then how to register the views with the models & how to notify the views that the model has been updated?? From jcarlson at nospam.uci.edu Wed Feb 18 19:42:39 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 18 Feb 2004 16:42:39 -0800 Subject: Is there Multi-media support in Python ? In-Reply-To: <73NYb.10391$jH.32000@twister.tampabay.rr.com> References: <73NYb.10391$jH.32000@twister.tampabay.rr.com> Message-ID: > One of the reasons we were interested in Python is that, we thought, capible > of creating software that will run on Mac, Windows or Linux systems. > > I understand that Python itself is the basic language and that there are > add-ons for other stuff... like win32all, wxPython, Py2exe, NumArray, > PythonCard, etc... You will find that Python will interface with quite a few Windows components with win32all (now pywin32 I believe), of course there is already os.startfile() for simple "open this file with the appropriate viewer" applications. Depending on the 'multimedia' you want to deal with, wxPython is capable of embedding various objects into itself. On Windows it seems to be fairly trivial to embed Internet Explorer in a wxPython window, which could be used with the standard IE plugins to view media. On other platforms, perhaps wxMozilla (http://wxmozilla.sourceforge.net/) would satisfy a large portion of your requirements. It may take some work to get it working with wxPython, but it also may be a quick SWIG run. As it stands, wxMozilla runs on all major platforms, so may be your best bet for images and multimedia with browser plugins. - Josiah From tjreedy at udel.edu Tue Feb 24 17:29:07 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Feb 2004 17:29:07 -0500 Subject: Thoughts about Python References: <403B4963.4060303@compuserve.de> <15c2d03b.0402241333.5f7a2738@posting.google.com> Message-ID: "Marco Aschwanden" wrote > How many "object oriented" languages do you know ... Python is object-based and allows its flavor of object-oriented programming, but it is not restrictively objected-oriented way that Java and some other languages are. One can write Python programs, even fairly large programs, with modules, statements, and functions, without ever using the class statement. > Obviously my "ideas/thoughts" are MY "personal problem" with Python as > I understand the comments so far and I must first learn more Python > before I can state things that disturbed me while learning... It is one thing to ask questions, another to express opinions, and a third to dogmatically present opinions and preferences as facts and shoulds. Perhaps you did more of the third than you intended. Terry J. Reedy From rmunn at pobox.com Fri Feb 6 13:10:57 2004 From: rmunn at pobox.com (Robin Munn) Date: Fri, 06 Feb 2004 18:10:57 GMT Subject: How can this be? References: <4eBUb.15701$uM2.7740@newsread1.news.pas.earthlink.net> Message-ID: r.e.s. wrote: > "Paul Prescod" wrote ... > >> You sent a reference to L into the function. The function probably >> mutated it. If you wish the function to work with a copy, try this: >> >> from A import * >> L = [0] >> print L >> x = f(L[:], 'a data string') >> print L >> >> This is normal and often useful behaviour. > > I can see that it would be -- Thanks for answering > a beginner's question. I notice also the following: > > def f(L): > L[0] = 1 > > def g(L): > L = [1] > > L1 = [0], L2 = [0] > > f(L1), g(L2) > > ... L1 gets mutated, but not L2 (even though both > references were passed). It's probably explained > in the tutorial -- which I'm now going to re-read. Fredrik Lundh's short article on Python objects (which starts with the helpful advice "Reset your brain") is also useful as a starting point: http://effbot.org/zone/python-objects.htm -- Robin Munn rmunn at pobox.com From cookedm+news at physics.mcmaster.ca Tue Feb 24 17:52:10 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 24 Feb 2004 17:52:10 -0500 Subject: Thoughts about Python References: <15c2d03b.0402240311.395f5382@posting.google.com> <15c2d03b.0402241237.708cb4e8@posting.google.com> Message-ID: At some point, PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) wrote: >> Forget the speed and memory difference. The main argument for tuples as a >> separate type are to use as dictionary keys. How do you propose to handle >> dictionary keys without tuples? > > Maybe I don't get the point here: Why do dictionaries need tuples to > work? I know that tuples can be used as keys... but how many times do > you need tuples as dictionary keys (it would be simple to turn a list > into an immutable string if really needed ("::".join(["a","b"]). Simple, yes. Practicable, no. Wrong, certainly. For instance, I have a lot of use cases where I use tuples of numbers -- (3, 4, 20.0101), eg. It'd be a *hack* to convert that into a string, and the representation would not be unique. This ain't Perl. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From sdb1031 at yahoo.com Thu Feb 5 21:43:42 2004 From: sdb1031 at yahoo.com (Stephen Briley) Date: Thu, 5 Feb 2004 18:43:42 -0800 (PST) Subject: "datatype mismatch error" in MS Access Message-ID: <20040206024342.57431.qmail@web60904.mail.yahoo.com> For some reason, my posts are scrubbed as attachments. Lets hope that sending from the yahoo account works. I'm new to Python and I'm trying to do some database work with MS Access, but I can't seem to get around a "datatype mismatch error". Here's an example table that I'm working with... ID name dept 1 steve acct 2 mike acct 3 george payroll 4 frank payroll >>> import win32com.client >>> engine = win32com.client.Dispatch("DAO.DBEngine.36") >>> db = engine.OpenDatabase(r"c:\python-access\db4.mdb") >>> rs3 = db.OpenRecordset("work") >>>rs3 = db.OpenRecordset("select * from work where ID = 3 ") >>>dept = rs3.Fields("dept") >>>print dept payroll The above does exactly what I want, except I'd like to use a variable instead of the number 3. When I try I get the following... >>>idnum = 3 >>>rs3 = db.OpenRecordset("select * from work where ID = '%i'" %(idnum)) Traceback (most recent call last): File "", line 1, in ? File "win32com\gen_py\00025E01-0000-0000-C000-000000000046x0x5x0.py", line 508, in OpenRecordset ret = self._oleobj_.InvokeTypes(1610809383, LCID, 1, (9, 0), ((8, 1), (12, 17), (12, 17), (12, 17)),Name, Type, Options, LockEdit)com_error: (-2147352567, 'Exception occurred.', (0, 'DAO.Database', 'Data type mismatch in criteria expression.', 'jeterr40.chm', 5003464, -2146824824), None) The data type for the ID field in the table is "number" so why am I recieving the datatype mismatch error? I'd really appreciate some help, if anyone has any suggestions. Thanks! __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From mark at diversiform.com Fri Feb 20 15:27:58 2004 From: mark at diversiform.com (mark) Date: Fri, 20 Feb 2004 12:27:58 -0800 Subject: mcmillan installer web site In-Reply-To: Message-ID: <107730889101@neptune.hosting4u.net> Here's Gordon's mail from the Installer mail list: My host was acquired & the transition wasn't managed very well. Should be back pretty soon. -- Gordon - 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 bap Sent: Friday, February 20, 2004 11:41 AM To: python-list at python.org Subject: mcmillan installer web site Is anyone else having problems accessing the Mcmillan installer web site (www.mcmillan-inc.com)? I get a no permission error message - so I don't know if my ISP is blocked or something is wrong with the web site. Bruce Peterson -- http://mail.python.org/mailman/listinfo/python-list From mwh at python.net Thu Feb 5 11:55:22 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 5 Feb 2004 16:55:22 GMT Subject: integer overflow References: <_LKdnSsPRbRZ77_dRVn_vQ@news.rockefeller.edu> Message-ID: Chad Haynes writes: > Michael Hudson wrote: > > > Chad Haynes writes: > > > >>I got an odd error which I cannot explain and cannot seem to reproduce. > >>The following statement > >> > >> lst[0] = num > >> > >>produced this error > >> > >> OverflowError: unsigned short is greater than maximum > >> > >>The number was around 65536 so it makes sense that it would overflow a > >>short, but why is it trying to force it into a short integer? > > Is lst an array.array('h') or something (numarray...)? > > Nope, its just a regular list Code, please. Cheers, mwh -- The snakes are optional, as are the electrodes, the molten lead and the ritual buggering by syphilitic warthogs. -- Tanuki the Raccoon-dog, asr From whitedw at NOSPAMcox.net Sun Feb 22 02:28:19 2004 From: whitedw at NOSPAMcox.net (Derek W) Date: Sat, 21 Feb 2004 23:28:19 -0800 Subject: Python program organization In-Reply-To: References: <6fGZb.25259$tM5.21166@fed1read04> Message-ID: <40385A13.6090904@NOSPAMcox.net> Fran?ois Pinard wrote: > [Derek W] > > >>Is it proper to break the program up into modules and put all of the >>modules in a package even if the modules would be of little or no use >>to others (such as the program specific GUI code)? > > > Hi, Derek. It looks proper to me. You might want to break a big > package into sub-packages, but all of it usually goes into a single > directory hierarchy. > > >>Would this package then go under Python's site-packages directory when >>the program is installed? > > > This is the most natural thing to do. > > >>Would distribution of a program like this use distutils? > > > Why not? :-) > Fran?ois, Thank you for replying to my post. I very much appreciate your input. Great homepage by the way. Thanks again, Derek From __peter__ at web.de Sun Feb 22 03:02:14 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Feb 2004 09:02:14 +0100 Subject: list partition References: Message-ID: Moosebumps wrote: > Is there a function that takes a list and predicate, and returns two > lists -- one for which the predicate is true and one for which it is > false? I take a slightly different approach, which is not limited to boolean predicates: >>> def predicate(v): return v & 1 ... >>> d = {} >>> for i in range(10): ... d.setdefault(predicate(i), []).append(i) ... >>> d[True] [1, 3, 5, 7, 9] >>> d[False] [0, 2, 4, 6, 8] >>> Peter From rhaper at houston.rr.com Mon Feb 16 23:15:02 2004 From: rhaper at houston.rr.com (Rod Haper) Date: Tue, 17 Feb 2004 04:15:02 GMT Subject: Simple addition In-Reply-To: References: <4AQXb.25652$646.5355@newssvr25.news.prodigy.com> <3OadnQovPKs4nqzdRVn-hQ@comcast.com> Message-ID: Rainer Deyke wrote: > Dan Bishop wrote: > >>Why not display the *exact* decimal representation, >>"0.1000000000000000055511151231257827021181583404541015625"? > > > This has my vote. Unfortunately Python seems incapable of figuring out all > of those digits. > > Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>'%.64f' % 0.1 > > '0.1000000000000000100000000000000000000000000000000000000000000000' > > Python 2.3.3 seems to be able to do it on Red Hat Linux 9.0: [rodh at rodh rodh]$ python Python 2.3.3 (#1, Dec 20 2003, 17:47:13) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> '%.64f' % 0.1 '0.1000000000000000055511151231257827021181583404541015625000000000' >>> Must be a M$ MSC problem. -- Rod From vivek_sawant at killspam.unc.edu Wed Feb 18 17:05:13 2004 From: vivek_sawant at killspam.unc.edu (Vivek Sawant) Date: Wed, 18 Feb 2004 17:05:13 -0500 Subject: Accessing method object from within a method In-Reply-To: <4033D7ED.D3F7754F@engcorp.com> References: <4033d11a$1_2@news.unc.edu> <4033D7ED.D3F7754F@engcorp.com> Message-ID: <4033e199$1_3@news.unc.edu> Peter, I had browsed through documentation for frame objects earlier, but nothing had jumped out. Here's what your suggestion helped me conjur up and it worked: def method (self, ...) mname = sys._getframe(0).f_code.co_name; # do something with mname Is this what you had in mind or did you mean to suggest something better? Thanks! \vivek Peter Hansen wrote: >Vivek Sawant wrote: > > >>Is there a way to obtain the method/function object from within the >>method like 'self' refers to the object instance. I would like to avoid >>looking method name (string) in class/object attributes. My goal is to >>write code that need not be changed when the method name is changed. >> >>def method (self, ...) >> # somehow obtain 'methodobj' for this 'method' >> mname = methodobj.__name__; >> # do something with mname >> >> > >The usual use for this is for debugging purposes, when somebody wants >to print the name of the current method. If your needs are not much >different than that, look into sys._getframe() and frame objects. > >-Peter > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Wed Feb 18 19:26:29 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 19 Feb 2004 11:26:29 +1100 Subject: Garbage Collection Method Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01377C59@au3010avexu1.global.avaya.com> > From: JAVIER ALBERTO MONTOYA TORRES > > Someone else know whats the way Python collect Garbage, by > unreferenced locations in memory, usings flags, maybe hybrid > of two or > more methods, ... Can help me? http://www.python.org/doc/faq/general.html#id43 http://www.catb.org/~esr/faqs/smart-questions.html#before Tim Delaney From sean at datamage.net Sun Feb 8 17:12:52 2004 From: sean at datamage.net (Sean Legassick) Date: Mon, 9 Feb 2004 00:12:52 +0200 Subject: OT: Recommended news reader? References: <4f0a9fdb.0402031309.fde7220@posting.google.com> Message-ID: In message , Thomas Heller writes >But I was very astonished to see that no other mail/news client I have >examined allows customizing the From: address depending on the folder or >group you are currently in. Can that really be true? Turnpike does . It costs about UKP15 and there's no eval version, which is terrible marketing on Demon's behalf. It's a wonderful email and news client with all kinds of great features (ok, I was responsible for redesigning the UI during my time at Demon so I'm somewhat biased...) -- Sean Legassick sean at datamage.net From theller at python.net Tue Feb 24 10:49:02 2004 From: theller at python.net (Thomas Heller) Date: Tue, 24 Feb 2004 16:49:02 +0100 Subject: Distutils: compilation of generated code. References: Message-ID: <65dw5vgx.fsf@python.net> Jacek Generowicz writes: > I am using a Python program to generate the C++ source code of an > extension module in a package which is managed by distutils. What's > the best way to instruct distutils to re-generate the code before > compiling it, if and only if the generation program is newer than the > generated code ? subclass distutils build_ext command. Thomas From wweston at att.net Thu Feb 26 13:52:57 2004 From: wweston at att.net (wes weston) Date: Thu, 26 Feb 2004 18:52:57 GMT Subject: configure 'time out' time for urllib In-Reply-To: <403DD771.F58FBF24@molgen.mpg.de> References: <403DD771.F58FBF24@molgen.mpg.de> Message-ID: Andreas, Follow the link in Pieter's reply. It explains that the method changes the timeout for ALL connections. You won't need to recode in sockets. Thanks Pieter. wes Andreas Dahl wrote: > Hi, > > I use urllib to retrieve data via HTTP. Unfortunately my program crashes > after a while (after some loops) because the connection timed out. > > raise socket.error, msg > IOError: [Errno socket error] (60, 'Connection timed out') > > I am not so familiar with python, but is there a possibility to > configure the 'waiting time'? Or how can I handle such an event? To skip > that query and go to the next one would also work. > > Many thanks in advance, Andreas > > code: > params = urllib.urlencode({'rs': rs}) > try: > file = > urllib.urlopen("http://www.ncbi.nlm.nih.gov/SNP/snp_ref.cgi?%s" % > params) > except IOError, message: # file open failed > print >> sys.stderr, "File could not be opend:", message > sys.exit(1) > data = file.readlines() # array with html-doc-content > file.close() > From martin at v.loewis.de Tue Feb 3 13:30:38 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 03 Feb 2004 19:30:38 +0100 Subject: internationalisation/gettext - any sample (.MO) data available ? In-Reply-To: <282f826a.0402021907.2266c6b4@posting.google.com> References: <282f826a.0402021907.2266c6b4@posting.google.com> Message-ID: Richard Shea wrote: > As a first step I'm looking at the class based gettext. I just > wondered if anyone knew of some ready made .MO files I could use - I > don't care what the subject matter is I just want something realistic > to work with (I have tried googling but a search string with 'sample' > and 'file' pulls up an awful lot of unrelated stuff). Here is the smallest example I can think of (actually, the smallest one using Tk - one with pure text output could be smaller): # Python import gettext gettext.install("demoapp", localedir=".", unicode=True) import Tkinter t=Tkinter.Label(text=_("Hello, World")) t.pack() b=Tkinter.Button(text=_("Close"), command=t.tk.quit) b.pack() t.tk.mainloop() Save this as a.py, and invoke # Shell Command Line xgettext a.py (use xgettext.py if you don't have xgettext) This produces a file messages.po. Change this to read # demoapp message file # msgid "" msgstr "" "Project-Id-Version: demoapp\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2004-01-25 21:50+0100\n" "PO-Revision-Date: 2004-01-25 21:52+0100\n" "Last-Translator: Martin v. L?wis \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=iso-8859-1\n" "Content-Transfer-Encoding: 8bit\n" #: a.py:5 msgid "Hello, World" msgstr "Hallo, Welt" #: a.py:7 msgid "Close" msgstr "Ende" and invoke # Shell Command Line msgfmt messages.po (use msgfmt.py if you don't have msgfmt) Save the resulting messages.mo as ./de/LC_MESSAGES/demoapp.mo Set the LANG environment variable to de_DE.ISO-8859-1, and invoke # Shell Command Line python a.py and enjoy the German user interface :-) If you have multiple languages, hand messages.po to translators (calling it demoapp.po), and compile each translation you get back from the translators. Regards, Martin From chrish at cryptocard.com Mon Feb 16 08:16:30 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Mon, 16 Feb 2004 08:16:30 -0500 Subject: package similar to XML::Simple In-Reply-To: References: Message-ID: Paulo Pinto wrote: > does anyone know of a Python package that > is able to load XML like the XML::Simple > Perl package does? Despite all of the, uh, _discussion_ in this thread, I'd like to thank you folks for pointing out pyRXP... I hadn't found that before, and if I can whip up a pyRXP -> DOM2 translator, it will fit my needs _perfectly_. Thanks! -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. From kmeling at vizrt.com Fri Feb 6 04:59:57 2004 From: kmeling at vizrt.com (Kathy) Date: 6 Feb 2004 01:59:57 -0800 Subject: Create Unicode object problem Message-ID: <8d5080f5.0402060159.39612a86@posting.google.com> Hi! Is there any way I can create a unicode object from the unicode code itself. I extract the code from a file and need to create a unicode object that represents the corresponding character. So what i get from reading my file is a string containing for example the code 'u8c79' (Chinese character). Help on this would be appreciated! Kathy From pod at internode.on.net Tue Feb 3 02:39:39 2004 From: pod at internode.on.net (PoD) Date: Tue, 03 Feb 2004 17:39:39 +1000 Subject: Question about 'if __name__ == "__main__":' References: Message-ID: On Mon, 02 Feb 2004 23:33:42 -0800, Amy G wrote: > I have a program that needs a little help. > Right now the program runs in my crontab. When it runs, it sets a few > variables based on a query to a MySQL database. I would like to modify it > so that it can run as it is... or if arguments are supplied, use those > instead of querrying the database. > Hint: len(sys.argv) From llothar at web.de Wed Feb 18 20:07:39 2004 From: llothar at web.de (Lothar Scholz) Date: 18 Feb 2004 17:07:39 -0800 Subject: Bug in "sys.settrace" ?? Message-ID: <6ee58e07.0402181707.26418b2c@posting.google.com> I use sys.settrace in my console application to stop any endless loop but in the following loop: a = 0 while 1: a = a + 1 the trace function is only called 4 times, but in code a = 0 while 1: a = a + 1 print a the trace function is called infinite times. So i assume that there is a bug in the first case. I think that the system assumes that it must not call the trace function again because it is always the same line number, and the optimizer removes the "while 1" line. From matt.gerrans at hp.com Fri Feb 27 15:03:47 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Fri, 27 Feb 2004 20:03:47 GMT Subject: remove BOM from string read from utf-8 file References: Message-ID: I found myself often needing to read text files that might be utf-8, unicode or ansi, without knowing beforehand which, so I wrote a single function to do it. I don't know if this is the correct way to handle this situation, but I couldn't find any function that would simply open a file with the appropriate codec automatically, so I use this (it doesn't handle all cases, but just the ones I've needed so far): import os, codecs #--------------------------------------------------------------------------- - # OpenTextFile() # # Opens a file correctly whether it is unicode or ansi. If the file # doesn't exist, then the default encoding is unicode (UTF-16). # # Python documentation of the codecs module is pretty weak; for instance # there are all these: # BOM # BOM_BE # BOM_LE # BOM_UTF8 # BOM_UTF16 # BOM_UTF16_BE # BOM_UTF16_LE # BOM_UTF32 # BOM_UTF32_BE # BOM_UTF32_LE # but no explanation of how they map to the encodings like 'utf-16'. Some # can be inferred, but some are not so clear. #--------------------------------------------------------------------------- - def OpenTextFile(filename,mode='r',encoding=None): if os.path.isfile(filename): f = file(filename,'rb') header = f.read(4) # Read just the first four bytes. f.close() # Don't change this to a map, because it is ordered!!! encodings = [ ( codecs.BOM_UTF32, 'utf-32' ), ( codecs.BOM_UTF16, 'utf-16' ), ( codecs.BOM_UTF8, 'utf-8' ) ] for h,e in encodings: if header.find(h) == 0: encoding = e break return codecs.open(filename,mode,encoding) From otto_kruse at hotmail.com Sun Feb 22 11:20:33 2004 From: otto_kruse at hotmail.com (=?ISO-8859-1?Q?Otto_Kr=FCse?=) Date: Sun, 22 Feb 2004 17:20:33 +0100 Subject: limiting text input in Tkinter Entry widget Message-ID: <4038d6c2$0$49821$1b2cd167@news.wanadoo.nl> Hi everyone, I'm building a GUI in which I want, amongst other things, for people to fill in there postal code. The postal codes of my country (Holland) are in this format: 1234 AB So for the input I use two entry widgets, one of a length of (characters) for the numbers and one of lenght 2 for the letters. What I don't like is that although the visible part of the widgets thus are 4 and 2 characters, users can actually input more characters. They could for example input 12345 abcd. I want to make that impossible. Does anyone know a way to limit the amount of characters an entry widget can take? Is there an easy option to set for this or does this problem require some python code? Can't seem to find answers in any documentation. The code: self.e1 = Entry(frame, width="4") self.e2 = Entry(frame, width="2") Thanks a lot, Otto From John at the.computer Fri Feb 6 23:28:09 2004 From: John at the.computer (John Matthews) Date: Sat, 07 Feb 2004 04:28:09 GMT Subject: Beginning programmer question - How to print a list in a different format References: Message-ID: In article , John at the.computer says... > Hi. > > I have a dictionary thus: (wraps) > > p1hand = > {'b12':b12,'d12':d12,'d23':d23,'n12':n12,'n23':n23,'n34':n34,'p12':p12,' > p23':p23,'p34':p34,'p45':p45} > > I set a variable called p1handlist so that I can print a list of the > keys to the screen: > > p1handlist = p1hand.keys() > print p1handlist > > and the output looks like this: > > ['b12', 'd12', 'd23', 'n12', 'n23', 'n34', 'p12', 'p23', 'p34', 'p45'] > > how can I make it so that the output looks more like this?: > > b12, d12, d23, n12, n23, n34, p12, p23, p34, p45 > > This is for a simple text mode game I am writing and the output to the > screen is important because at times the list gets too big to print on > one line of the display. > > Thanks! > > John > > > > Robert & Andres, Thanks so much for the help. As it turns out: >>> print ', '.join(p1handlist) does the trick! You have made me look like a genius! :) John From merkosh at hadiko.de Tue Feb 10 11:24:35 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 10 Feb 2004 17:24:35 +0100 Subject: software design question References: <6ee58e07.0402080823.75df2850@posting.google.com> Message-ID: Lothar Scholz wrote: >> Is 500 lines a good count to start splitting up the code? > No ! > My modules are normally between 1000-3000 lines. Having to much files > (worst case scenario is PHP) is just another form of spaghetti code. > With so small files you should focus on the task that needs to be done > and only if you really do two different things in one module you > should decide to split it. Maybe a merge would help you more then > splitting. What IDE /Editor do you use? I currently use Emacs and I find it very hard to skip back and forth between methods and functions in larger files. Ciao Uwe From ajsiegel at optonline.com Wed Feb 25 20:34:59 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 26 Feb 2004 01:34:59 GMT Subject: No Thoughts about Everything References: Message-ID: <3eca401a1tiu4hoeh3tfeh61gtt42srr1u@4ax.com> On Wed, 25 Feb 2004 19:46:53 +0100, bblochl wrote: >Obviously you assume I try to torture people with that task of "production programming" as you name it. >That is absoluteley not my stile. Exactly prevention was the reason I was looking for a solution in the meagre and > precise form of the word "final" in python as well to hand it as a tool to the people. So to my regret > I recognize now that in python there is a comparable self explaining solution as in JAVA not avalaible and > I have to split off that in many (even simple) applications very helpful and as a programming concept interesting feature. In fairness, it was I who introduced the term "production programming". Dave actually rejected the characterization. > >But I hope you will not be convinced that explaining the meaning and applying the five letters of the JAVA-modifier >"final" is too much for a one year JAVA course for university scientists? > Even after PISA - that is not only an italien city - I can not belief that! I absolutely agree that the java modifier should be taught in a Java class. But probably not in a Python class - for the obvious reason. My experience was that the need to deal with the Java OO modifiers makes the learning experience rote, before its time. The method and class modifiers do become meaningful, but well after one has the core OO concepts under one's belt, by having acutally written some independant Code. But since the modifiers must be there in one form or another - from the beginning - every introduction to the language I have seen makes them a Big Thing, up front. And, therefore, the population of those who get to the point of writing independant Code, is dwindled. Those without a taste for what - at that point - seems like obscure formalism, drop off. Who are probably some of the brighter ones. Python works much better as an introduction to OO programming. IMO, based on my expereince. Art From sdhyok at yahoo.com Fri Feb 20 13:24:32 2004 From: sdhyok at yahoo.com (sdhyok) Date: 20 Feb 2004 10:24:32 -0800 Subject: Class for Time Series Data References: <420ced91.0402191804.49a5d91f@posting.google.com> <3064b51d.0402200801.6e58c34b@posting.google.com> Message-ID: <420ced91.0402201024.5c849393@posting.google.com> Not only for ad-hoc calculations. I am looking for some serious works for time series data, like ts class in R. Daehyok beliavsky at aol.com wrote in message news:<3064b51d.0402200801.6e58c34b at posting.google.com>... > sdhyok at yahoo.com (sdhyok) wrote in message news:<420ced91.0402191804.49a5d91f at posting.google.com>... > > Hi, I am trying to build up a system handling time series data a lot. > > Do you know any well-designed python class specially for time series data? > > Thanks in advance. > > > > Shin, Daehyok > > I use a 1-D Numeric array to store the data of a time series. What is > missing in the Numeric array that you want? It is easy to write Python > functions to compute things like the autocorrelation function or the > coefficients of an autoregressive model, using the features of Numeric > and the accompanying LinearAlgebra module, which can fit regressions > via least squares. From steve at ferg.org Wed Feb 4 12:09:07 2004 From: steve at ferg.org (Stephen Ferg) Date: 4 Feb 2004 09:09:07 -0800 Subject: javadoc for python References: <401f0ace$1_1@newspeer2.tds.net> Message-ID: I too wish there was Javadoc-style documentation for Python. In any event, you might try this: http://www.ferg.org/pyref/index.html From usenet_spam at janc.invalid Sun Feb 29 13:33:24 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 29 Feb 2004 18:33:24 GMT Subject: AES in Python? References: <7x7jy6em8d.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > Some time ago I had a copy of an AES implementation written in pure > Python by Bryan Olson. I seem to have misplaced it. Anyone have a > copy they can post a url for (or post the code)? Or if needed, leave > me a note at . Thanks. AES = Rijndael An implementation in Python: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From maxm at mxm.dk Thu Feb 5 05:54:10 2004 From: maxm at mxm.dk (Max M) Date: Thu, 05 Feb 2004 11:54:10 +0100 Subject: Smarter way of doing this? In-Reply-To: <402216c0$0$135$3a628fcd@reader1.nntp.hccnet.nl> References: <401e4d57$0$295$edfadb0f@dread12.news.tele.dk> <401f53ad$0$287$edfadb0f@dread12.news.tele.dk> <4020eb47$0$271$edfadb0f@dread12.news.tele.dk> <402216c0$0$135$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <402220D2.7050909@mxm.dk> Anton Vredegoor wrote: > Max M wrote: > > >>I solved it by using acumulated probabilities instead. So the final >>version is here, if anybody cares. > > Yes it's fast, but I don't think it's smart :-) Unfortunately I > haven't got a working solution as an alternative, but only some code > that "explains" what I mean: > > > def choice_generator(population,probabilities): > PC = zip(probabilities,population) > while 1: > p,c = max([(p*random(),c) for p,c in PC]) > yield c > > This is short and fast. However, the distribution of the outcomes is > wrong, because the list of probabilities should be "adjusted" so that > in the end the *outcomes* are distributed according to the > "probabilities". Or should that be proportions? I don't understand what you mean. If I calculate the deviations from what is expected, and use a large result set, I get very small deviations. I am interrested in getting a result as a propertion of the probablilty, or more correctly in this case, the frequency. If I want it as probabilities I just have to normalise the sim to 1.0. This has the advantage that the frequencies can be expressed as integers too. This is nice in my Markov chain class that count words in text, etc. In my example below each letter should be occur 50% of the times of the previous letter. Perhaps you mean that it should behave differently? regards Max M ################### probabilities = [16, 8, 4, 2, 1] elements = ['a', 'b', 'c', 'd', 'e'] sample_size = 1000000 s = Selector(probabilities, elements) r = s.get_range(sample_size) r.sort() previous = float(sample_size) for element in elements: count = r.count(element) deviation = (previous/2.0-count) / count * 100 previous = count print element, count, deviation >> a 517046 -3.29680531326 >> b 257439 0.421070622555 >> c 129159 -0.340278261677 >> d 64148 0.672663216312 >> e 32208 -0.416045702931 From g2h5dqi002 at sneakemail.com Wed Feb 11 19:58:38 2004 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 12 Feb 2004 13:58:38 +1300 Subject: calling Pyrex results from C In-Reply-To: References: <20040120172733.GA7666@titan.progiciels-bpi.ca> <20040120234855.GV22782@jowls> Message-ID: <402ACFBE.7030805@sneakemail.com> Kyler Laird wrote: > cdef public char* string(x): > s = str(x) > return(s) Whenever you allow Pyrex to coerce a Python string into a char *, you need to be careful that the Python string will remain alive for as long as the C pointer is needed. In this case, str(x) is probably returning a string with no other references, so it's deallocated as soon as the function finishes, and a dangling pointer is then returned. You'll need to make a copy of the string's contents somehow, e.g. cdef extern from "string.h": char *strcpy(char *) cdef public char* string(x): s = str(x) return strcpy(s) and remember to free() it when you're finished with it. (Warning: Don't try to write it as return strcpy(str(x)) # WRONG or you'll have the same problem -- the string will be deallocated before strcpy() gets a chance to copy it!) Some other comments: * In the C code, it's better to declare pointers to Python objects as PyObject * rather than void *, e.g. PyObject *im, *im_size; since this will give you better type checking from the C compiler. * Your C code as written leaks Python objects, since it never decrefs the objects returned by image_file_open and image_size.It also doesn't do anything about checking for and handling Python exceptions. It's much better if you can do all creation and manipulation of Python objects in Pyrex, since it takes care of refcounting and error checking automatically (although read the doc section on Error Return Values to make sure exceptions are propagated from functions that don't return Python objects). You may want to put something in your main function to catch exceptions and print a traceback, since that won't happen automatically with no Python interpreter at the top level. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From foeclan at yahoo.com Fri Feb 6 11:36:03 2004 From: foeclan at yahoo.com (Mike Vieths) Date: Fri, 06 Feb 2004 10:36:03 -0600 Subject: execv putting quotes around arguments Message-ID: <4023c273$0$41295$a1866201@newsreader.visi.com> I'm running into a problem when I try to run commands with os.execv. It seems to be putting quotation marks around each element of the list passed as its second argument. This is fine for the most part, but if the argument has a space in it, getopt (in the command being called) will read the entire quoted string as the argument and generally fail. Here's an example: Python 2.2.2 (#1, Jan 30 2003, 21:26:22) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> arg0='/bin/ls' >>> arg1='-l foo' >>> args=[arg0]+[arg1] >>> os.execv(arg0, args) /bin/ls: invalid option -- Try `/bin/ls --help' for more information. This can be worked around by breaking '-l foo' into two seperate elements ('-l' and 'foo'), but that's not always intuitive. Anyone know why those quotes are there, and if there's a way to make them go away? I'm stuck with execv, since this is part of a larger project for which I'm creating a module, and modifying that portion to use os.popen, os.system, or something similar isn't an option. Mike Vieths From __peter__ at web.de Sat Feb 14 07:23:54 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Feb 2004 13:23:54 +0100 Subject: Namespace issues... References: Message-ID: cghost wrote: > i am very confused...why does the following script modify the global list > "l": > > l=[] > > def x(): > l.append("xyz") > > x() > print l > > but the same script applied to a single variable doesnt..: > > l="moe" > > def x(): > l+="howdy" > > x() > print l It's even worse: >>> def add(a, b): ... a += b ... Now consider >>> lst = [] >>> add(lst, ["alpha"]) >>> lst ['alpha'] >>> add(lst, ["beta", "gamma"]) >>> lst ['alpha', 'beta', 'gamma'] where add(a, b) appends b to a versus >>> tpl = () >>> add( tpl, ("alpha",)) >>> tpl () where no apparent change takes place. The difference is that list is a mutable type i. e. its instances can be changed anytime, whereas tuples are immutable, i. e. they cannot be changed once they are created. For lists a += b is implemented to append the items in b to a. The binding of a is not changed in the process. For immutable types this is not an option - they cannot be altered. Therefore, for tuples a += b is implemented as a = a + b, i. e. a new tuple containing the elements of both a and b is created and the variable a is bound to the new tuple. In the example the binding takes place inside a function, so you never see the new tuple unless you return it or declare the variable as global as Vincent already pointed out. Strings are immutable too, so >>> s = "abc" >>> add(s, "def") >>> s 'abc' as expected (hopefully). Peter From kent at cpttm.org.mo Mon Feb 16 05:26:44 2004 From: kent at cpttm.org.mo (Kent Tong) Date: 16 Feb 2004 02:26:44 -0800 Subject: Installation problem on Windows 98 Message-ID: Hi all, I've installed Python 2.3 using the Windows installer downloaded from www.python.org. I'm using Win98. The installation process went well without any problem. However, double-clicking the "IDLE (Python GUI)" does nothing. The cursor changes to a hour-glass for about 1 second and then nothing happens. The "Python (command line)" works. Any help? Thanks! From mcfletch at rogers.com Wed Feb 25 15:55:04 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 25 Feb 2004 15:55:04 -0500 Subject: Thoughts about Python In-Reply-To: References: <15c2d03b.0402240311.395f5382@posting.google.com> <15c2d03b.0402241237.708cb4e8@posting.google.com> <15c2d03b.0402250123.151f06db@posting.google.com> Message-ID: <403D0BA8.4070109@rogers.com> Rainer Deyke wrote: >Mike C. Fletcher wrote: > > >>Actually, this is the classic problem of data-escaping. It's >>*possible* to guarantee unique values when encoding as a string, but >>it's a *lot* harder than just doing str( data ). >> >> > >In Python it's one extra line of code. > >from pickle import dumps >dumps(data) > > Sure, even used that to create the examples :) , but it instantiates and invokes a huge class (~500 lines of Python code) built using multiple other dictionaries, each of which would need to be serviced themselves without getting into weird recursion problems. Pickling machinery is *really heavy* (i.e. a lot harder for the computer to do, and a lot more hairy to program) than a few structure lookups to find functions computing hashes and/or equalities and the inclusion of a static sequence type. Peace and lava lamps, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From bart_nessux at hotmail.com Mon Feb 23 20:22:25 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Mon, 23 Feb 2004 20:22:25 -0500 Subject: whitespace within a string Message-ID: Is there a function/module that can be used to throw out extra whitespace that appears within a string? The problem that I have is this: Before any configuration is done to my files, they have lines with tabs in between the words like this: "disable = yes" After configuring the files using the operating system's administration tools, the OS rewrites the files to contain spaces instead of tabs. So now, the file looks like this: "disable = yes" I would like my script to work in either situation. Right now, it only works with spaces, not tabs. Below is the script: def enable_ssh(): # works on 10.3 systems, not 10.2 systems import os os.chdir('/etc/xinetd.d') find = 'disable = yes' replace = 'disable = no' x = file('ssh') data = x.read() x.close() search = str.find(data, find) if search >= 0: data = data.replace(find, replace) outputFile = file('ssh', 'w') outputFile.write(data) outputFile.close() print print "SSH was disabled... service restarted!!!" print else: print print "SSH was enabled... no action taken." print enable_ssh() From gerrit at nl.linux.org Wed Feb 4 13:13:57 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 4 Feb 2004 19:13:57 +0100 Subject: an ingrate newbie complains In-Reply-To: References: Message-ID: <20040204181357.GA5734@nl.linux.org> Batista, Facundo wrote: > Elaine Jackson wrote: > > #- 1) I find the following behavior puzzling and disappointing: > #- > #- >>> X=[(1,1),(2,4),(3,9),(4,16),(5,25)] > #- >>> Y=dict(X) > #- >>> Z=list(Y) > #- >>> Z==X > #- False > #- >>> Z==Y.keys() > #- True > > >>> Y > {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} > >>> Z > [1, 2, 3, 4, 5] > > I should expect that Z is not equal to Y. Well, the complain here is dat list(D) == D.keys(), not D.values(). I share that complain. >>> D {0: 'foo', 1: 'foo', 2: 'foo', 3: 'foo', 4: 'foo'} >>> list(D) [0, 1, 2, 3, 4] Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From richard at logixlab.com Tue Feb 10 23:00:52 2004 From: richard at logixlab.com (Richard Kessler) Date: Wed, 11 Feb 2004 04:00:52 GMT Subject: cPickle and BOA Constructor hanging! Message-ID: I am attempting a GUI using BOA Constructor. I have some simple code to pickle an object, but for some reason when I use cPickle it hangs the system, but pickle works just fine. I do not have a clue why cPickle will not work. The code is myObj = MyObject() myObj.SetSomeProperties f = open("my file name",'w') cPickle.dump(myObj,f) on the cPickle line, all things end, it just goes into the twilight zone...no errors reported to help diagnose. If I replace cPickle with pickle, I am OK. Many thanks in advance if anyone can help me understand the problem. Richard Kessler From newsgroups at jhrothjr.com Tue Feb 3 06:26:08 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 3 Feb 2004 06:26:08 -0500 Subject: unittest and private methods References: <88caaeda.0402022158.3a7923ac@posting.google.com> Message-ID: <101v1cv4kb6tge6@news.supernews.com> "Yin" wrote in message news:88caaeda.0402022158.3a7923ac at posting.google.com... > I am an avid user of unittest and write tests for everything. Every so > often, I write a class that has some private methods that I only want > to be called from within the class. I usually write unittests for > these private methods using the mangled form of the call from a test > script file. It's not very elegant, and I wanted to get some feedback > on how others write unit tests for private methods. > > I suppose that I could just not use private methods, and have them all > be public, but it's a lot cleaner for me to hide all the other > extraneous methods rather than expose them to the public. Technically, the __ syntax that does name mangling is supposed to be for private methods, and the _ syntax is supposed to be for protected methods and attributes. However, I find that the distinction is not worth all that much, and use the single underscore for both. Possibly that's because I don't use subclassing all that much anyway so I don't find 'protected' to be a useful distinction. John Roth > > Thanks, > Yin From donn at drizzle.com Sun Feb 29 00:21:57 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 29 Feb 2004 05:21:57 -0000 Subject: [Tutor] Re: Reading text lines from a socket References: <40412589.40704@venix.com> <2004022821115516807%bob@redivicom> Message-ID: <1078032115.135462@yasure> Quoth Bob Ippolito : | The real solution is just to use a layer of abstraction, like | asyncore/medusa, Twisted, etc. Relying on the fact that your operating | system may or may not allow a socket to act sort of like a file is | really not something you should do, from Python or otherwise. | | socket.makefile is platform specific, at best. Is it? Do you know of a platform where it doesn't work? I won't laugh -- I use Python on BeOS. But there, where in fact sockets can't be treated as files, makefile() works anyway because it makes a Python class instance that's like a file object, but uses recv() and send() instead of the read(2) and write(2) system calls that the file object uses via stdio. I don't use it myself, but because I just don't like the way stdio buffering works with devices like pipes and sockets. Haven't noticed a platform portability problem. Donn Cave, donn at drizzle.com From jcarlson at nospam.uci.edu Thu Feb 5 22:53:12 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 05 Feb 2004 19:53:12 -0800 Subject: where does Python stand? In-Reply-To: References: <6ee58e07.0402051148.25add90e@posting.google.com> Message-ID: > I'm kind of lost... There are too many of these acronyms in the > market.. Need some directions.. Option 1: Purchase a mac. Get a .mac account. Use iPhoto. Option 2: Purchase some books at your local bookstore that explain what each of these technologies do. If the acronyms are over your head, then learning the a language to write the scripts is likely not going to be possible. Prove me wrong. I'd be glad if you were to do option 2 and produce something worthwhile. - Josiah From jcarlson at nospam.uci.edu Fri Feb 13 18:21:56 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 13 Feb 2004 15:21:56 -0800 Subject: 6 Qustions about Python: Does it do GUI? more... In-Reply-To: References: Message-ID: > 1) I really like C/C++ but I hate dealing with memory allocation, python > handles all memory allocation automatically. Included with Python are many > built in data structures, such as list (like a linked list). Internally, it is actually a resizable array. Saves on pointers. - Josiah From akniekko at yahoo.com Tue Feb 3 23:03:38 2004 From: akniekko at yahoo.com (niekko) Date: Tue, 3 Feb 2004 19:03:38 -0900 Subject: newbie with a gui question References: <1020nse8569lr70@corp.supernews.com> <1020q1dq34lt260@corp.supernews.com> Message-ID: <1020rovdi2lve6f@corp.supernews.com> I'll check it out...thank all!! "Josiah Carlson" wrote in message news:bvpqje$82s$2 at news.service.uci.edu... > > That's just it, the course material is "go out and find > > it on the 'net." I've got several books on Python and none of them help > > will building this gui. > > > > Can someone get me started, at least?? > > 1. Go to www.wxpython.org > 2. Download wxPython > 3. Follow the examples given here: > http://wiki.wxpython.org/index.cgi/Getting_20Started#head-bc009992ceb90dddb7eb3db953e25d1792da2cdd > 4. When you get stuck, read the included documentation (wx.chm) and > check out the included wxPython demo (both are included with the base > distribution). > > - Josiah From paul at prescod.net Sat Feb 28 11:44:14 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 28 Feb 2004 08:44:14 -0800 Subject: Functional languages vs. hybrids (was Re: How does Ruby compare to Python?? How good is DESIGN ofRubycompared to Python?) In-Reply-To: References: Message-ID: <4040C55E.9080700@prescod.net> Joe Mason wrote: >... > Down in the depths of the compiler, the simplest way to > implement (C-style) functions is just to total up all the > parameters and local space it will need and lay out a > stack frame. We're talking about Python and the Python compiler generates Python bytecodes, not machine code! > ...hybrid languages like Python and Ruby and Java and C#, then. It's > the combination of first-order functions *and* side effects that kills > you. (I don't know enough Java/C# to know if they have nested functions > and "function pointers" or equivalent - it actually wouldn't surprise me > if Java doesn't.) Python function calling was never even remotely close to machine function calls for a variety of reasons (primarily the fact that we're talking about an interpreter rather than a compiler). You may well be right that Python _would_ pay a cost for nested functions if its function model was not already substantially more complicated, sophisticated and expensive than C's. But there are all sorts of reasons that Python function calls are slow and I frankly think that nested scopes are the least of them: * Python functions use a stack that is different than the C stack (that's why stackless is even possible) * Python functions have complicated calling conventions (varargs, optional args, keyword args) * Python functions are called through a protocol that supports other types of "callables" * Python integers etc. must be unboxed after the function call to do anything useful with them All of these performance-sucking features were in Python long before nested functions. Paul Prescod From merkosh at hadiko.de Thu Feb 5 12:36:27 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 05 Feb 2004 18:36:27 +0100 Subject: convert utf-8 to latin-1? Message-ID: Hi, in a PyQt application I'm writing, the user can select a filename with a FileDialog. Then I would like to open this file. This works fine if there are no "special symbols" in the filename, such as the german umlauts: "???" Currently I convert the returned, of what I'm pretty sure its a utf-8 string object, to a normal string using the str() function. But then my string contains garbage and I cannot find that file on my ext3 fs (which uses latin-1). So my first question is wether you *can* convert it without loosing something and secondly: how? Thanks for any pointers - Ciao Uwe From crescent_au at yahoo.com Fri Feb 6 17:39:12 2004 From: crescent_au at yahoo.com (Ben) Date: 6 Feb 2004 14:39:12 -0800 Subject: where does Python stand? References: <6ee58e07.0402051148.25add90e@posting.google.com> Message-ID: Josiah Carlson wrote in message news:... > > I'm kind of lost... There are too many of these acronyms in the > > market.. Need some directions.. > > Option 1: > Purchase a mac. > Get a .mac account. > Use iPhoto. > No way!! I don't even consider this as an option. I was asking about "technologies" and "writing scripts", NOT about purchasing a machine! > Option 2: > Purchase some books at your local bookstore that explain what each of > these technologies do. > This is very possible.. but I can't afford to buy "some" books, that's why I'm using this post and google ;) Ben From zunbeltz at wm.lc.ehu.es.XXX Thu Feb 5 09:21:17 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 05 Feb 2004 15:21:17 +0100 Subject: global variables in module References: Message-ID: Harald Massa writes: > Zunbeltz, > > > MyApp(wxApp): > > How can i use cf in other modules of the program. Did I need declare cf > > global, or make it a module variable, ... Any hint, please > > is used the following approach: > > 1) defining one module named > I've take another aproach. I've created a module where I define a class derived from ConfigParse. I've take the idea from the source of idle. > ReportGlobals > > loggedInUser="nasenbaer" > workerQueue=Queue.Queue() > > there all varibles which are "konfiguration related" are defined, also > "programm global queues", "error loggers", "database connection pool" > > All these variables are defined as module level variables > (on "indent 0" :))) ) > > 2) in all modules of the programm I use > > import ReportGlobals as gl > > print "You are %s" % (gl.loggedInUser,) > > > HTH > > Harald > > Thanks for your answer Regards, Zunbeltz > > and access the From skatepunk319 at hotmail.com Sun Feb 15 03:30:03 2004 From: skatepunk319 at hotmail.com (Spencer) Date: 15 Feb 2004 00:30:03 -0800 Subject: How to make forums References: <402ed6f8$0$14898$afc38c87@news.optusnet.com.au> Message-ID: Sam wrote in message > The cgi module will be of use to you: > > http://www.python.org/doc/current/lib/module-cgi.html > > On a related topic, how would one implement something equivalent to PHP > 'sessions' using Python to keep track of logged on users etc? Thank you. I will read about that module. I wrote the PHP script a while ago. I think it's been about a year now. I've been using Python for a shorter amount of time. I will make a Python login script. I'll do all of this later today (it's 3:24 AM right now, I am very tired.) Oh yeah, before any of you make a comment like "just use already made code" or "use Zope", don't. That's not the purpose of this project. I want to use my brain, my Python skills, the resources I have, creativity, etc., to make a forum. I want to learn how to solve things myself, and to explore the unknown. Anymore suggestions will be greatly appreciated! Thanks for the ones already made. From jzgoda at gazeta.usun.pl Fri Feb 13 17:50:47 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 13 Feb 2004 22:50:47 +0000 (UTC) Subject: package similar to XML::Simple References: <402931E4.C1E50E92@engcorp.com> <40294322.7AF2C6D7@engcorp.com> <40294D36.B0AEE3C4@engcorp.com> <402A69C2.FC8DABA@engcorp.com> <402D4FF7.944423B7@engcorp.com> Message-ID: Peter Hansen pisze: >> > Classifying a lack of Unicode support in an XML parser as a >> > 'bug' is ridiculous. >> >> Lack of Unicode support in an XML parser makes it unusable for most part >> of humanity. It's much worse than bug, it's a mistake. > > Most of humanity doesn't use XML, so that's silly. Most of humanity doesn't use ASCII. -- Jarek Zgoda http://jpa.berlios.de/ From elainejackson7355 at home.com Fri Feb 13 17:47:19 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 13 Feb 2004 22:47:19 GMT Subject: beeline through tkinter References: Message-ID: "Lonnie Princehouse" wrote in message news:f70e3538.0402131412.6103d116 at posting.google.com... | This isn't quite an answer to your question, but I've got exactly such | a Tkinter chessboard. It's only half-finished (I have a short | attention span for projects!), but it might give you some ideas: | | http://magicpeacefarm.com/lonnie/chessboard.tar.gz This won't unzip for me. I get a message that says "Error reading header after processing 0 entries". From dietrich at zdome.net Sun Feb 1 16:26:12 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 1 Feb 2004 13:26:12 -0800 Subject: advice on programming style: is multiple inheritance bad? In-Reply-To: References: Message-ID: <429D3C48-54FD-11D8-8CFC-0003934ACDEC@zdome.net> Since you asked for advice on programming style ... The argument for single inheritance is that objects should only have one "is a" relationship. Penguin "is a" bird. For multiple inheritance, Penguin "is a" swimmer also. However, to keep everything clear, I would try to make sure each object has only one "is a" inheritance, and all the other inheritances are "does", e.g., Penguin "is a" bird, "does" fly. If an object really does have two "is a" relationships, try to use two objects. For example: class AirlineReservation(Person, SeatOnAirplane): pass This is kinda dumb and obvious, but it shows how multiple "is a" relationships can be total nonsense. There are probably times when multiple "is a" relationships make sense, but most of the time it's just bad program design. It looks like your SuperA is a "does" class... personally, I would name the types of classes differently, but that's up to you. class Bird: def WhoAmI(self): return "bird" # or DoesSwim, CanSwim, whatever... I'd pick one keep it consistent class Swimming: def Swim(self): print "A %s goes SPLASH!" % self.WhoAmI() class Penguin(Bird, Swimming): def WhoAmI(self): return "penguin" I think pure single inheritance without mixins is bad language design. Arguments against multiple inheritance usually involve overlapping superclasses, and every time I have seen it it *has* been bad design... but does anyone have overlapping superclasses that they can't separate? I'm curious. On Feb 1, 2004, at 10:48 AM, Uwe Mayer wrote: > I got a class A2 that needs to inherit from class A1. > A2, as well as some other classes implement a same functionality and in > order to prevent code duplication I'd like to factorize that > (potentially) > duplicate code into a class SuperA from which then A2 and all other > classes > could inherrit. > However, this would cause A2 to have two super classes A1 and SuperA - > which > is possible of course in Python. > > My question is: is that bad programming style? >> From C++ and Java we "learn" that you shouldn't do that. > > Class A is automatically generated from other tools, so I can't solve > the > problem by just letting A1 inherit from SuperA. > > Your opinions? From jcarlson at nospam.uci.edu Tue Feb 10 18:03:42 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 10 Feb 2004 15:03:42 -0800 Subject: help! multi-threading problem on hyperthreading smp linux server In-Reply-To: <2mcWb.9183$Lp.1693@twister.nyc.rr.com> References: <402901C2.00000B.04040@PIGPEN> <2004021012361076434601@k2.sage.att.com> <2mcWb.9183$Lp.1693@twister.nyc.rr.com> Message-ID: > GIL = Global interpreter lock. It shold cause trouble on SMP. As someone > recently mentioned, Jython does not have it, so you have options. Are you sure it is the GIL? I run quite a few threaded applications on my SMP machine, and have had no isses with the GIL killing it...well, except for that one wxPython thing. Maybe the GIL is the cause. - Josiah From bubbarichau at warmmail.com Wed Feb 25 14:58:47 2004 From: bubbarichau at warmmail.com (rich hammett) Date: Wed, 25 Feb 2004 19:58:47 -0000 Subject: Tkinter on RedHat Linux 9.0 References: Message-ID: <103pvjni4vc587e@corp.supernews.com> Sen j?lkeen, kun Perry Mason oli pahoinpidellyt h?nt?, Thomas Korb yll?tti tuomarin todistamalla: > On Sat, 10 May 2003 14:34:05 -0600, Don Donigan wrote: >> >> Can anyone tell me how to install Tkinter on RedHat Linux 9.0? >> I have not need successfull as of yet. Thanks in advance. >> > You have to install the following 4 RPM packages: > 1. python 2. tcl 3. tk 4. tkinter Is there any way to update the python.org webpage for Tkinter? It currently says you never need to download tkinter separately, which has had me chasing my tail here for a few days. rich > Use 'rpm -qi ' to see, which packages are already > installed on your system (e.g.: rpm -qi tkinter). > To install a package, use 'rpm -ihv '. This command > will i.p. tell you, if other packages must be installed first > (e.g. 'itcl' or 'tix' might be necessary). > You will find the RPM 'packagefiles' on your Red Hat 9 CDs, but > it is often easier (and faster) to download them directly from the > Red Hat Network (http://rhn.redhat.com) or from any other good RPM > archive. -- -to reply, it's hot not warm +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ \ Rich Hammett http://home.hiwaay.net/~rhammett / "Better the pride that resides in a citizen of the world; \ than the pride that divides / when a colorful rag is unfurled." From jcarlson at nospam.uci.edu Sat Feb 28 23:11:00 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 28 Feb 2004 20:11:00 -0800 Subject: Python:Email and Header Parsing: Some Help In-Reply-To: References: Message-ID: > HTMLGen won't work, as that generates HTML (hence the name...). To > strip out the HTML tags, probably a regular expression would be > sufficient. Otherwise, have a look at HTMLParser (in the standard library). To strip out html, use sgml: http://flangy.com/dev/python/striphtml.html - Josiah From yuba at cyberback.com Mon Feb 16 13:28:08 2004 From: yuba at cyberback.com (Greg Lindstrom) Date: 16 Feb 2004 10:28:08 -0800 Subject: Python and MS Exchange References: <68fec02e.0402130818.48132268@posting.google.com> Message-ID: <68fec02e.0402161028.2c90010@posting.google.com> Mark (and others), Thanks for your time and attention. Since I expect to eventually want to do all sorts of things with this application, I think it's best to use MAPI (and not simple MAPI). I have the SpamBayes MAPIDriver (and everything else out of the "sandbox") and have stepped through it enough to figure most of it out. When I run "dump_profiles.py", I get the "MS Exchange Settings" (as I expected). When I run the "dump_props.py" it complains that "FalseGetAllItems" is not defined. Humph. When I attempt the "extract_prop.py -p Subject test" it complains about not being able to find a default message store. I have read through a lot of the MSDN Docum From wfolta at netmail.to Tue Feb 17 15:19:26 2004 From: wfolta at netmail.to (Wayne Folta) Date: Tue, 17 Feb 2004 15:19:26 -0500 Subject: PEP-315 ("do" loop) In-Reply-To: <4032385D.6030003@prescod.net> References: <0F705920-60F0-11D8-BE5B-000A959CB2EC@netmail.to> <4032385D.6030003@prescod.net> Message-ID: <95785602-6186-11D8-BE5B-000A959CB2EC@netmail.to> > until x <==> while not x That was one thought that crossed my mind when I first saw an until construct in a language. (Was it PL/I?) So it is a bit of a confusion, but at the same time my spider senses were telling me that surely a language wouldn't reserve a keyword "until" to simply save someone from typing "while not". (Of course, a language like perl might well do this, but that's why we use python, eh?) While it might be easy to confuse how "until" acts, it has the strength that it follows the intuitive loop paradigm we're used to in all other looping constructs that I know of: what loops is inside the loop. Python has "else" extensions to loops that are different from most languages, but even here the "else" part does not loop. PEP-315 creates a different kind of two-part loop where code outside of the "while" is repeatedly executed. That will fool people who are used to the usual one-part loops. You can claim it's actually a "do" loop, but with the condition in the middle of the loop, that doesn't really hold water. At the very least I'd say that you need to choose a word other than "while" to avoid this kind of confusion. For example, "do ... until ..." loop where "until" <==> "while not" so that you know immediately what's going on. Otherwise, when you see a "while", you're never sure what kind of loop it is until you look above it and determine it's not a "do while". > > Nothing about the word "until" implies to me that it delays the loop > test on the first go-round. PEP 315's syntax seems more clear to me. Nothing about "do" implies "do repeatedly". My first guess on what the PEP-315 syntax means, based on python's "while ... else" syntax, would be that the "do" part is executed and then the while loop is executed conditional on the "do" having not been broken out of: the inverse of "while ... else". From miki.tebeka at zoran.com Wed Feb 4 06:37:44 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 4 Feb 2004 03:37:44 -0800 Subject: Reading files with names dynamically changing References: Message-ID: <4f0a9fdb.0402040337.1a60183c@posting.google.com> Hello Satish, > An external solver program is dynamically producing files with different > names 0000001.dat, 0000002.dat, 0000003.dat etc.....at regular intervals. > These files contain all numeric data. Is it possible to read each of these > dynamically in python ?? What do you mean? If you want to find all *.dat file use the `glob' module. > If so, how should my code look like ?? #!/usr/bin/env python from glob import glob from os.path import getmtime files = glob("./*.dat") # Find all files ending with .dat in current directory # Sort by modification time, newest first files.sort(lambda f1, f2: cmp(getmtime(f2), getmtime(f1))) # Do something with the files for file in files: print file HTH. Miki From nospam-deets at web.de Thu Feb 5 06:58:42 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Thu, 05 Feb 2004 12:58:42 +0100 Subject: a strange problem in python multi-thread programming References: Message-ID: > Today,I found a strange problem in python multi-thread programming.When I > used function win32com.client.Dispatch('ADODB.Connection') in primary > thread, it was OK. But when I called it in secondary-thread, it raised a > exception. Then debugging and tracking the code, I found the problem was > from the function pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) in . The parameters are (ADODB.Connection, None, > 21, {00020400-0000-0000-C000-000000000046}). But just as I said above, > this function would be ok in primaray thread mode but not work in the > secondary-thread mode. Since this function is from the dll(in my computer > is python23.dll), I can not see the source code and don't know how to > solve this problem. Anyone can help me? It has been years since I dealed with COM the last time - so I'm sort of on the speculative side here. However I remember that there were different com-server-models your com-objects could support. They dealt with in/out-processes and threading. So might it be that your ADODB.Connection is not supposed to be called in a multi-threaded environment? -- Regards, Diez B. Roggisch From OlafMeding at noSpam.compuserve.com Mon Feb 2 21:48:29 2004 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Mon, 2 Feb 2004 20:48:29 -0600 Subject: javadoc for python Message-ID: <401f0ace$1_1@newspeer2.tds.net> I played a little with happydoc and pydoc and wonder which one I should use. Also, is there a better documentation general available (I am spoiled by javadoc). Lastly, I could not find good documentation for either happydoc or pydoc. Thanks. Olaf From paul at prescod.net Sun Feb 8 14:43:55 2004 From: paul at prescod.net (Paul Prescod) Date: Sun, 08 Feb 2004 11:43:55 -0800 Subject: Had Phyton suggested In-Reply-To: References: <4026488d$0$95048$edfadb0f@dread11.news.tele.dk> Message-ID: <4026917B.8030405@prescod.net> Steve Horsley wrote: >... > > At the risk of making a lot of python fans angry, I would also suggest > that you look at java. This IS a compiled language (although ironically, > the compiled bytecode is interpreted). Python and Java both compile to byte-code. The only difference is that Python does it automatically whereas Java requires you to compile manually. I suggest this for a few reasons: > * You cannot really avoid thinking in an object-oriented way when > writing java. I suspect that python will allow you to develop some very > nasyt habits. I disagree that the opposite of object orientation is "nasty habits." Forcing every problem into an object oriented paradigm is itself a nasty (and ultimately confusing) habit. > * The java tutorial is massive, and has loads of examples. Is it more massive than these: * http://www.ibiblio.org/obp/thinkCSpy/ * http://diveintopython.org/ * http://www.mindview.net/Books/TIPython * http://www.python.org/doc/current/tut/tut.html * http://honors.montana.edu/~jjc/easytut/easytut/ And this one is specifically about game programming: * http://pygame.org/docs/tut/chimp/ChimpLineByLine.html > * I have not seen anything like BlueJ for python. BlueJ is an excellent > beginners IDE with editor, debugger, and a UML-like diagram that shows > how your classes interconnect. I haven't tried BlueJ so I can't compare but I don't think an IDE could make up for Java's flaws as a learning language. "Hello world" in Java is 7 lines compared to 1 in Python. The Python version has just two concepts: printing and strings. The Java version brings in three keywords (class, public, static) a module, an object, a function, two types, etc. > Better, learn a little of both languages. Can't disagree with that. Learn Python. Learn Pygame. Write your game. Then learn Java to have something good to put on your resume. Paul Prescod From steve at ferg.org Fri Feb 27 10:50:39 2004 From: steve at ferg.org (Stephen Ferg) Date: 27 Feb 2004 07:50:39 -0800 Subject: Python: GUI Builder References: Message-ID: Look at: http://www.ferg.org/easygui From peter at engcorp.com Tue Feb 10 11:27:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Feb 2004 11:27:29 -0500 Subject: approach to writing functions References: Message-ID: <40290671.7A5864CA@engcorp.com> Bart Nessux wrote: > > fp0 = os.popen("/sbin/ifconfig en0 inet", "r") > fp1 = os.popen("/usr/bin/uptime", "r") > fp2 = os.popen("/usr/bin/uname -a", "r") > fp3 = os.popen("/usr/bin/wc -l /etc/passwd", "r") > msg = MIMEText("-- IFCONFIG --\n\n" + fp0.read() + "\n-- UPTIME --\n\n" > + fp1.read() + "\n-- UNAME --\n\n" + fp2.read() + "\n-- PASSWD LC > --\n\n" + fp3.read()) > fp0.close() > fp1.close() > fp2.close() > fp3.close() This sequence has duplication, so it could stand some refactoring. Write a routine that executes a command and returns the result, then call it with various commands, something like this: def cmd(c): f = os.popen(c, 'r') try: result = f.read() finally: f.close() return result responses = [cmd(c) for c in ['/sbin/ifconfig en0 inet', '/usr/bin/uptime', '/usr/bin/uname -a', '/usb/bin/wc -l /etc/passwd']] msg = MIMEText('blah %s, blah %s, blah %s, blah %s' % responses) That's only one example of what you could do to simplify/make reusable code. The best thing I know of to decide when to make a function is when you have code that is about to take responsibility for two different things. Your code has responsibility for setting up user info, retrieving command output, execute four commands, generating the mail body from the results, setting up the entire mail message, and sending the mail message. That's six different areas of responsibility (give or take) and there should probably be at least three or four functions in there to handle some of those in a cleaner fashion. Always ask yourself "what is this chunk of code responsible for?" If the answer is more than one thing, consider splitting it up. This is, by the way, effectively the concept of "cohesion", and you would do well to learn about "cohesion" and "coupling". You always strive for low coupling (connections between different things) and high cohesion (responsibility for only closely related things) in code, if you want clean design. -Peter From pekka.niiranen at wlanmail.com Tue Feb 10 02:18:38 2004 From: pekka.niiranen at wlanmail.com (pekka.niiranen) Date: Tue, 10 Feb 2004 07:18:38 GMT Subject: Newbie questions: symbolic links and hashable items Message-ID: Hi everybody, 1) I am accessing HP-UX partition thru Samba mount. My problem is: Using shutil.copy() copies symbolic links because os.path.islink() does not recognize those as links. How can I make Python running in W2K recognize symbolic links from Samba -mount? 2) How can I check whether a value is hashable? The code below works but for going thru set of values it seems bit odd. # x is hashable ? u = {} try: u[x] = '' except TypeError: 3) Can filenames in any operating system, all Unicode objects and all strings be assumed as hashable? I would like to use them as dictionary keys. -pekka- From pantsmetalkid at charter.net Sat Feb 21 00:16:37 2004 From: pantsmetalkid at charter.net (John) Date: Sat, 21 Feb 2004 00:16:37 -0500 Subject: New user needs help Message-ID: <103dqa9m48nj792@corp.supernews.com> I am new to using Python. Everytime I run this program it prints "The lowest common factor is 0", no matter what numbers I use. Can anybody see anything wrong with my program? Thanks in advance. def getnum1(a): a = input("What is the first number?") if a == 0: getnum1(a) def getnum2(b): b = input("What is the second number?") if b == 0: getnum2(b) def euclid(num1, num2, num3, num4): if num1 < num2: num3, num4 = num1, num2 num1, num2 = num4, num3 euclid(num1, num2, num3, num4) elif num2 != 0: num3, num4 = num1, num2 num1 = num4 num2 = num3 % num4 euclid(num1, num2, num3, num4) else: print "The lowest common factor is: ", num1 a = 0 getnum1(a) b = 0 getnum2(b) x, y = 2, 100 euclid(a, b, x, y) From nobody at nowhere.near.org Thu Feb 26 06:05:41 2004 From: nobody at nowhere.near.org (nobody) Date: Thu, 26 Feb 2004 11:05:41 -0000 Subject: Python: GUI Builder References: Message-ID: <403dd304$0$17076$cc9e4d1f@news.dial.pipex.com> You could try BOA Constructor, it is Delphi like. It needs wxPython (wxWindows python binding) installed first. The Google will spit the correct URLs. "Anand K Rayudu" wrote in message news:mailman.144.1077773598.8594.python-list at python.org... > Hi All, > > I am new to python & want to build some GUI dialogs. > Can some one please suggest some document reference. > > I am hoping that standard python install will have some GUI development > modules & GUI builder in built. > I have python 2.3.3. > > Can some one please suggest > > Thanks in advance. > > > Anand > > > > > From dippy at mikka.net.au Sun Feb 8 00:02:14 2004 From: dippy at mikka.net.au (Steven) Date: Sun, 08 Feb 2004 05:02:14 GMT Subject: passing what a function returns to another function References: Message-ID: On Sun, 08 Feb 2004 11:06:00 +1100, Bart Nessux wrote: > I have 2 functions among others. One gets a URL and returns its, For > example, it returns 'http://127.0.0.1' How can I pass this to another > function? I've never worked with code that has lots of functions before. Either store the function result in an intermediate variable, or just call the second function directly on the result of the first: # method 1: using an intermediate variable my_url = receive_target() receive_commands(my_url) # method 2: call one function directly on the result of the other receive_command(receive_target()) Please note, the way you have written these two functions, I don't believe either method will work. In particular, receive_commands() doesn't take any arguments, so you have no way to pass it an argument :-) Also, receive_target appears to be using a lot of global variables, which is probably not a good idea. If you have to use globals, it is recommended that you declare them that way first, even if you don't strictly need to. I would try something like this: # WARNING: untested code, almost certainly won't work def receive_targets_url(I): # This receives the DDOS target's URL... # Input: socket I # Output: string URL # I hope DDOS doesn't stand for Distributed Denial of Service global DDOS_ZOMBIE_IP, U_PORT # by convention, constants are in ALL UPPERCASE I.bind((DDOS_ZOMBIE_IP, U_PORT)) I.listen(5) conn, addr = I.accept() ddos_target = conn.recv(1024) conn.close() return ddos_target def receive_commands(url): # This receives commands ... # Input: url is a string containing the URL to use # Output: none for i in xrange(999999999): # hmmm, this looks like a Denial of Service attack to me... # haven't you got something better to do with your time, # like maybe writing a natural language parser or something # useful and challenging? f = urlopen(url) -- Steven D'Aprano From grahamd at dscpl.com.au Tue Feb 10 19:42:57 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 10 Feb 2004 16:42:57 -0800 Subject: synchronized method References: <40290916.ECCDE661@engcorp.com> Message-ID: Peter Hansen wrote in message news:<40290916.ECCDE661 at engcorp.com>... > > Under normal execution the lock will not be released because you return > > from the try clause. There is also the case that method isn't defined. > > If that were true, the finally clause would be pretty useless in many > cases. (Try it out yourself: it will work properly.) > > Also, isn't "method" defined as the argument to the synchronized() > function at the top? Hmmm, I stand corrected on both counts. It was one of the days I should have kept my mouth shut. Too stinking hot here at the moment, my brain isn't working. :-) From bblochl2 at compuserve.de Mon Feb 23 07:29:22 2004 From: bblochl2 at compuserve.de (bblochl) Date: Mon, 23 Feb 2004 13:29:22 +0100 Subject: Typecasting Message-ID: <4039F222.70708@compuserve.de> Hi Everybody, Can you guide me to convert string into Int datatype? (i.e. How can we convert string into int? like '555' into 555) Thanks in advance. ~Rajesh One possible answer: Simply use int(). For insdtance: >>> x="555" >>> x '555' >>> x=int(x) >>> x 555 Or an application to convert a string input: >>> x=int(raw_input("Type a number: ")) >>> x 555 From ods at strana.ru Thu Feb 19 04:45:28 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 19 Feb 2004 12:45:28 +0300 (MSK) Subject: codecs limitation In-Reply-To: Message-ID: On Wed, 18 Feb 2004, A.M. Kuchling wrote: AK> > I have the same question as stated in comments: should we AK> really AK> > enforce this and forget the idea to define some AK> specialized AK> > encodings like 'html'? AK> AK> I suppose it depends on what the codecs system is *for*. If AK> it's an AK> interface that goes between between the abstract world of AK> Unicode code AK> points and the concrete world of 8-bit characters that AK> represent those code AK> points, then the idea of returning anything but an 8-bit AK> string from AK> .encode() doesn't make sense. If codecs are for arbitrary This restrition doesn't apply to decode, so we already have codecs like 'base64', 'quoted-printable', 'uu', 'zlib'. In case of 'html' encoding we should be able to apply it to unicode too, in this case the result must be unicode. I can't see why this restriction is partially applied and allows str<->str cobversion, but forbidds unicode<->unicode? Certainly, both 'base64' et al. and 'html' can be implemented as standalone functions. AK> string-to-string AK> transformations, then the restriction should be relaxed. -- Denis S. Otkidach http://www.python.ru/ [ru] From rawbobb at hotmail.com Sat Feb 28 22:56:31 2004 From: rawbobb at hotmail.com (bobb) Date: Sun, 29 Feb 2004 03:56:31 GMT Subject: MySQLDB - generating "...not in (1,2,3)" from Python list ? References: <282f826a.0402230152.253315ca@posting.google.com> <282f826a.0402260128.4400d7d9@posting.google.com> Message-ID: "Richard Shea" wrote in message news:282f826a.0402260128.4400d7d9 at posting.google.com... > Hi - I'm sorry I haven't responded before I got a cold earlier this > week and it's kind of knocked me sideways. Reading the replies I > realised I had done something fundamentally wrong and I was able to > use them as a basis for getting it to work correctly so thanks very > much to all of you for your help. > > There is one thing about the whole business which I find a bit > difficult - it would be nice if after you have executed the query you > were able to actually view the query (with substituted parameters) as > a string to ensure that your query was what it thought it was. I > understand that mySQLdb is really a wrapper around the C API for > MySQL. I've taken a look at that and I can't find anything like what > I'm describing but if any of you guys do know of such a feature it > would be useful in future to know - one of the reaons I was having > problems this time was fully appreciating just what the query was I > was submitting. > Like this? print "delete from " + str(t) + " where " + str(col) + " = " +str(num) + ";" delete from table where id = 1; ??? > I should just say before you think I'm nuts that the 'real' query was > a good deal more complex (and had more substituted parameters) than > the simple one which I created to ask the question I did. > > Anyway thanks again for all your help. > > regards > > richard shea. From usenet_spam at janc.invalid Fri Feb 6 08:10:42 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 06 Feb 2004 13:10:42 GMT Subject: OT: Recommended news reader? References: <4f0a9fdb.0402031309.fde7220@posting.google.com> Message-ID: Thomas Heller schreef: > JanC writes: > >> Thomas Heller schreef: >> >>> But I was very astonished to see that no other mail/news client I >>> have examined allows customizing the From: address depending on the >>> folder or group you are currently in. Can that really be true? >> >> You never looked at Xnews ? :-) > > No, I need imap as well as nntp. Why not use a dedicated client for each? BTW: you can read IMAP & POP3 mailboxes with Xnews + Hamster AFAIK. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter.maas at mplusr.de Tue Feb 17 13:29:40 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 17 Feb 2004 19:29:40 +0100 Subject: Viewing Directories as tree In-Reply-To: References: <402ED475.6030601@prescod.net> Message-ID: Jalil Feghhi wrote: > > I am looking for some python code that I can plug-into my web > application to display file system heirarchies > using a tree structure. I have seem some libraries that do this but > only as a standalone application. > > Is there anything that can be used in a browser? The following recipe displays a directory tree in ASCII. I suppose it can be easily modified for HTML. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/217212 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 jcarlson at nospam.uci.edu Wed Feb 4 16:31:32 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 04 Feb 2004 13:31:32 -0800 Subject: Newbie -- bitwise shifts In-Reply-To: References: Message-ID: gbblob wrote: > Can someone please explain to me why left shits are equivalent to > multiplication and right shifts equivalent to devision? This seems > backwards to me. > > e.g. > > 15 is binary 1111 > if I shift this left 2 bits I get 11 > > however in Python 15<<2 = 60 ?! In computer science, shifting a number 'k' bits to the left, is the same as adding 'k' zeroes to the right side. Shifting a number 'j' bits to the right, is the same as removing 'j' digits from the right side. 15<<2 == 15 * 2**2 15>>2 == 15 // 2**2 This has been the way of things since at least the 1950's. - Josiah From tismer at stackless.com Tue Feb 24 22:07:05 2004 From: tismer at stackless.com (Christian Tismer) Date: Wed, 25 Feb 2004 04:07:05 +0100 Subject: xmlprclib/server not reusing connections In-Reply-To: <007601c3fb46$f917b9b0$3501a8c0@rogersqyvr14d3> References: <403BF010.2020409@stackless.com> <007601c3fb46$f917b9b0$3501a8c0@rogersqyvr14d3> Message-ID: <403C1159.8090806@stackless.com> Roger Binns wrote: >>This is why I developed Stackless Python. >>It behaves in a similar way, acting like many callbacks, >>but you *write* your code in the most natural way possible. >>In a way, Stackless takes all the clumsy state keeping stuff >>away from the programmer and frees his mind to write simple >>top-down programs with no callbacks. > > I certainly agree with that and really like your examples. > > However my code also has to use wxPython, win32all, pySerial, M2Crypto > and libusb. I have no idea if all those are integrated correctly with > Stackless (and work correctly on Linux, Windows and Mac), but I was > certainly not going to be the first person to find out. And I would > still have to have fixed xmlrpc client/server portions to reuse > connections properly anyway. Sure. Some of my experience: (yes, I'm using Stackless since a year now :-) It works just *great* with wxPython. There are a few objects which need a little care since they only live on the C stack (mouse events for instance), but all in all it is wonderful to use wxPython + Stackless (+ Boa Constructor + PIL + ...). I have multiple dynamic widgets with animated graphical content in my GUI, it is all running in a single thread, and all my tasklets can update the GUI at any time, since it is a single thread... Let me know if you need sample code. Like a mouse handler, written like a single, main program. No callbacks... 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 markus_wankusGETRIDOFALLCAPS at hotmail.com Sun Feb 29 16:12:36 2004 From: markus_wankusGETRIDOFALLCAPS at hotmail.com (Markus Wankus) Date: Sun, 29 Feb 2004 16:12:36 -0500 Subject: Limitations of 30 Day Eval? In-Reply-To: References: Message-ID: <7Bs0c.1389$i_2.12581@news20.bellglobal.com> Jarek Zgoda wrote: > Markus Wankus pisze: > > >>Dumbass...sorry - wrong newsgroup. Damn this new newsreader! > > > Use slrn. With ^C you could cancel this message. > I just started using Thunderbird...and it has a cancel feature too. Whaddya know? ;o) Markus. From teiffel at attglobal.net Fri Feb 27 16:12:13 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Fri, 27 Feb 2004 16:12:13 -0500 Subject: comp.lang.python In-Reply-To: References: <403FA011.3030600@attglobal.net> Message-ID: <403FB2AD.3060005@attglobal.net> Terry Reedy wrote: >"Marcello Pietrobon" wrote in message >news:403FA011.3030600 at attglobal.net... > > >>Is the server comp.lang.python working or not ? >> >>If yes, >>what settings do I need in order to see this mailing list in newsgroup >>form ? >> >> > >I am not sure what you are asking. The c.l.p newsgroup should be carried >on any general-purpose news server. The mailing list version is also gated >to newsgroup form (along with numerous otherwise non-newsgroup lists) at >news.gmane.org (access is free). > >Terry J. Reedy > > > > > > I use Mozilla 1.6 and from the link to comp.lang.python that you can see in http://www.python.org/community/lists.html I am not able to subscribe to the Newsgroup while I am able to do it for any other. I cannot do it even manually Maybe I don't have the right informations Cheers, Marcello From __peter__ at web.de Wed Feb 18 08:12:12 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Feb 2004 14:12:12 +0100 Subject: hmm, lets call it: generic __init__ problem References: Message-ID: paul k?lle wrote: > To be honest, it is a "real world" (if there is any) task. The funClass > thing was just to isolate the problem. I'm writing an LDAP client and > the data model is made up of ObjectClasses which in turn have required > and optional attributes. ObjectClasses can inherit attributes from > "superior" ObjectClasses and the actual dataset (entry) may consist of > multiple ObjectClasses, collecting all their attributes. > > I thought it would be a good idea to mimic that with classes in the > client code by naming the classes like the ObjectClasses and get the > required and allowed attributes of the instance from the server in > __init__ like: > r = self.schema.get_obj(ldap.schema.ObjectClass,\ self.__class__.__name__) > ...process r... > > This has to be done for every parent and the whole point was *not* to > write another __init__ for each subclass. So the question boils down to: > > 1) Do I have to call Super.__init__ explicitely in: Child(Super)'s > __init__ method ? Yes. (But there's a workaround, see below) > 2) If 1): Since I do not want to write a new __init__ for every possible > subclass, how do I call Super.__init__ if I do not know Super's name? super() comes to the rescue. If you follow c.l.py you'll notice that there are pitfalls, though. http://www.python.org/2.2/descrintro.html#cooperation might be useful. >>> def makeClass(attributes): ... class A(object): ... def __init__(self, **kw): ... super(A, self).__init__(**kw) # this does the magic ... for a in attributes: ... setattr(self, a, kw.get(a, "")) ... return A ... >>> A = makeClass("abc") # use a list of attribute names in real code >>> B = makeClass("xyz") >>> class C(A,B): ... pass ... >>> c = C(**dict(zip("abklxy", range(6)))) >>> c.a # initialized by keyword arg 0 >>> c.c # set to default value '' >>> c.k # silently ignored Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'k' >>> The makeClass() factory is not strictly needed. Just remember to derive every base class from object and call super(CurrentClass, self).__init__() in its __init() method. Peter From cookedm+news at physics.mcmaster.ca Wed Feb 4 14:52:42 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 04 Feb 2004 14:52:42 -0500 Subject: PEP 327: Decimal Data Type References: Message-ID: At some point, Stephen Horne wrote: > On Mon, 02 Feb 2004 17:07:52 -0500, cookedm+news at physics.mcmaster.ca > (David M. Cooke) wrote: > >>At some point, "Batista, Facundo" wrote: >> >>> danb_83 wrote: >>> >>> #- On the other hand, when I say that I am 1.80 m tall, it doesn't imply >>> #- that humans height comes in discrete packets of 0.01 m. It >>> #- means that >>> #- I'm *somewhere* between 1.795 and 1.805 m tall, depending on my >>> #- posture and the time of day, and "1.80" is just a convenient >>> #- approximation. And it wouldn't be inaccurate to express my height as >>> #- 0x1.CC (=1.796875) or (base 12) 1.97 (=1.7986111...) meters, because >>> #- these are within the tolerance of the measurement. So number base >>> #- doesn't matter here. >>> >>> Are you saying that it's ok to store your number imprecisely because you >>> don't take well measures? >> >>What we need for this is an interval type. 1.80 m shouldn't be stored >>as '1.80', but as '1.80 +/- 0.005', and operations such as addition >>and multiplication should propogate the intervals. > > I disagree with this, not because it is a bad idea to keep track of > precision, but because this should not be a part of the float type or > of basic arithmetic operations. > I was being a bit facetious :-) This is certainly something that can be done without being builtin, like this: http://pedro.dnp.fmph.uniba.sk/~stanys/Uncertainities.py > Having an approximate representation with an interval sounds good, but > remember that one error source is the arithmetic itself - e.g. 1.0 / > 3.0 cannot be finitely represented in either binary or decimal without > error (except as a rational, of course). Hey, if my measurement error is so small that arithmetic error becomes significant, I'm happy. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From stefnin at alussinan.org Sun Feb 8 16:22:35 2004 From: stefnin at alussinan.org (Stéphane Ninin) Date: 08 Feb 2004 21:22:35 GMT Subject: fonts in PIL ? Message-ID: Hello all, I am writing (on Linux Redhat 9) some script to make graphs using PIL, from a set of points. All is ok, except that there seems to be no font coming with PIL. Where could I fond some ? Also, are there some real examples of use of fonts in PIL ? Documentation says something like: > load > ImageFont.load(file) => Font instance > > Loads a font from the given file, and returns the corresponding font > object. If this function fails, it raises an IOError exception. but should "file" be the full path to the font, or just a font name ? Same question for method truetype: > truetype > ImageFont.truetype(file, size) => Font instance > > Load a TrueType or OpenType font file, and create a font object. This > function loads a font object from the given file, and creates a font > object for a font of the given size. > On Windows, if the given file name does not exist, the loader also looks > in Windows fonts directory. Also, only true type fonts can be resized: there is no easy way to resize standard fonts ? (I am not a font expert :) ) Thanks in advance for your answers. Regards, -- Stephane Ninin From skatepunk319 at hotmail.com Sat Feb 14 15:03:58 2004 From: skatepunk319 at hotmail.com (Spencer) Date: 14 Feb 2004 12:03:58 -0800 Subject: How to make forums Message-ID: I am interested in making my own forums (powered by Python). I was wondering what would be needed to make one, so that I can start making it. I have always used the login script I made (it uses PHP and MySQL), will people be able to use the forums using a PHP/MySQL login script? Will it makes things more complicated? Of course I will answer any questions you may have. From majordomo-owner at mj2.freeswan.org Sun Feb 1 02:33:36 2004 From: majordomo-owner at mj2.freeswan.org (majordomo-owner at mj2.freeswan.org) Date: Sun, 01 Feb 2004 08:33:36 +0100 Subject: Majordomo results: hello Message-ID: <20040201073336.306162AD03@lists.freeswan.org> An embedded and charset-unspecified text was scrubbed... Name: not available URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: not available URL: From usenet at ixokai.net Mon Feb 9 14:05:08 2004 From: usenet at ixokai.net (Ixokai) Date: Mon, 9 Feb 2004 11:05:08 -0800 Subject: CoInitialize error when using adodbapi References: Message-ID: <102fmf9l12eho0e@corp.supernews.com> Basically, adodbapi uses COM, and COM and threads require a bit of care, apparently. Your webkit thing may be using a thread to handle stuff. import pythoncom pythoncom.CoInitialize() ... code ... pythoncom.CoUnitialize() You need to call pythoncom.CoInitialize() once for each thread... theres something about sys.coinit_flags = 0 (or 1) that may be nessecary but I don't know what they mean precisely :) --Stephen "Max Ischenko" wrote in message news:c089rb$7cg$1 at hyppo.gu.net... > > Hi, > > I'm using adodbapi wrapper arount OLEDB driver and I got this error when > calling adodbapi.connect(): > (-2147221008, 'CoInitialize has not been called.', None, None) > > The weird part is that it occurs only when running under WebKit, my > standalone test programs run just fine. > > I'm using py2.3 with win32all build 163, if that matters. > > Any ideas? > > tia. From magnus at thinkware.se Fri Feb 20 13:51:56 2004 From: magnus at thinkware.se (Magnus Lyck?) Date: 20 Feb 2004 10:51:56 -0800 Subject: Python Productivity Gain? References: Message-ID: <258fd9b8.0402201051.577b0fab@posting.google.com> "kbass" wrote in message news:... > In different articles that I have read, persons have constantly eluded to > the productivity gains of Python. One person stated that Python's > productivity gain was 5 to 10 times over Java in some in some cases. The > strange thing that I have noticed is that there were no examples of this > productivity gain (i.e., projects, programs, etc.,...). Can someone give me > some real life examples of productivity gains using Python as opposed other > programming languages. I don't think a tenfold programmer productivity increase over Java is typical, but there are certainly examples of significant productivity gains in converting to Python from some other language. See here for instance: http://www.thinkware.se/cgi-bin/thinki.cgi/PythonQuotes E.g. "I was amazed by the amount [of] flexibility and self-awareness that Python had. When a 20,000 line project went to approximately 3,000 lines overnight, and came out being more flexible and robust once it had been completed, I realized I was on to something really good." --Glyph Lefkowitz (Developer of the Twisted network server framework) This 6-7-fold improvement was in going from C++ I think. "...However, it did provide a hard measurement on the benefits of using Python instead of C++: the lines of Python code was 10% of the equivalent C++ code. ... From a software engineering standpoint, this was a tremendous success. Bug counts are always proportional to the number of lines of code, meaning that the Python version should have 10% of the bugs of the C++ version. Further, the fewer lines of code meant that it would have a smaller and more understandable "footprint" in the developers' minds. The Python code was arguably more maintainable due to its improved readability and rapid edit-test cycle (no compile and link step). Lastly, the server could also be shown to be more robust - being entirely in Python, it was not subject to memory-related coding errors such as null pointers, buffer misallocation and overruns, or unfreed or doubly-freed memory..." --Greg Stein, eShop (which was later sold to Microsoft) Here you have a 10-fold gain, going from C++. Another aspect of any X-fold programmer productivity improvement is that there is a lot more than just programming going on in a project. If requirements capture, analysis, design, testing, documentation, planning etc takes the same amount of time, you will still not be able to influence the total project cost a lot. On the other hand, using a tool like Python doesn't just influence the programmers, but the whole project! If prototyping and coding in general becomes significantly faster, the trade off for how much analysis and design you should do will change. Why spend weeks at a conference table arguing about different design alternatives if the programmers can supply several different implementations within a day? The sooner a prototype can be put in the hands of the end users, the faster mistakes in the requirements gathering will be sorted out, and new needs will be discovered and can be weighed in before it's too late. The ability to play interactively with Python objects and to develop really rapidly means that the roundtrip from end user request, to a new prototype for her to try out, can be reduced from hours to minutes or from days to hours. There is no reason to even leave the end users computer to add and demonstrate a new or changed feature. All we need is there... Testing, deployment, data conversion etc are also parts of software development projects that can gain a lot from having a tool like Python available. Other examples of productivity boosts with python can be found here: http://pythonology.org/success Few mention numbers though. I guess that there are some organisations that use the Capability Maturity Model for Software who would be able to find useful metrics if they used Python for a project similar to one where they had previously used Java, but a) few use CMM with such rigor, and b) if they did, they might not want to tell! Let the competition continue to waste their time coding Java. :) Finally, c) organisations where CMM is popular are probably organisations where static typing, waterfall development style and other rigid and archaic ideas are more popular than agile methods and tools. Still benchmarks always have a limited value. I've looked a bit at benchmarks, such as The Great Computer Language Shootout and looking at lines of code there, gives much smaller differences than five to ten times. I compared C++ and Python, and C++ varied from 25% less to 500% more lines of code, on the average C++ programs were around 80% longer. Less than a twofold gain it seems... But when we study the material in more detail, we see some relevant things: The more "realistic" the benchmarks are, the bigger the difference: For plain algorithm tests and things like "nested loops", "call a method", "instanciate an object" etc, there is almost no difference. For things like "echo client/server", "spell check", file handling etc, the difference is between 2.4 and 5.1 times. I don't know how strong the Java standard library is, but several of the benchmarks are about reimplementing builtin things in Python, such as sorting and random number generation. Completely meaningless! A real life implementation would be a much shorter, since most of the needed code is already in a standard library module! For fun, I've made Python programs that achieved the same end result without trying to use the same (meaningless) methods as the other programs in the benchmark, and they are often 10 times shorter. Sometimes they are also much faster and scalable. There are three big reasons that Python programs are typically short and easy to read. * The Python syntax and data types are at a higher level of abstraction, and don't have a lot of noise. It's also designed with the objective of making it easy to do the right thing, rather than making it difficult to do the wrong thing. * The dynamic nature of Python makes it easy to write very flexible code, and avoid a lot of code redundancy and twisting that is common as you have to fight against the limitations of more static and low level languages. * Python's standard library is rich and reasonably easy to use. In addition to that, the absence of compile and link steps in Python makes development much faster than languages like C++. I've worked in large C++ projects where building major applications could take an hour due to the extensive dependencies. In Python this is a non- issue. I don't know enough about Java development to compare with that. Since Python programs are shorter and easier to understand, and faster to write than programs written in most other languages, it's usually viable to change or rewrite code which is slow or otherwise non-optimal, while it's common in projects using other languages that code which is known to be bad is kept because it's too costly to fix it. Anyway, if you try Python in some project, I geuss your will form an educated opinion. I'm sure there is no one objective truth about this. Different people have different preferences, and different languages have different sweetspots. If you are writing drivers for hardware, or encryption code, Python is probably not main language, but it might still be very useful for various tools and one shot hacks that you do while you develop the "real" software in some other language. Some people think Ruby is "purer" and "prettier" than Python. Personally, I find the Perl-like features, such as various #@$% etc and mixing regular expressions in the syntax of the language rather awkward. From dswj at plasa.com Wed Feb 18 08:04:17 2004 From: dswj at plasa.com (dw) Date: Wed, 18 Feb 2004 20:04:17 +0700 Subject: curses class Message-ID: Yo guys, i've been looking into multiplatform console/terminal POS solution using python+curses, but stopped on the learning curve curses poses beautifully, and am now wondering if anyone has been making wonderful class for making text-based dialog box, grid, choose list, window, large-font, menu, and most of the spices that makes up a good terminal based program? -- dody wijaya =========================================================================================== Akses Internet Prabayar TELKOMNet-Prepaid, nominal Rp.10.000- Rp.150.000. Dapatkan di Plasa - Plasa TELKOM terdekat (khusus di Jawa Timur) =========================================================================================== From timothy.williams at nvl.army.mil Thu Feb 26 08:14:13 2004 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 26 Feb 2004 05:14:13 -0800 Subject: tkFileDialog different between Linux and Windows References: Message-ID: "Russell E. Owen" wrote in message news:... > In article , > timothy.williams at nvl.army.mil (Tim Williams) wrote: > > >I'm using Python 2.3.2 and tkFileDialog in a program I have. I'm > >trying to use this on Linux (RH 8.0) and Windows 2000. When I first > >upgraded from v2.2 to v2.3. I noticed that > >tkFileDialog.askopenfilename() returns a tuple on Cancel instead of > >''. I found that the Windows version still returns a string (''). Now > >I'm finding out that tkFileDialog.Directory().show() does this too. > ... > >How can I check tkFileDialog to do the "right" thing? All I want is > >the string that contains the path, but I want this to work on both > >Linux and Windows. > > Is this the sort of thing you want? > > dirobj = tkFileDialog.askdirectory() > if not dirobj: > # user Cancelled; works whether the return is '' or () > return > > # dirobj may be a string or a Tk_Obj > dirname = unicode(dirobj) > > The same code should work for askopenfilename. That did it! Thanks! From kbk at shore.net Fri Feb 6 14:45:46 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 06 Feb 2004 19:45:46 GMT Subject: new newbie References: Message-ID: <87llngj8k6.fsf@hydra.localdomain> not_yet writes: > also wanted to ask is there a faq for this group? www.python.org/doc/faq For the newsgroups, you can search quickly using Google Groups: www.python.org/search -- KBK From stewart at midtoad.homelinux.org Mon Feb 23 01:15:32 2004 From: stewart at midtoad.homelinux.org (stewart) Date: Mon, 23 Feb 2004 06:15:32 GMT Subject: learning to program with Python References: Message-ID: <8Ug_b.593859$X%5.271567@pd7tw2no> Ricardo wrote: > The code in wich i'm > having problems is as follows: > ... > if corPelo != None > self.corPelo = corPelo ... Oi Ricardo, tudo bem? I see at least two problems here. Python requires brackets around the 'if' comparison, and a colon at the end of the if statement. Try re-writing your statement as: if (corPelo != None): self.corPelo = corPelo Boa sorte! S From tjreedy at udel.edu Sun Feb 22 14:27:28 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 22 Feb 2004 14:27:28 -0500 Subject: Conversion code not working properly References: <3uuh305tv9o3g5dpenoqaghtbkiuihdpua@4ax.com> Message-ID: "weasel" wrote in message news:3uuh305tv9o3g5dpenoqaghtbkiuihdpua at 4ax.com... > Why is the Farenheit to Celsius part not working properly? Specific examples of what you put in, what you get out, and what you expected out and why often helps get answers. > Instead of > showing a similar range of what the farenheit is listing, the celsius > portion is showing half the range of farenheit. Celcius ranges are 5/9ths, approximately 1/2, the corresponding Farenheit ranges. Terry J. Reedy From joe at notcharles.ca Wed Feb 25 15:42:38 2004 From: joe at notcharles.ca (Joe Mason) Date: Wed, 25 Feb 2004 20:42:38 GMT Subject: How does Ruby compare to Python?? How good is DESIGN of Rubycompared to Python? References: Message-ID: In article , Dave Brueck wrote: > def someFunc(callback): > print callback(5,6) > > def functionCallback(a, b): > return a + b > > class Foo: > def methodCallback(self, a, b): > return a * b > > then both these work: > > someFunc(functionCallback) > f = Foo() > someFunc(f.methodCallback) > > This is pretty darn useful and IMO quite Pythonic: the creator of the function > and the creator of the callback have to agree on only the most minimal set of > details - just those relating to the calling interface - leaving completely > open any implementation details. I still don't see how this is notable. Seems perfectly straightforward to me - I'd just assume that's how it worked except in C++, about which I never assume anything. A better example of buond vs. unbound methods is this: def boundFunc(callback): print callback(5, 6) def unboundFunc(obj, callback): print callback(obj, 5, 6) def functionCallback(a, b): return a + b class Foo: def methodCallback(self, a, b): return a * b + self.c def setc(self, c): self.c = c >>> boundFunc(functionCallback) 11 >>> f = Foo() >>> f.setc(3) >>> boundFunc(f.methodCallback) 33 >>> unboundFunc(f, Foo.methodCallback) 33 For anyone who does care, the Ruby version is def boundFunc(callback) puts callback.call(5, 6) end def unboundFunc(obj, callback) callback.bind(obj).call(5, 6) end def functionCallback(a, b) return a + b end class Foo def methodCallback(a, b) return a * b + @c end def setc(c) @c = c end end > boundFunc(method(:functionCallback)) 11 => nil > f = Foo.new => # > f.setc(3) => 3 > boundFunc(f.method(:methodCallback)) 33 => nil > unboundFunc(f, Foo.instance_method(:methodCallback)) => 33 It's a little more cumbersome to manipulate functions because of the extra calls to "call" and "bind", because "f.methodCallback" actually calls the method with no params instead of returning a reference to it. This is one of the things I dislike about Ruby, but it's not like unbound methods are missing from the language. (I was wrong when I said "unbound method" was a concept that had no meaning to Ruby - it even had a "bind" method to support them. Didn't know about that until I looked it up just now.) Joe From ab at telin.diespammerdie.UGent.be Fri Feb 6 05:25:22 2004 From: ab at telin.diespammerdie.UGent.be (Alex Borghgraef) Date: Fri, 6 Feb 2004 10:25:22 +0000 (UTC) Subject: Python projects in kdevelop 2.1 Message-ID: Hi all, Since we don't have gideon installed here at work, I was wondering if it is possible to use the older version, kdevelop 2.1 for python projects. If so, how? Do I have to download some plugin of sorts? -- Alex Borghgraef From jzgoda at gazeta.usun.pl Sun Feb 22 11:43:55 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 22 Feb 2004 16:43:55 +0000 (UTC) Subject: Some source code References: Message-ID: Adam Przybyla pisze: >> file('output.txt','w').writelines(['%s,"%s"\n' % (line[:-1], >> sum(map(int,line[1:-2].split('","')))) for line in >> file('input.txt')]) > file('output.txt','w').writelines(['%s,"%s"\n' % > (line[:-1],sum(eval(line[1:-2]))) for line in file('input.txt')]) You still call this code "pythonic"? -- Jarek Zgoda http://jpa.berlios.de/ From claird at lairds.com Sat Feb 21 12:17:13 2004 From: claird at lairds.com (Cameron Laird) Date: Sat, 21 Feb 2004 17:17:13 -0000 Subject: How do I access Python's dictionary of all global variables? References: Message-ID: <103f4kp694je77e@corp.supernews.com> In article , Noah wrote: >I thought that Python has a builtin dictionary that associates >global variable names with their values. I have forgotten how to do this and >I can't seem to come up with the right search keywords to locate this secret >again. I'm trying to write a global dynamic variable debugger sort of thing. > >So for example you could have code that looked something akin to this: >>>> x = 5 >>>> y = "hello" >>>> z = [1,2,3] >>>> print __VARS__['x'], __VARS__['y'], __VARS__['z'] >x hello [1, 2, 3] > >Is it possible to iterate through all variables in all scopes in all objects? . . . Start with print globals() -- Cameron Laird Business: http://www.Phaseit.net From http Sat Feb 28 14:18:51 2004 From: http (Paul Rubin) Date: 28 Feb 2004 11:18:51 -0800 Subject: Please hear my plea: print without softspace References: <4041796c.2181078@news.muenster.de> Message-ID: <7xhdxbau78.fsf@ruckus.brouhaha.com> "Carmine Noviello" writes: > def pprint(*args): > txt = "" > for a in args: > txt += str(a) > print txt > > Is it ok? import sys def pprint(*args): for a in args: sys.stdout.write(a) From martin at v.loewis.de Wed Feb 11 12:39:51 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 11 Feb 2004 18:39:51 +0100 Subject: Python.h problem-> /usr/include/python2.2/longobject.h:48: warning: ISO C89 does not support `long long' In-Reply-To: References: <16425.25330.886172.548459@montanaro.dyndns.org> <20040210231435.GB15796@spawar.navy.mil> <16425.31826.535656.7252@montanaro.dyndns.org> Message-ID: seberino at spawar.navy.mil wrote: > However, I know in near future all Python > integers will be of type "Python long" and there > won't be "Python ints" anymore IIRC. You might remember incorrectly, atleast with respect to the time scale in which this is happening. > I wonder if Python source will still use 64 bit ints then in > implementation. C ints and long longs have nothing to do with Python ints and longs. A Python int is implemented with a C long, and a Python long is not implemented with any primitive type (instead, it is implemented as an array of C shorts). In any case, Python will continue to use the PY_LONG_LONG type even if Python ints would go away. Regards, Martin From lutz at rmi.net Tue Feb 10 11:02:15 2004 From: lutz at rmi.net (Mark Lutz) Date: 10 Feb 2004 08:02:15 -0800 Subject: When Pythons Attack (article) Message-ID: O'Reilly just posted an article I wrote, which describes the most common mistakes made by Python beginners. It's available at this direct link: http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html but can also be found on O'Reilly's home page (www.oreilly.com), the O'Reilly Network page (www.oreillynet.com), and the Python resources page (python.oreilly.com). --Mark Lutz (http://www.rmi.net/~lutz) From klaus_neuner82 at yahoo.de Fri Feb 13 07:09:13 2004 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 13 Feb 2004 04:09:13 -0800 Subject: write a recognizer References: <3e96ebd7.0402120105.14ee6f6d@posting.google.com> Message-ID: <3e96ebd7.0402130409.6148caec@posting.google.com> Thanks to all who participated in this thread. From jnoller at reference-info.com Wed Feb 4 09:27:18 2004 From: jnoller at reference-info.com (Jesse Noller) Date: 4 Feb 2004 06:27:18 -0800 Subject: Read a binary file and feed it to PyCURL Message-ID: <2835a96b.0402040627.37adc538@posting.google.com> The problem: I am writing a file uploading utility in python that uses the walk() function to parse a directory, finding any file under that directory, and upload it to a remote server using the pyCURL curl interface. The files are invariably binary files, and the upload method is via an HTTP PUT to the system. I also need to perform the reverse - I need to GET those files and write them to disk. The problem I am seeing is memory. Currently, I call os.path.walk(dir), and then I call the upload function. The upload function basically goes (the formatting got nuked when I pasted it): f = open(filepath, "rb") fs = os.path.getsize(filepath) c = pycurl.Curl() c.setopt(c.URL, target_url) c.setopt(c.HTTPHEADER, ["User-Agent: Load Tool (PyCURL Load Tool)"]) c.setopt(c.PUT, 1) c.setopt(c.READDATA, f) c.setopt(c.INFILESIZE, int(fs)) c.setopt(c.NOSIGNAL, 1) if verbose == 'true': c.setopt(c.VERBOSE, 1) c.body = StringIO() c.setopt(c.WRITEFUNCTION, c.body.write) try: c.perform() except: import traceback traceback.print_exc(file=sys.stderr) sys.stderr.flush() f.close() c.close() sys.stdout.write(".") sys.stdout.flush() This opens the file via open() - which reads the file into memory. This of course, causes problems when the client machine only has 512 megs of ram and we're uploading a 2-3 gig file (barring the argument against doing this via HTTP PUT). Does anyone know a more efficient method to do this with? Please also note I am measuring the metrics for each transaction sent too - so I don't want to chunk and then upload, as I only get metrics for the chunks. The metrics measuring comes before the c.close() function: speed_up = c.getinfo(c.SPEED_UPLOAD) size_up = c.getinfo(c.SIZE_UPLOAD) ttime = c.getinfo(c.TOTAL_TIME) ctime = c.getinfo(c.CONNECT_TIME) sttime = c.getinfo(c.STARTTRANSFER_TIME) Does anyone have any thoughts? Thank you -jesse From deets_noospaam at web.de Mon Feb 2 16:01:08 2004 From: deets_noospaam at web.de (Diez B. Roggisch) Date: Mon, 02 Feb 2004 22:01:08 +0100 Subject: Finding messages in huge mboxes References: <401eb54c$0$315$e4fe514c@news.xs4all.nl> Message-ID: > Anyone who has a better idea? AFAIK MUAs usually use a mbox.index-file for faster access. The index is computed once, and updated whenever a new message is added. You could create this index quite easily yourself by looping over the mbox and pickling a list of tell'ed positions. If you also store the creation-date of the index and the filesize of the mbox-file, you should be able to create a function that will update the index whenever the underlying mbox has changed. Another approach would be to perform index-creation on regular bases using cron. Regards, Diez From trevp at trevp.net Sat Feb 28 13:27:09 2004 From: trevp at trevp.net (Trevor Perrin) Date: 28 Feb 2004 10:27:09 -0800 Subject: Pure Python HTTPS Server References: <7x4qtcozv5.fsf@ruckus.brouhaha.com> <47e891f1.0402280017.5f8af771@posting.google.com> <7xd67zsfqg.fsf@ruckus.brouhaha.com> Message-ID: <47e891f1.0402281027.21cc232d@posting.google.com> Paul Rubin wrote in message news:<7xd67zsfqg.fsf at ruckus.brouhaha.com>... > trevp at trevp.net (Trevor Perrin) writes: > > > I proposed a standard block cipher API and wrote a > > > sample implementation last year, > > > > I like that API. I wonder if there's any performance issues in > > separating the codebook from the mode-of-operation, but I haven't > > thought about that much. > > If needed, the C-level API can be expanded so codebook modules have a > way to communicate directly with the modes-of-operation module, > without needing to do Python attribute lookups all the time. But even > without that optimization, I don't think the performance issues should > be so bad. The attribute lookup shouldn't be any slower than a > codebook call, so if you do it just once when you invoke a chaining > mode, the overhead for large buffers should be minimal. Sounds good, as long as you don't have to do anything expensive per-block. > Do you happen to have a pure-Python DES implementation around? I > started writing one once, but it had some bug (i.e. it didn't pass > FIPS test vectors) that I never got around chasing down. I found one here: http://home.pacific.net.au/~twhitema/des.html It's too slow to do anything useful (that's DES's fault, I think, not the progammer's). > > Did you ever look at the key management scheme I circulated a while > back? Is it the kind of thing anyone cares about? I didn't see that. I did see that you've talked about a stdlib interface to OS-level Random Number Generators, like /dev/urandom and CryptGenRandom. I think that's an excellent idea. (aside from ciphers and RNGs, the other thing on my wish-list is faster modular exponentiation.. Python use a simple right-to-left square-and-multiply. I'm no expert here, but I think it would be pretty easy to make that a few times faster for crypto sized numbers. tlslite's handshaking, in python code, is ~5x slower than OpenSSL right now..) Trevor From shalabh at gameboard.org Mon Feb 16 01:39:46 2004 From: shalabh at gameboard.org (Shalabh Chaturvedi) Date: 15 Feb 2004 22:39:46 -0800 Subject: Python Productivity Gain? References: Message-ID: "kbass" wrote in message news:... > In different articles that I have read, persons have constantly eluded to > the productivity gains of Python. One person stated that Python's > productivity gain was 5 to 10 times over Java in some in some cases. The > strange thing that I have noticed is that there were no examples of this > productivity gain (i.e., projects, programs, etc.,...). Can someone give me > some real life examples of productivity gains using Python as opposed other > programming languages. There is lot that can be said about why Python is more productive. I'll make one point that has not yet been mentioned in this thread. I like to say that Python has a very good impedance match with the mind (mine at least :). Normally when you program, you: 1. Analyze the problem 2. Come up with a 'solution in mind' 3. Translate the 'solution in mind' into 'solution in code' It's 3 where Python shines. For a concrete example, consider looping over a list of items. Apart from the looping object and the list, you need: Java: An iterator C: A counter Perl: A lot of '$' signs :) Python: Nothing. (for item in mylist:) Notice how Python keeps it explicit yet minimal, and there's nothing more in your mind than what is absolutely necessary ("fits you brain"). As a real life analogy, when I make a multi-egg omelette, for each egg in bunch_of_eggs, I pan.put(egg.break()). If I had to think of an iterator, or a counter, it would be lunchtime before I'd have breakfast. In other words, Python *is* how I think. This is what I mean by a good impedance match. Note that you can still use an iterator in Python (but only if and when you need it). For another example, consider nested lists in Perl and Python. In Perl one struggles with the language, in Python one struggles with only the problem. In other languages I've used (Java, C++, Perl), I always get sidetracked into syntax issues ("oh I have to write it *this* way!"), library issues ("oh I have to import this and that first!") and such, all of which consume my brainpower leaving little for the problem at hand. These little things add up and affect productivity tremendously. Python has few of these and I've always found myself rushing to Python as the first choice to implement any algorithm, solution, or idea that I had. It is the shortest path to the program. Some newcomers are so used to thinking in roundabout ways that they write C or Java code in Python. I did too - using counters for loops, creating way too many classes etc. But eventually everyone learns the power of simplicity. Naturally, reading a Python program and figuring out what it does is fast too, greatly improving maintainability. I'm writing an article on Python productivity, which I'll post here at some point. Cheers, Shalabh From peter at engcorp.com Tue Feb 24 14:30:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 24 Feb 2004 14:30:07 -0500 Subject: Memory Leak References: Message-ID: <403BA63F.ACCB26CB@engcorp.com> Guy wrote: > > It might take me a little time to explain this but here goes. Thanks for the details you did provide; it's more than most manage! > Firstly I'm not using the latest upto date python releases so my first > plan is to try more upto date rels of python and win32 libs, as this > has fixed problems for me in the past (Don't like doing this as it > usally breaks stuff and sys admin are slow to update software, > although they do a cracking job, just covering my back.) Definitely do that. There have been memory leaks in past versions (and possibly are in the latest too, but it's perhaps less likely unless you are using some of the newest features, which you obviously aren't). I'd even suggest that doing much before you try that would be a waste. > The problems occure when I build more than one flavour of the product, > (there are 16 possible flavours and about 50 modules which get turned > into libs and exe's this means theres 800 processes to be set off one > after the other or if using a clean build 1600 process and thats just > for win32, to build one flavour it takes about 40 mins on my comp.) > > When using the build script it keeps logs of what its built and > records all output from the process all these python objs and lists > are destroyed by using del to try and free up memory, this never seems > to have that much effect the memory just keeps getting used up until > usally the script or python crashes due to the lack of mem. Memory leaks are extremely difficult to debug, perhaps more difficult than any other problem except race conditions. Thankfully, real memory leaks are very rare. I don't think you've described enough to prove that you actually have a memory leak. What you are describing sounds more like you're just using up all the resources too quickly, which is more of a capacity (or design) problem than anything else. More importantly, you've got way too many variables involved to be able to troubleshoot this, if it's really a memory leak. You absolutely will have to simplify the setup, while keeping the problem occurring, in order to solve this issue. If this is a memory leak involving Python, you will be able to reproduce it with a program that involves nothing but Python, and perhaps a small external dummy program that you launch repeatedly in the other processes. You shouldn't have to bother with "del" at all, since all that does is release the name from the object it's bound to (or vice versa) and if there are no other names bound to the object, Python will free the memory anyway. (Note that it might not return the memory to the OS, however. You can't force that to happen, either.) Doing a "del" followed by reassigning the name to a new object is basically a waste of time. Consider this. From the looks of things, you are doing so much that is actually *outside* of the scope of Python that you might simply be running out of memory elsewhere. Also consider whether this might be due to memory fragmentation rather than true leaking. You might need to analyze your pattern of memory usage to see whether this could be the case. -Peter From piedmontbiz at aol.com Sun Feb 29 12:50:27 2004 From: piedmontbiz at aol.com (PiedmontBiz) Date: 29 Feb 2004 17:50:27 GMT Subject: Brent Ashley's JavaScript remote scripting (JSRS) Message-ID: <20040229125027.01774.00000642@mb-m22.aol.com> I am looking for ways to do interactive web pages with python as a backend. I ran across serveral articles on Brent Ashley's JavaScript remote scripting (JSRS) locateded at http://www.ashleyit.com/rs/ This package allows a client web browser to transfer data to and from the server without loading reloading pages.... as I understand it. The resulting "application" would be have like a desktop application. I downloaded and am now studying the code. There are no demos with a web page calling a python script but I am going to whip something up soon. Anyone with any experience with this? Does it really work? Any caveats? Thanks allen From hermes at numericable.fr Fri Feb 20 06:03:31 2004 From: hermes at numericable.fr (hermes at numericable.fr) Date: Fri, 20 Feb 2004 12:03:31 +0100 (MET) Subject: Python and C Message-ID: <1077275011.4035e983d897a@pascal.numericable.net> Hi, this may be a newbie question, as I'm quite new to python but I'd rather get your points of view instead of wasting a week or two on a wrong way I'm using python 2.3 on a mandrake brand new system My problem : I'd like to use a complex C program under python. After few researchs I tested SWIG, which seems to work for me exept that I'd like to be able to use a C function under python that has this prototype void Fitimp(double *x1, double *x2... ) these double parameters are lists of double precision number. The python script will read this datas from files, So i'd like to know how to transform a python list of double precision float to a C double * variable Thx for your help Gilles A From scrutinizer at gmx.at Thu Feb 5 15:07:10 2004 From: scrutinizer at gmx.at (Francesco) Date: Thu, 05 Feb 2004 21:07:10 +0100 Subject: wxPython issues References: <5onv10pd080l2jkufaigdtcn21p2735jpf@4ax.com> Message-ID: On Tue, 03 Feb 2004 19:36:13 -0800, Josiah Carlson wrote: > >P.S. If you are looking for a good editor for Python, I wrote one: >http://pype.sourceforge.net PS: yes, it is; you know me from sf :) -- Francesco From jepler at unpythonic.net Wed Feb 25 09:59:28 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 25 Feb 2004 08:59:28 -0600 Subject: Memory Leak ['LBBW': checked] In-Reply-To: References: Message-ID: <20040225145927.GA25342@unpythonic.net> On Wed, Feb 25, 2004 at 03:18:33PM +0100, Holger Joukl wrote: > 2) I am quite stunned by the del alist[:] thing: > >>> class foo: > ... def __del__(self): > ... print "foo.__del__" > ... > >>> alist=[foo(), foo(), foo()] > >>> del alist[:] > foo.__del__ > foo.__del__ > foo.__del__ > >>> alist > [] > alist[:] creates a shallow copy of alist, which is a new object. del then > decreases the refcount of this > temporary object, thus it is destroyed. But why is the original alist empty > after that, why are the > list elements destroyed? > Does that mean if a shallow copy of a list is created, the refcounts of the > elements in the list are not increased? "del alist[:]" does not get a slice of alist and then delete the resulting copy. del can work on names ("del a"), attributes ("del o.x") and slices ("del l[:]"). The following part of an interactive session shows that __delslice__, not __getslice__ is called for "del c[:]". >>> class C: ... def __getslice__(self, *args): print "getslice", args ... def __delslice__(self, *args): print "delslice", args ... >>> c = C() >>> c[:] getslice (0, 2147483647) >>> del c[:] delslice (0, 2147483647) Jeff From rpm1deleteme at direcway.com Fri Feb 13 17:01:27 2004 From: rpm1deleteme at direcway.com (RPM1) Date: Fri, 13 Feb 2004 17:01:27 -0500 Subject: beeline through tkinter References: Message-ID: "Elaine Jackson" wrote ... > I'm about to tackle tkinter, but here's the thing: The only kind of GUI I want > to work on is a chessboard (an 8x8 grid of images that can be "moved around"). > So before I start, I'm asking the room at large: Is there some way of going > directly to what I'm interested in? Any help will be very much appreciated. Chess board huh? What are you going to do with a chess board and python? Just curious, :-) Patrick From jcarlson at nospam.uci.edu Sat Feb 21 01:53:10 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Fri, 20 Feb 2004 22:53:10 -0800 Subject: Parsing apache log files In-Reply-To: References: Message-ID: > It was the http auth, which for some reason, show up from time to time, > may be a misconfigured router/proxy don't know. But this works, although > my brain is still parsing the regexp :) Thank you very much for your > help. It is relatively easy to generate the regular expression by hand, I did. But I agree, it is a bit dense if you didn't do it. I need to pull out the python docs every time I see a regular expression that I didn't write. - Josiah From kent at springfed.com Sat Feb 14 17:42:56 2004 From: kent at springfed.com (Kent Tenney) Date: Sat, 14 Feb 2004 16:42:56 -0600 Subject: A Python equivalent of cfengine? Message-ID: Howdy, Any recommendations for automating administrative tasks using Python? Thanks, Kent From http Thu Feb 19 22:57:54 2004 From: http (Paul Rubin) Date: 19 Feb 2004 19:57:54 -0800 Subject: Generating a large random string References: <4034D506.2E37519A@netsurf.de> <7xsmh6a7cd.fsf@ruckus.brouhaha.com> <7x65e2ikqi.fsf@ruckus.brouhaha.com> Message-ID: <7x7jyipflp.fsf@ruckus.brouhaha.com> "Sean Ross" writes: > And when you've done > > s = open("/dev/urandom").read(1000000) > > is s a string containing one million letters [a-zA-Z] and no other > types of characters, as the OP is looking for? Oops, per other post, it gives strings of bytes and needs filtering. The following runs in about 1.2 seconds on my machine, but has an small (infinitesimal) chance of failure: import string,array,time t=time.time() ttab = string.letters*4 + '\0'*48 a = array.array('B', open("/dev/urandom").read(1500000).translate(ttab)) a = array.array('B', filter(abs,a)).tostring()[:1000000] print time.time()-t From bob at redivi.com Sun Feb 29 09:27:12 2004 From: bob at redivi.com (Bob Ippolito) Date: Sun, 29 Feb 2004 09:27:12 -0500 Subject: Thoughts on new vs traditional idioms References: <5d83790c.0402290218.2d3c493f@posting.google.com> Message-ID: <2004022909271250073%bob@redivicom> On 2004-02-29 06:49:36 -0500, Peter Otten <__peter__ at web.de> said: > Raymond Hettinger wrote: > >> d = {'a':1} >> d.__init__([('b',2), ('c',3)]) # update with an items list >> d.__init__(d=4, e=5) # update with keyword arguments >> d.__init__(mydict) # update with another dictionary > > This is the first time I've seen the init as update idiom - this is clearly > not a case of love at first sight. Objects cumulating data over subsequent > calls of __init__() seems unintuitive to me. > > Why isn't dict.update() enhanced to handle all three cases? You might > actually use the same implementation for both __init__() and update(). I submitted a small patch last week to correct this (well, to support the first case, not the kwargs), but it was -1 or -0 by several people, including guido, and ended up rejected. -bob From exarkun at intarweb.us Sat Feb 7 12:36:21 2004 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 7 Feb 2004 12:36:21 -0500 Subject: [Twisted] Sessions validity In-Reply-To: References: Message-ID: <20040207173620.GA894@intarweb.us> On Sat, Feb 07, 2004 at 06:10:49PM +0100, Frantisek Fuka wrote: > Sorry for posting this here but I got no reaction when asking in > twisted-web mailing list: > > Twisted stores the Session objects using cookies. I'd like to know how > long these Sessions last (it seems to be 30 minutes?) and - more > importantly - I'd like my application to be able to set different > Session timeouts for different users. I need some of the users (just > some!) to be able not to click on anything on the site for several hours > and still be logged in afterwards, when they click. > > Is there a way to do this cleanly or do I have to change the Twisted > sources? (I admit I am not very proficient with the cookies) > The default is 60 seconds before login occurs, 30 minutes afterwards. It is changed by calling "setLifetime" on the GuardSession. Jp From na Sun Feb 8 18:13:24 2004 From: na (ADE) Date: Sun, 8 Feb 2004 15:13:24 -0800 Subject: How to search for files References: <102d1936uqaqbc4@corp.supernews.com> Message-ID: <102dgpk7akbmo94@corp.supernews.com> Hi I figured it out thank you for pointing me in the right direction "fBechmann" wrote in message news:c06149$50n$05$1 at news.t-online.com... > os.walk (needs python 2.3) and/or glob.glob() should be good places to > start your search. From jnewman at ups-scs.com Wed Feb 4 13:18:25 2004 From: jnewman at ups-scs.com (jnewman at ups-scs.com) Date: Wed, 4 Feb 2004 13:18:25 -0500 Subject: Out of Office AutoReply: HI Message-ID: I'm out of the office traveling on business until Sunday, February 8th, 2004. I can be reached on my mobile at (720) 635-6889. You can also contact Doug Scobee at descobee at ups-scs.com or (720) 941-1001 for CO, KS, NE,ND, SD, WY issues. Jon G. Newman Branch Manager - CO, KS, NE, ND, SD, WY (720) 941-1001 Office (720) 941-2610 Fax (800) 877-1683 Toll Free (720) 635-8669 Mobile jnewman at ups-scs.com UPS Supply Chain Solutions From nospam-deets at web.de Wed Feb 4 11:11:03 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Wed, 04 Feb 2004 17:11:03 +0100 Subject: Advice: socket handling and threads References: Message-ID: > Is it sensible to port these sections of code to Python? Do I stand to > gain or lose by doing this... I doubt the performance difference will be > noticeable, and the only areas of the project that I would maybe consider > extending in C++ are to do with parsing (and to be honest I think it'll be > fine left in Python). > > Finally there is the cherry on the cake in the form of cross-platform > compatibility. My C++ code only works on *nix (or cygwin) but as far as I > understand it, my threads and sockets should work fine on Windows and Mac > too, if done in Python...? (This is a CLI app not GUI by the way.) > > Thoughts and general musings will be greatly appreciated (as will any > warnings of pitfalls I may encounter!) You should look into python twisted, a framework for networking. It has plenty of features. You can easily write portable networking code that makes use of select for dispatching, so you don't need to be multithreaded. It also supports reactors that are multithreaded, but in my expirience thats not necessary, as multithreading often is an excuse for easier handling of blocking io - which you avoid by the underlying select-based infrastructure. I had a mult-threaded client-server-app that also involved the serial line - porting it to twisted was easy and straighforward, and now I'm rid of all threads - which leads to way lower system load while the performance is the same. Regards, Diez From tyler at ml1.net Sat Feb 14 16:59:27 2004 From: tyler at ml1.net (Tyler Eaves) Date: Sat, 14 Feb 2004 21:59:27 GMT Subject: XML Parsing Message-ID: Hi, Right now I'm using xml.dom.minidom for parsing some xml files. It works, certainly, but the speed leaves a bit to be desired. Are there any other XML modules that offer the same interface minidom does, but are faster? Things like validation are not a big deal for me, as all the XML is generated by my own programs, so I'm not worried about malformed documents. From __peter__ at web.de Sun Feb 15 07:52:56 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Feb 2004 13:52:56 +0100 Subject: sending output References: Message-ID: Fknapp wrote: > I'm new to boa constructor, however I went through the tutorial and > loved it. I am trying to create a simple math program for my 6 yr old > daughter, I am creating a window that askes for two numbers and then > asks for the total, based on what they enter it compares and says that > is correct or that is wrong. I created a python script that works, > however when I try to import and say "myscript".DoThis() I get all > kinds of sytax errors. Any help would be appriciated Let's see: >>> "myscript".doThis() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'doThis' >>> Failing, but definitely *not* a syntax error. Please post _real_ if short code and _actual_ tracebacks (cut and paste). Peter From max at ucmg.com.ua.remove.it Tue Feb 10 02:38:20 2004 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Tue, 10 Feb 2004 09:38:20 +0200 Subject: synchronized method Message-ID: Hi, I wrote simple implementation of the "synchronized" methods (a-la Java), could you please check if it is OK: def synchronized(method): """ Guards method execution, similar to Java's synchronized keyword. The class which uses this method, is required to have a L{threading.Lock} primitive as an attribute named 'lock'. """ def wrapper(self, *args): self.lock.acquire() try: return method(self, *args) finally: self.lock.release() return wrapper ...I'm no big thread expert tia. ... The problem is not that there are problems. The problem is expecting otherwise and thinking that having problems is a problem. -- Theodore Rubin From FBatista at uniFON.com.ar Wed Feb 11 11:42:00 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 11 Feb 2004 13:42:00 -0300 Subject: How to avoid "f.close" (no parens) bug? Message-ID: Eric Brunel wrote: #- You may be able to call some "real" code just by accessing #- an attribute by using #- properties. I'm not quite sure, and I can't check because I #- have only Python 2.1 #- here. Jeff Epler wrote: #- For another, there may be legitimate uses, when it's specifically to #- cause the side effect that computation of the property requires #- (especially in the context of software testing). For instance, see #- http://weblogs.mozillazine.org/hyatt/archives/2003_08.html#003963 #- Personally, I view the fact that javascript (apparently) requires #- assigment to a dummy variable as a drawback of js. Thank you Jeff & Eric. I think these are valid cases and because of them, we can not forbide the use of such lines. Thanks again. . Facundo From paul at prescod.net Mon Feb 23 12:15:59 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 23 Feb 2004 09:15:59 -0800 Subject: Typecasting In-Reply-To: References: Message-ID: <403A354F.7040302@prescod.net> Jani Yusef wrote: > ... > Wow, YAMQFAI (Yet Another Moronic Question From An Indian). What is > terrible is how GE is now suffering because of these dollar a day > idiots. Man, what exactly did you learn at IIT? Did you learn how to > stop wiping your ass with your bare hand at least? > Anyway, the answer to your question is > s="555" > i=int(s) > now i is equal to 555. Better to not answer than to answer with contempt and racism. Among other problems, you give a poor impression of Pythonistas and Persians. You should spew bile into another forum from a different email address. Paul Prescod From rupole at hotmail.com Sat Feb 28 16:48:08 2004 From: rupole at hotmail.com (Roger Upole) Date: Sat, 28 Feb 2004 13:48:08 -0800 Subject: Python COM Variant problem References: Message-ID: <4040de8f_1@127.0.0.1> Try running makepy on the typelib that contains the objects. Also, the actual error msg that if fails with would be helpful. Roger "Annie" wrote in message news:b9942658.0402270131.624a8492 at posting.google.com... > I am trying to call a COM object which expects a variant datatype to > be passed in to the COM API object. However, I get " >" and the program fails. > > Below is my code in Python, and the same code in VB which is working > fine... > > I guess this is a variant problem with python? How can I make this > work? Would appreciate if someone can guide me as I am a python > newbie... :-) > > Thanks very much... > > ##In Python > def setAddOnValue(oBusObj > oAddOns = oBusObj.AddOns > print oAddOns #returns ">" > print oAddOns.Count #return 3 > for x in range(1, oAddOns.Count): > oAddOn = oAddOns.Item(x) #expects variant datatype for the x > variable > > > > ##In VB > Public Function setAddOnValue(oBusObj As Variant, strAddOnLabel As > String, strPropLabel As String, oVal As Variant) As Boolean > Dim x, y > Dim oAddOns As CAddOns > Dim oAddOn As CAddOn > Dim oAddOnValues As CAddOnValues > Dim oAddOnValue As CAddOnValue > > setAddOnValue = False > Set oAddOns = oBusObj.AddOns > > For x = 1 To oAddOns.Count > Set oAddOn = oAddOns.Item(x) > If oAddOn.AddOnName = strAddOnLabel Then > Set oAddOnValues = oAddOn.AddOnValues > For y = 1 To oAddOnValues.Count > Set oAddOnValue = oAddOnValues.Item(y) > If oAddOnValue.PropertyLabel = strPropLabel Then > setAddOnValue = True > Set oAddOnValue.Data = oVal > Exit For > End If > Next y > End If > If setAddOnValue = True Then > Exit For > End If > Next x > End Function From kbass at midsouth.rr.com Thu Feb 5 20:47:36 2004 From: kbass at midsouth.rr.com (kbass) Date: Fri, 06 Feb 2004 01:47:36 GMT Subject: Newbiew Question: Graphs and CGI in Python References: Message-ID: "kbass" wrote in message news:iVBUb.1956$cc.1002 at fe3.columbus.rr.com... > Is there a module for creating graphs within CGI programs in Python? I am > attempting to retrieve data from a database (Postgres) and display the data > in a graph through the browser. Thanks! > > kbass > > I am using Python 2.1 and Python 2.3 on RH Linux AS 2.1 From paul at prescod.net Thu Feb 26 04:31:33 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 26 Feb 2004 01:31:33 -0800 Subject: Some language proposals. In-Reply-To: References: Message-ID: <403DBCF5.4010405@prescod.net> Jacek Generowicz wrote: > I do wish you'd run your examples through a Python interpreter before > posting them. The little bugs you include, really interfere with > trying to understand what your point is. Sorry. Don't know what else I can do: bash-2.05a$ cat foo.py class a: pass def func(): pass lst = [1, 2, 3, "a", "b", "c", object(), lambda x:x ] for x in lst: a.b = x assert a.b is x, "What???? %s"% x print "Okay", x bash-2.05a$ python foo.py Okay 1 Okay 2 Okay 3 Okay a Okay b Okay c Okay Traceback (most recent call last): File "foo.py", line 11, in ? assert a.b is x, "What???? %s"% x AssertionError: What???? at 0x122190> bash-2.05a$ And this is after cutting and pasting the program from your reply back into a file. Given that I was trying to demonstrate an inconsistency in behaviour I felt it helpful to show examples of logical behaviour. Paul Prescod From lubowiecka at go2.pl Fri Feb 6 11:50:45 2004 From: lubowiecka at go2.pl (Nazgul) Date: Fri, 6 Feb 2004 17:50:45 +0100 Subject: self-extracting installer References: <4f0a9fdb.0402050419.3552abe@posting.google.com> Message-ID: Great thanks!!! Best Wishes, Sylwia From paul at prescod.net Mon Feb 9 17:08:57 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 09 Feb 2004 14:08:57 -0800 Subject: Had Phyton suggested In-Reply-To: References: <4026488d$0$95048$edfadb0f@dread11.news.tele.dk> Message-ID: <402804F9.30207@prescod.net> Steve Horsley wrote: > > > Python: > edlin myprog.py > python myprog > > java: > edlin myprog.java > javac myprog.java > jave myprog So Python does two steps with one command and Java does not. Surely that is an argument in favour of Python! > As for not encouraging bad habits, I thought not until I came across a > 34k python script where every variable was global and not one procedure > accepted any arguments or returned any values. I suspect that the only > chopping into procedures was to keep the text on the page. I now think > that a real beginner needs a better push in the right direction. If the programmer doesn't understand why this kind of programming is bad, I expect that they will replicate it in Java with static variables and static functions. Even in Java it takes extra effort to pass parameters instead of referring to static variables. But I think someone would have to do some usability testing to decide this for real. Paul Prescod From michele.simionato at poste.it Sat Feb 28 02:27:33 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 27 Feb 2004 23:27:33 -0800 Subject: Feature request: subclassing FunctionType [Was: Some language proposals] References: <95aa1afa.0402262158.5b33de79@posting.google.com> Message-ID: <95aa1afa.0402272327.29828430@posting.google.com> Jacek Generowicz wrote in message news:.... > > I don't think that Python's behaviour differs from other languages, in > this respect. For example in Common Lisp: > > * (defun make-adders (n) > (loop for i below n collect > (lambda (x) (+ x i)))) > MAKE-ADDERS > * (destructuring-bind (add0 add1) (make-adders 2) > (list (funcall add0 0) > (funcall add1 0))) > (2 2) I don't know Common Lisp, but Scheme scope rules do what I expect: (define (make-adders n) (unfold (cut = <> n) (lambda (i) (lambda (x) (+ x i))) add1 0)) (define-values (add0 add1) (apply values (make-adders 2))) (print (add0 0)) ;=> 0 (print (add1 0)) ;=> 1 My feeling about Python scope rules are mixed: in the beginning, I thought they were just broken, since they were not following my expectations (I don't know where those expectations were coming from, maybe from Pascal? I didn't know any functional language at that time, mah!). Later on, when I learned about the default argument tricks, I thought there was a logic in there, i.e. I may choose if I want to use the value of the "i" argument at the definition time or at the usage time explicitly and "explicit is better than implicit". However, now that I see that there are languages that implement the scope rule I would expect, and since I don't see a real life case where Python default of using the value of "i" as the usage time is useful, I am starting questioning them again. The only reason I see for the present state of the scope rules, is to discourage people from using closures and using objects instead. Which is not necessarely a bad thing, yes, but then I would need a better support from the language, and the ability to subclass FunctionType to be happy again ;) Michele Simionato From glc at well.com Sat Feb 28 14:27:28 2004 From: glc at well.com (Greg Chapman) Date: Sat, 28 Feb 2004 19:27:28 GMT Subject: Type emulation issues with new style classes References: Message-ID: On Sat, 28 Feb 2004 11:33:54 GMT, "Chris" wrote: >class Z(object): > value = 42 > def __hasattr__(self, name): > if name == '__int__': > return True > def __getattr__(self, name): > if name == '__int__': > return lambda: self.value The following allows your test case to work, but it may have various subtle problems. AddDynOper emulates __getattr__ semantics: the descriptor is not installed if the type already has an attribute of the given name: class DynOperDescr(object): def __init__(self, name): self.name = name def __get__(self, instance, typ): if instance is None: return self return instance.__getattr__(self.name) def AddDynOper(declcls, name): if not hasattr(declcls, name): setattr(declcls, name, DynOperDescr(name)) class Z(object): value = 42 def __getattr__(self, name): if name == "__int__": return lambda : self.value raise AttributeError(name) AddDynOper(Z, "__int__") --- Greg Chapman From kbk at shore.net Sun Feb 8 14:48:44 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 08 Feb 2004 19:48:44 GMT Subject: Clearing IDLE's screen? References: <4f0a9fdb.0402080107.3800b86e@posting.google.com> Message-ID: <87k72x73oj.fsf@hydra.localdomain> miki.tebeka at zoran.com (Miki Tebeka) writes: > I'd like to bind so that it will clear IDLE's screen (in the > interactive prompt). > Any pointers/suggetions? Try this: def clear(): for i in range(60): print If that is adequate, then you should be able to write an extension for IDLE which would bind this function to a key. Read .../idlelib/extend.txt for further information. Note that if you use this approach, previous entries into the Shell window can be retrieved by scrolling up and/or using the "View Last Restart / F6" feature. This is useful to recall code to the command line for re-evaluation. The downside is the buffer can get pretty large. You have to decide if that's a problem. It hasn't been for me. If you have an Edit window open, you can always close the Shell window occasionally and reopen it from the Run menu. If you really want to clear the buffer for the Shell window, then the Tkinter Text widget would have to be truncated. That involves a deeper understanding of IDLE, particularly EditWindow.py, OutputWindow.py, and PyShell.py. It is conceivable that it could be done as an extension. === I have been planning on implementing an integrated Shell Clear capability in IDLE 1.1 which would truncate the Shell Text widget. Just re-opening the Shell window would probably move it on the screen, so that is not very attractive. The question for the list is, should Clear be orthogonal to Reset or should Clear also do a Reset? Other comments? -- KBK From noemail at noemail4u.com Mon Feb 9 11:32:57 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Mon, 09 Feb 2004 16:32:57 GMT Subject: finding all sublists of list2 that are identical to list1 References: <3e96ebd7.0402090659.7948e06b@posting.google.com> Message-ID: On 9 Feb 2004 06:59:35 -0800, klaus_neuner82 at yahoo.de (Klaus Neuner) wrote: >Hello, > >the function given below returns all indexes of list2 where a sublist >of list2 that is identical to list1 begins. > >As I will need this function quite often, I would like to know if more >experienced programmers would agree with the way I defined the >function: > >- Is there a more efficient way to do it? (Apart from building >automata.) >- Is there a more elegant/Pythonic way to write the function? > >Klaus > > >def sublist(list1, list2): > if list1 == list2: > return [0] > elif len(list1) > len(list2): > return [] > else: > result = [] > shift = 0 > i = 0 > while shift <= len(list2)-len(list1): > if list1[i] == list2[shift+i]: > if i == len(list1)-1: > result.append(shift) > i = 0 > shift += 1 > else: > i += 1 > else: > i = 0 > shift += 1 > return result I don't know about it being Pythonic, but list comprehensions are always fun. This one's 10-20% faster (based on timeit results) than your code: def sublist(list1, list2): len1 = len(list1) rnge = xrange(len(list2)) return [i for i in rnge if list2[i:len1+i] == list1] If you need this for a specific purpose, you might be able to transform the data and try a different technique which would be executed internally at the "C" level. For example, if your list is always integers, you might be able to join them into a tab-delimited string and scan the string with a regular expression (unless you consider that building automata). The list doesn't have to be integers for the regex idea to be used--you just have to be sure the values in list1 contain no regex metacharacters, and that list1 and list2 don't contain your delimiter (tab in this example). If list1 contains regex characters, you need to escape them with a backslash first. It's possible that if you know something about the size of list1, you could use this information also, but without more details, I'm shooting in the dark. --dang From trevp at trevp.net Sat Feb 28 03:17:18 2004 From: trevp at trevp.net (Trevor Perrin) Date: 28 Feb 2004 00:17:18 -0800 Subject: Pure Python HTTPS Server References: <7x4qtcozv5.fsf@ruckus.brouhaha.com> Message-ID: <47e891f1.0402280017.5f8af771@posting.google.com> Paul Rubin wrote in message news:<7x4qtcozv5.fsf at ruckus.brouhaha.com>... > Trevor Perrin writes: > > Are you and Paul still looking at adding ciphers to stdlib? That > > would make me really, really happy :-).... > > Do you mean me? Yes! Sorry, I was typing quickly. > I proposed a standard block cipher API and wrote a > sample implementation last year, I like that API. I wonder if there's any performance issues in separating the codebook from the mode-of-operation, but I haven't thought about that much. > but had to set it aside temporarily > because of other commitments at the time. Between then and now I > heard that the distro maintainers decided they weren't willing to put > ciphers into the stdlib because they were concerned it would create > legal obstacles importing Python into certain places. They didn't > seem to mind that the existing rotor module already creates those same > issues, or that just about every web browser these days contains an > SSL stack, so they only need to be concerned about places where it's > illegal to use web browsers. Yeah, I thought things were pretty liberalized these days. US Export isn't a problem. I guess a few countries still have import issues, but providing a no-crypto distribution that omits a few modules seems like it would take care of that. > I haven't pursued the issue since then, > but I guess I can do some more work on the code now. I'd be happy to help, or cheerlead, or anything. Is this something that belongs on the python-crypto list? Trevor From jcarlson at nospam.uci.edu Mon Feb 2 00:01:19 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 01 Feb 2004 21:01:19 -0800 Subject: OT: why do web BBS's and blogs get so slow? In-Reply-To: <7x1xpece0g.fsf@ruckus.brouhaha.com> References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> <7xk736s7av.fsf@ruckus.brouhaha.com> <7x1xpece0g.fsf@ruckus.brouhaha.com> Message-ID: > OK, I looked at a few typical user pages. I might look at the code > sometime (I think it's in Perl though, yecch). But I don't understand > about needing to do a lot of processing for each page. The ones I > looked at looked like they could have been served static entirely from > cache, updated only when someone actually posts a new entry or comment. > Maybe it's doing that, which would certainly make it fast. Quoting the latest news post (http://www.livejournal.com/users/news/) "We now host over 2,000,000 users, roughly half of which are active in some way." 'Active in some way' are those who visit and check their friends page, those that post updates to their own livejournal, or those that post replies to entries/replies on livejournals, I believe in the last month. 30k visitors/day, many doing more than one thing when they visit (check their friends page, post some replies, update their own livejournal, etc.), everyone hitting different parts of the database, many causing database updates (without updates, livejournal is worthless), etc. No offense, but I'd love to see you write a BBS/Blogging software that does that - in any language. - Josiah From cpl.19.ghum at spamgourmet.com Wed Feb 4 10:35:10 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 4 Feb 2004 16:35:10 +0100 Subject: global variables in module References: Message-ID: Zunbeltz, > MyApp(wxApp): > How can i use cf in other modules of the program. Did I need declare cf > global, or make it a module variable, ... Any hint, please is used the following approach: 1) defining one module named ReportGlobals loggedInUser="nasenbaer" workerQueue=Queue.Queue() there all varibles which are "konfiguration related" are defined, also "programm global queues", "error loggers", "database connection pool" All these variables are defined as module level variables (on "indent 0" :))) ) 2) in all modules of the programm I use import ReportGlobals as gl print "You are %s" % (gl.loggedInUser,) HTH Harald and access the From fidtz at clara#spam#.co.uk Wed Feb 11 10:36:23 2004 From: fidtz at clara#spam#.co.uk (DomF) Date: Wed, 11 Feb 2004 15:36:23 -0000 Subject: iterating over a list and printing References: Message-ID: <1076513796.95697.0@despina.uk.clara.net> "Bart Nessux" wrote in message news:c0dhev$2gp$1 at solaris.cc.vt.edu... > ip_list = [] > inputFile = file('ips.txt', 'r') > ip_list.append(inputFile.read()) This line just reads the whole file into the first element of the list. Put "print ip_list" here to confirm this to yourself. You need to loop over the file with the optional "size" parameter set or by using inputFile.readlines() if ips.txt is one IP address per line. Dom > inputFile.close() > for i in ip_list: > print "/sbin/ifconfig %s netmask 255.255.252.0 broadcast > 128.173.123.255 up" %i > > The last line does not work. It prints the first part (/sbin/ifconfig), > then the entire list of ips, then the second part (netmask 255.255.252.0 > broadcast 128.173.123.255 up). Any ideas on how to fix this? The desired > results are to print a line for each IP. > > /sbin/ifconfig IP1 netmask 255.255.252.0 broadcast 128.173.123.255 up > /sbin/ifconfig IP2 netmask 255.255.252.0 broadcast 128.173.123.255 up > etc... From alanmk at hotmail.com Thu Feb 12 08:00:30 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 12 Feb 2004 13:00:30 +0000 Subject: Simple allowing of HTML elements/attributes? References: Message-ID: <402B78EE.56B854C@hotmail.com> [Leif K-Brooks] >>> I'm writing a site with mod_python which will have, among other >>> things, forums. I want to allow users to use some HTML (, >>> ,

, etc.) on the forums, but I don't want to allow bad >>> elements and attributes (onclick, if the username is stored in a browser cookie. More generality you can simulate a client side include: where the server responds to requests for username.js with document.write("hi [username]") after determining the username from the sent cookie. The server to use cache control headers very aggressively to stop the browser from showing the wrong name if someone logs off and then logs back in as another user. I remember cackling somewhat madly when I came up with this, because it was after having spent about a whole day coding up generating a messy page dynamically and realizing I could do the above instead (more complicated situation of course). From opstad at batnet.com Tue Feb 24 17:55:29 2004 From: opstad at batnet.com (David Opstad) Date: Tue, 24 Feb 2004 14:55:29 -0800 Subject: Linguistically correct Python text rendering References: Message-ID: In article , "Mike Maxwell" wrote: > Isn't this a function of whatever app you're running Python code inside (a > terminal or something)? E.g. could you take the output of your Python > program as a file and display it in Yudit or a Pango app? In an interactive Python session on the Mac, the terminal window can display Asian or accented Latin with no problem, so that: >>> firstCJKChar = u"\u4e00" >>> print firstCJKChar.encode('utf-8') gives the correct output, the Chinese character "yi". (The terminal's defaults are for UTF-8 text display) All I'm wondering is whether this odd asymmetry (between parts of Unicode that display correctly with no further work and parts of Unicode that need more active processing) is something that could be addressed by adding more sophistication to Python's own output formatting. The alternative is, as you suggest, to export Unicode text and open it with another application, but I want Python to shine for all languages by default! Dave From bob at redivi.com Thu Feb 26 17:47:50 2004 From: bob at redivi.com (Bob Ippolito) Date: Thu, 26 Feb 2004 17:47:50 -0500 Subject: Pure Python HTTPS Server References: <7xd6814gzi.fsf@ruckus.brouhaha.com> Message-ID: <2004022617475016807%bob@redivicom> On 2004-02-26 17:24:01 -0500, Paul Rubin said: > "Mikey At Work" writes: >> Does anyone know of any HTTPS servers available that are totally >> written in Python? Thanks. > > That depends on what you mean by "pure". You can do it with the various > OpenSSL Python bindings that have been written. I don't think anyone > has ever written a complete SSL stack in Python. I've toyed with the > idea but it would be a lot of work. Have you seen: http://trevp.net/tlslite/ ? From premshree_python at yahoo.co.in Thu Feb 19 06:16:08 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Thu, 19 Feb 2004 11:16:08 +0000 (GMT) Subject: Socket Programming in Python Message-ID: <20040219111608.5951.qmail@web8301.mail.in.yahoo.com> For the uninitiated: "Socket Programming in Python" at evolt.org: http://evolt.org/article/Socket_Programming_in_Python/17/60276/index.html ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Insurance Special: Be informed on the best policies, services, tools and more. Go to: http://in.insurance.yahoo.com/licspecial/index.html From newsgroups at jhrothjr.com Thu Feb 12 09:40:21 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 12 Feb 2004 09:40:21 -0500 Subject: does python support mvc architecture References: Message-ID: <102n468gt8klr44@news.supernews.com> wrote in message news:f046efac.0402120627.948b7ed at posting.google.com... > Hi > Does python support MVC architecture? Java has register & notify > obsever methods in javax.util . Does python has these functions. If > not then how to register the views with the models & how to notify the > views that the model has been updated?? I don't know of a notifier class in the standard library, but it's not all that difficult to write one. This is the one I am currently using: ----------------------------------------------------- # module Notify class Notify(object): def __init__(self): self.listenerList = [] def sendMessage(self, event): for callback in self.listenerList: callback(event) return def addListener(self, callback): self.listenerList.append(callback) def removeListener(self, callback): self.listenerList.remove(callback) ----------------------------------------------------- callback has to be a callable of some kind, a bound method is perfectly acceptable and that's what I use. Works great. John Roth From fumanchu at amor.org Mon Feb 23 18:51:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 23 Feb 2004 15:51:48 -0800 Subject: subject with smtplib? Message-ID: Jeff Sandys wrote: > Can you include a subject with sendmail using smtplib? Hi, Jeff, Try starting your message "body" with header lines, a la: To: sandys at juno.com From: fumanchu at amor.org Subject: Putting subjects in smtp messages Robert Brewer MIS Amor Ministries fumanchu at amor.org From mcfletch at rogers.com Wed Feb 25 06:13:47 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 25 Feb 2004 06:13:47 -0500 Subject: Locate python home In-Reply-To: References: Message-ID: <403C836B.3050502@rogers.com> Thomas Aanensen wrote: >>Never trust the assumption: >> >> >>> import os >> >>> os.path.isfile( os.path.join(os.path.dirname( sys.executable ), >>'python.exe' )) >>False >> >>(This is from within Pythonwin, which has its executable elsewhere). >> >>It's a good idea to check and see if the file really does exist. If it >>doesn't, either raise an error to tell the user to figure out what's >>wrong, or use the executable as given, (possibly checking/raising the >>error *only* if the executable is named pythonw and you can't find the >>python executable, though that would still have you running PythonWin in >>the above example (checking for "not named python" would be safer)). >> >> > >What about using PYTHONHOME as environment variable. Is that appropriate? > > Well, doesn't exist on my win2k machine, at least. Using sys.executable with some defensive programming is probably what you really want. Just *check* the assumptions and punt if there's a problem (with a useful error message). 99% of the time you'll be fine, and the other 1% of the time people are being silly anyway (such as running the script from Pythonwin) and just need to be knocked up-side the head with a cloodle-stick :) . "Can't find python.exe in executable's directory %r, and the running executable is not named python.exe, please use python.exe to run this script" or "Can only find pythonw.exe in directory %r, this script needs access to python.exe, please contact technical support to get a full python installation" might be suitable error messages. Enjoy yourself, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From manders2k_NOSPAM at yahoo.com Wed Feb 4 12:05:24 2004 From: manders2k_NOSPAM at yahoo.com (manders2k) Date: 4 Feb 2004 09:05:24 -0800 Subject: different string representation (buffer gap) References: <7xr7xbfjbe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xr7xbfjbe.fsf at ruckus.brouhaha.com>... > You can do some of that with the array module, but Python's regexp > library doesn't give any way to search backwards for a regexp, so that's > another problem you'll face trying to write an editor in Python. Yeah, I have a feeling that it might be easier to code up the buffer in C/C++, and embed it in the interpreter. I'm not sure how much of a performance bottleneck having this very low-level component written in python will be on modern machines; probably not such a big deal. Writing a buffer class and fiddling with pointers and whatnot actually sounds easier to do in C++ than in emulating this style of thing in Python (then again, I'm a heck of a lot more comfortable with C++ than Python at this point, so that might not speak to the difficulty of the task). What I guess I wish were the case is that I could implement the "string interface" on my BufferGap, so that everywhere that Python (at the C API level) expects a string, a BufferGap could be used instead. That way, all the libraries that inspect and operate on strings would work transparently, without having to be recoded (copy / paste, end up with a lot of mostly identical, redundant code) to operate on this other string representation. Maybe this just isn't possible with the current C-Python implementation. I suspect it would be with many possible C++-Python implementations, but we don't have one of those lying around so... I'm pretty sure that for modest size buffers (even a megabyte of text), copying the contents of the buffer into a python-string representation before operating on it with python-libraries would be transparently fast. It just seems...wasteful, and potentially very bad news if someone ever tried to do a regex search on a buffer that occupied more than half of the physical memory of the machine or somesuch. From michele.simionato at poste.it Sat Feb 21 04:47:22 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 21 Feb 2004 01:47:22 -0800 Subject: hmm, lets call it: generic __init__ problem References: <95aa1afa.0402180908.1f7a8b6c@posting.google.com> Message-ID: <95aa1afa.0402210147.782625c7@posting.google.com> paul k?lle wrote in message news:... It came to my mind that you may want to read this post of mine (how to make __init__ calling super automagically): http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=2259b0e2.0212101101.2d93729e%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dautoinit%26btnG%3DCerca%2Bcon%2BGoogle%26meta%3Dgroup%253Dcomp.lang.python.* It does not solve your problem but it can give you some idea. HTH, Michele From max at ucmg.com.ua.remove.it Wed Feb 11 02:43:59 2004 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Wed, 11 Feb 2004 09:43:59 +0200 Subject: communicating with Java (from Python) In-Reply-To: References: Message-ID: Harry George wrote: >>I want to communicate my Python application with the Java one. >>The most obvious choice is XML-RPC, but ... I wonder about something >>more pythonic and powerful, like pyro. > > There was a thread to this topic a few weeks ago and XML-RPC came up > as the best bet, even for on-the-same-box communication. OK, thanks. From jepler at unpythonic.net Thu Feb 26 08:50:54 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 26 Feb 2004 07:50:54 -0600 Subject: Antwort: Re: Some language proposals. ['LBBW': checked] In-Reply-To: References: Message-ID: <20040226135053.GD28636@unpythonic.net> On Thu, Feb 26, 2004 at 10:36:17AM +0100, Holger Joukl wrote: > Well, there is no bug at all, as far as I can see. Runs in my interpreter. > Cheers > Holger I think that the person you were replying to (whose name you kindly removed, so I have no idea who it was) was trying to refer to this behavior: >>> class A: pass ... >>> def f(): pass ... >>> A.f = f; assert A.f is f AssertionFailure The statement "A.f = f" sets A.__dict__['f'] = f. The statement 'A.f is f' calls type(A).__getattribute__, which returns an "unbound method object". I won't argue that this behavior isn't surprising (since apparently it surprised somebody) but it's because of this behavior that the following code works: class A: def f(self): pass a = A() A.f(a) .. if A.f returned something other than an unbound method object, then it would also be legal to call 'A.f(0)' when 0 is not an instance of A. If the OP wants to add a function to A that is not treated as a normal method, then he can use the 'staticmethod' wrapper. >>> A.f = staticmethod(f) >>> A.f is f 1 Jeff From tjreedy at udel.edu Thu Feb 5 15:50:41 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Feb 2004 15:50:41 -0500 Subject: integer overflow References: <_LKdnSsPRbRZ77_dRVn_vQ@news.rockefeller.edu> Message-ID: "Chad Haynes" wrote in message news:_LKdnSsPRbRZ77_dRVn_vQ at news.rockefeller.edu... > Michael Hudson wrote: > > > Chad Haynes writes: > >> lst[0] = num > >> > >>produced this error > >> > >> OverflowError: unsigned short is greater than maximum > >> > >>The number was around 65536 so it makes sense that it would overflow a > >>short, but why is it trying to force it into a short integer? > > > > > > Is lst an array.array('h') or something (numarray...)? > > Nope, its just a regular list Suggestion: open interactive window, type in minimal lines of code needed to reproduce error, then cut and post entire window, including header that identifies your particular binary. Also mention the source of binary (who compiled, you or someone else). TJR From john.burton at jbmail.com Sun Feb 15 13:32:06 2004 From: john.burton at jbmail.com (John Burton) Date: Sun, 15 Feb 2004 18:32:06 -0000 Subject: IPv6 question References: <9r14g1-1vu.ln1@neon.jbmail.com> Message-ID: Martin v. L?wis" wrote in message news:c0oc6j$592$01$1 at news.t-online.com... > John Burton wrote: > > If I need to create an IPv4 socket and IPv6 socket and listen on both that > > doesn't > > seem to work. > > > > sock4 = socket(AF_INET, SOCK_STREAM) > > sock4.bind(('', 12345)) > > sock6 = socket(AF_INET6, SOCK_STREAM) > > sock6.bind(('', 12345)) > > > > I get an error that the address is already in use on the 2nd bind even > > though it's to a different > > socket type. This is on linux. > > Has anyone got this to work? Or am I missing something? > > You are missing something important. According to RFC 2553, a PF_INET6 > socket can be used for IPv4 communication, by means of IPV4_MAPPED > addresses (::FFFF:). So an application openening a > PF_INET6 listening socket will accept both IPv4 and IPv6 incoming > connections. > > If you want a socket that listens only on IPv6 connections, you > need to set the IPV6_V6ONLY socket option. In your case, it is > sufficient to just not create the IPv4 socket. When clients connect > through IPv4, you will find that the peername(2) of the socket > is an IPv4-mapped address. You should never ever transmit such > an address over the wire; it is meant for local use only. Thank you for your reply. That makes a lot of sense and I've had another try and it does work as you suggest. (I was thinking that Ipv6 sockets were not receiving connections via ipv4 because as you say they are reporting an ipv6 style mapped address) I've got a horrible feeling it doesn't work like this on windows though (my python build on windows doesn't seem to support ipv6 so I can't try it) From wfolta at netmail.to Sun Feb 15 15:38:10 2004 From: wfolta at netmail.to (Wayne Folta) Date: Sun, 15 Feb 2004 15:38:10 -0500 Subject: mailing list problems? In-Reply-To: References: <20040214221839.GA22649@nl.linux.org> Message-ID: > I have today seen only 5 mailing list messages to the python-list. > I see >30 messages in c.l.py newsgroup. > Do other people experience problems as well, or do I have a problem at > my > end? No, I've only seen a handful of messages in the last couple of days, too. It's strange to see more messages in the Mac Python list than in this one. (My domain is ".to", but I'm in the US, if that makes a difference.) From anand at easi.soft.net Thu Feb 26 00:37:12 2004 From: anand at easi.soft.net (Anand K Rayudu) Date: Thu, 26 Feb 2004 11:07:12 +0530 Subject: Python: GUI Builder Message-ID: <403D8608.40103@easi.soft.net> Hi All, I am new to python & want to build some GUI dialogs. Can some one please suggest some document reference. I am hoping that standard python install will have some GUI development modules & GUI builder in built. I have python 2.3.3. Can some one please suggest Thanks in advance. Anand From scrutinizer at gmx.at Sun Feb 1 11:46:54 2004 From: scrutinizer at gmx.at (Francesco) Date: Sun, 01 Feb 2004 17:46:54 +0100 Subject: wxPython issues Message-ID: Hello, I have some questions: 1. this is in Mainthread: def OnOverwriteDlg(self, event): print "OnOverwriteDlg" dlg = COverwriteDlg () dlg.m_strInfo = g_strTitle g_nGuiResult = dlg.ShowModal() ??? g_objGUISyncSemaphore.release () (not working) that is in worker thread: print "DlgOverwriteThreadsafe" g_strTitle = _("Overwrite %s ?") % strFile event = wxCommandEvent () event.SetEventType (wxEVT_COMMAND_BUTTON_CLICKED) event.SetId (19999) pFrm = wxGetApp().GetFrame() if(pFrm): wxPostEvent(pFrm, event) #wxpython: do not use this ????#wxYield() #//wait for GUI to end with owerwrite dialog print "before" ???? g_objGUISyncSemaphore.acquire() print "after" print g_nGuiResult return g_nGuiResult How can I get, that in worker thread on "before" is waiting, until the dialog in mainthread is finished? wxYield, Semaphore, Mutex, ... is all a bit strange for me. Is there any website dedicated to this issues? 2. I want to get a list icons from the windows shell folders and put it in the wxPython List control. How can I accomplish this? 3. menuAdd(self, pMenuFile, _("Exit") +"\tAlt+F4", _("Exit"), self.OnClose, wxID_CLOSE) def OnClose(self,event): #store startup preferences the onclose is called by ending the program via menu or Alt-F4. but if i quit the program with the mouse right above, the onclose will not be called. Many thanks in advance, -- Francesco From PeterAbel at gmx.net Mon Feb 16 08:36:04 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 16 Feb 2004 05:36:04 -0800 Subject: __del__ doesn't work References: <21064255.0402151141.51a38fed@posting.google.com> Message-ID: <21064255.0402160536.5cdefe5a@posting.google.com> PeterAbel at gmx.net (Peter Abel) wrote in message news:<21064255.0402151141.51a38fed at posting.google.com>... Thank you guys for your quick answers. Back reference is the problem. It's done in a not quite obvious way, so I didn't realize it immediately. I'll try to find a workaround either by weakref or anything else to avoid this. Many Thanks Peter From brice.vissiere at costes-gestion.net Thu Feb 12 10:59:21 2004 From: brice.vissiere at costes-gestion.net (Brice Vissi?re) Date: 12 Feb 2004 07:59:21 -0800 Subject: Splitting a DOM Message-ID: Hello, I would like to handle an XML file structured as following ... ... ... >From this file, I want to build an XML file for each STEP block. Currently I'm doing something like: from xml.dom.ext.reader import Sax2 from xml.dom.ext import PrettyPrint reader = Sax2.Reader() my_dom = reader.fromUri('steps.xml') steps = my_dom.getElementsByTagName('STEP') i=0 for step in steps: tmp = file('step%s.xml' % i,'w') tmp.write('\n') PrettyPrint(step , tmp , encoding='ISO-8859-1') tmp.close() i+=1 But I'm pretty sure that there's a better way to split the DOM ? Thanks for any suggestion provided. Brice From rmb25612 at yahoo.com Sun Feb 15 06:06:58 2004 From: rmb25612 at yahoo.com (Richard James) Date: 15 Feb 2004 03:06:58 -0800 Subject: [ANN] Atox 0.2 released References: <2c60f0e0.0402141444.3d0b785f@posting.google.com> Message-ID: <2c60f0e0.0402150306.78e188ee@posting.google.com> Istvan Albert wrote in message news:... > Richard James wrote: > > > But, I wasted a lot of valuable time and credibility trying to sell > > NOGUI uh... ANYGUI for in house rapid MS Windows gui development to my > > boss and co-workers. > > > > I don't know how many times I said: I'm sure the next release is just > > around the corner. And it will run on ANY gui that our customers have > > installed!!!!! > > The question that pops into one's mind here is why would you promise > things that are completely out of your control? I understand your > frustration with unfinished or dead projects but let's remember that > for each successful project there will be hundreds that die off and there > is nothing wrong with that. Survival of the fittest. > > i. Well it was part of my strategy of getting Python accepted into the work place as a serious work tool. The early versions of ANYGUI were very promising in the simplification of GUI interfaces. The command line interface may be second nature in the Linux hacker world. But in the "real" MS Windows business world it is not a "production level" interface. The true power of Python is in being able to do tasks, like lists and dictionaries, without thinking about it very much, and without fighting wild C pointers, or engaging in "in house" C++ class warfare over what type of list classes and or structures we use this week. Python is productive, but Python guis are a weak point, as is compilation. (Now really! How different are interpreters and linkers? Other than everybody loves to design and write interpreters and few have ever written a linker. My "FREE radical" idea is to define and generate bytecodes that can be both interpreted and linked. Another one is to dump all the C++ gui paradigms and get the assembly language game programmers involved in creating a FAST gui programming language you can use without spending 4 years reading the unclear out of date documentation. Does QT really need 5000 plus widgets? Or would a general purpose widget design language be better? I know gui programming keeps many gui gurus employed, but doesn't "survival of the fittest" mean constant challenge of the old guard? Flame away at me. But the Emperors in these two programming areas have no clothes. You can only wrap so many abstraction layers on top of interface layers before you strangle yourself. And don't get me started on the bizzare flavor of the week internet browser html flash asp js java notjava C# mess!) Programming productivity matters, the faster you can produce a finished Windows program the happier the customer is. And you get all those widgets you buy delivered to the store on time. Instead of half built widgets laying on a stalled production line, while the packaging machine GUI is locked up over night. The academic side of the Python world may not appreciate the "time is money" concerns. But if time didn't matter, I would write Windows apps in X86 Assembly and get 100X perfomance increases over the slow wxPython dll. There still are a lot of older slower X86 machines running 24/7 on the manufacturing floor. You don't need a 4GHZ machine to stamp date codes. Waiting 2 minutes for wxPython to load while the boss stares at the back of your neck makes Python look very bad. Gui4Cli pops right up and can talk back and forth to other G4C guis and even other native Windows apps that are running in the background. And adding a custom gui for a monitoring program, to alert production operators to catch a flakey machine in the act, is now childs play instead of a 40 hour C++ gui programming nightmare weekend. So I gambled on ANYGUI and lost, up until that point, the Python community had not let me down. ANYGUI had a snazy graphic on it's webpage and an active user and developers list going. And many people seemed to be excitedly involved at the time. More than anything, the book notice posted on the ANYGUI site in August 2002 sealed the deal that ANYGUI was a "REAL" product. I showed the "Practical Python" book to my boss. He liked the look of it. Can I get a refund? At least rename it "Mythical Python". And there has been NO notice on the website that the ANYGUI project has been abandoned, just a "stay tuned" notice. The developers list seems to have been abandoned by it's developers in August 2003. Doesn't this "current" 2004 advert look like the "fittest" having survived??? ---------- >From Barnes and Noble ---------- Practical Python is an indispensable guide for developers intent on learning what they need to know to master the Python language. - Author is well known for his online Python tutorials, Instant Python and Instant Hacking, and is the founder and lead developer of Anygui, a respected Python GUI unification project - Ruthlessly focused on providing practical Python instruction, foregoing those topics not of interest to mainstream developers ----------- "a respected Python GUI unification project"??? Was all this just smoke and mirrors to sell a $50 book? Is XML just the next hot book topic? As a contrasting example, the pycurl webpage looked like a twenty minute hand coded html job, yet pycurl has proven to be a reliable and very useful aspect of the Python programming experience. You can't judge a book by it's cover or a project by it's webpage design or even a project by it being in an authoritative looking book. So that is why I suggested some type of offical ranking page for Python projects. Maybe others can avoid wasting time and effort in the future. The only consequence was that we were stuck with the SOW (Same Old Way) method for a few more months. Until we found the FREE and well documented Gui4Cli. We can now make simple gui changes in the Gui4Cli script language in under half an hour. Most GUIs are also under 20K bytes in size and using pycurl you can update the production floor machine in seconds. For low to medium gui complexity Python with Gui4Cli gets the job done. And it helps in testing out ideas that can be later turned into full power C++ guis to handle higher data collection and control rates. So it turned out ANYGUI's failure to thrive, was as Martha Stewart says: "a very good thing". And now we almost don't know how we ever did things before we had Python and Gui4Cli! -- R.J. From jcarlson at nospam.uci.edu Thu Feb 19 16:41:29 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 19 Feb 2004 13:41:29 -0800 Subject: PEP-315 ("do" loop) In-Reply-To: References: Message-ID: > Amen to that! I think this is only a matter of education. People > should be told that 'while 1' construct is a good, simple, pythonic > way to do the thing. They are often prejudiced, thinking that there is > something 'wrong' with the construct. Hearing that it's ok to do > things this way can actually be very liberating: there is no reason to > feel guilty, and they will quite soon learn to appreciate how natural > and versatile the construct is. > > Naming it 'loop' would drive the point even further, of course. The nice thing about while is that it is general. You can put anything that returns some value that can be tested for truthfulness, even 1 (as we like to do). Changing the name alters the linguistic interpretation of what goes on. Using "loop" would suggest a subsequent "until": loop: #setup #loop internals until | Which is clearer, but adds two keywords. Though, like I said before, the while setup is perfectly understandable. - Josiah From pinard at iro.umontreal.ca Sun Feb 22 18:25:05 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sun, 22 Feb 2004 18:25:05 -0500 Subject: Where can I post a new debugger? In-Reply-To: <40392479@news.bezeqint.net> References: <6ee58e07.0402221348.46171b05@posting.google.com> <40392479@news.bezeqint.net> Message-ID: <20040222232505.GA12140@titan.progiciels-bpi.ca> > > "Ziaran _" wrote in message > > > I have written a new debugger. > > > I think people will find it useful. > "Lothar Scholz" wrote in message > > What is so different from the existing ones ? [Ziaran] > http://ziaran.freehosting.net/ An URL is hardly an explanation, and alone, hardly an English sentence. People should not have to start a browser merely to figure out an email. You think people will find your new debugger useful? Good for you! Now, if you want us to think the same, you should tell us a little more. Once interested, then we may start a browser :-). -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From dietrich at zdome.net Sun Feb 15 20:31:15 2004 From: dietrich at zdome.net (Dietrich Epp) Date: Sun, 15 Feb 2004 17:31:15 -0800 Subject: [OPINION] - does language really matter if they all do the samething? In-Reply-To: References: <69A0D4AB81C51447AD6BA387782B8D64093D8A@midl-mail4.etcconnect.com> <028FD9F0-4E01-11D8-BB78-0003934ACDEC@zdome.net> <4011C497.1040302@prescod.net> Message-ID: I was wrong about that example. I thought I made that clear in a later post. My point was that some paradigms are more Pythonic than others. I think the only good case I made was the 'choose-random' table. I don't generally feel constrained by Python, but Python is simply not the right tool for every job. When I want to write a program, I first think "How will this program work?" and then "What language most naturally expresses this idea?" With the 'choose-random' problem, my first idea was to write a Python program. I could not easily express my idea in Python. I could express my idea in Lisp, therefore, I used Lisp. I believe this decision to be rational. In this case, I felt very constrained by Python. My offer still stands: if anyone can express my idea in Python (not counting future versions of Python) in a way that is approximately as simple as how I expressed it in Lisp, I will post a picture of myself with "Python Rulz" written on my forehead. Someone accused me of not using Python to its full potential. I took that as tantamount to accusing me of being a bad programmer. I had a point, gave a good example, a bunch of bad examples, and tried to avoid making it personal. If anyone wants to go back and show how stupid some of my examples were, let me save you from wasting your precious free time: THOSE EXAMPLES WERE STUPID. Now that there is NO DISAGREEMENT, I don't see how beating this poor dead horse is going to accomplish anything even by Usenet standards. All those posts pointing out how stupid those examples were were all regurgitating the same information anyway. As for the Lisp example, I have yet to see a Python implementation that stands up to even the most trivial inspection, so I don't expect to defend it any further. In effect, the most productive thing that this thread can now accomplish is personal attacks and holy wars. In order to reduce the amount of traffic on this list, I preemptively call anyone responding to this message either wrong or troll, so I don't have to explicitly write that as a response. The previous paragraph is not intended to be serious. From miki.tebeka at zoran.com Mon Feb 16 06:48:50 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 16 Feb 2004 03:48:50 -0800 Subject: Stopping a program References: Message-ID: <4f0a9fdb.0402160348.7ee6760@posting.google.com> Hello Thomas, > A follow up to the question posed above: I discovered sys.exit() and > played around it. I find that it exhibits different behaviors > depending on whether the program is run from IDLE or fron the command > line. sys.exit just raises SystemExit exception. IDLE catches this exception and shows the traceback as it does to every other exception (try `raise OSError' in IDLE). In the command line raising SystemExit will quit the interpreter. If you just click on the .py file from the explorer it will close after executing the program. If you want to view what happened add `raw_input()' just before raising SystemExit. For most cases raising SystemExit does what you want. Just remember the IDLE does not emulate the command prompt. HTH. Miki From theller at python.net Tue Feb 17 03:29:18 2004 From: theller at python.net (Thomas Heller) Date: Tue, 17 Feb 2004 09:29:18 +0100 Subject: Installation problem on Windows 98 References: <87y8r2l73x.fsf@hydra.localdomain> <4qtqi1wt.fsf@python.net> Message-ID: "Neil Hodgson" writes: > Thomas Heller: > >> It is getting off-topic, but I still believe that pythonw.exe should be >> improved to show errors in a console window which opens as soon as the >> first output is written to sys.stderr (and sys.stdout also, maybe). > > So if it is being redirected or captured by another application, such as, > say, SciTE, then an extra console window will open up? No, that is not the intent. Can this case be detected somehow? Thomas From Mike at DeleteThis.Geary.com Fri Feb 6 02:15:30 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 5 Feb 2004 23:15:30 -0800 Subject: where should config files go in Windows? References: Message-ID: <1026fokdfis287b@corp.supernews.com> > >See the MSDN documentation for the various folders which are defined. > > > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/pl atform/shell/reference/functions/shgetfolderpath.asp > Thank you very much! That's just what I wanted. I'll put preferences > \TUIPrefs, optional user additions in \TUIAdditions > and optional shared additions in \TUIAdditions. I'd like to suggest creating only a single folder under Application Data, with additional folders inside it for your specific needs. The usual convention is to create a folder with your company name, then additional folders inside that for each product, and finally folders inside those for things like your TUIPrefs and TUIAdditions. Also, make careful note of the difference between Application Data and Local Settings\Application Data. On most machines, it doesn't matter which of those you use. But if someone uses "roaming profiles", then you need to choose which of those folders to use. Application Data is part of the roaming profile, and it gets copied from a server when the user logs in, and back to the server when the user logs out. Local Settings\Application Data resides strictly on the local machine. -Mike From guettli at thomas-guettler.de Tue Feb 17 10:25:44 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 17 Feb 2004 16:25:44 +0100 Subject: Compiling python scripts to native code ?? References: Message-ID: Am Tue, 17 Feb 2004 08:43:15 -0800 schrieb Fred Mailhot: > Hi... > > Is there any way to do this for *nix ?? Pointers to resources and/or FAQS > would be much appreciated. Why do you want to do this? - Improve speed - hide your source code ... thomas From peter at cendio.se Tue Feb 17 13:38:33 2004 From: peter at cendio.se (Peter Astrand) Date: Tue, 17 Feb 2004 19:38:33 +0100 (CET) Subject: [Announce] pyobfuscate In-Reply-To: <40323466.8050805@prescod.net> Message-ID: > It is not entirely uncommon to write python code that depends on exact > method or variable names: > > if hasattr(obj, "somemethod"): > doOneThing() > else: > doSomethingElse() > > Will the pyobfuscate break code like this? Currently, pyobfuscate does not change method names. So this should work. There are probably other cases with hasattr() and getattr() that fails, though. -- Peter ?strand www.thinlinc.com Cendio www.cendio.se Teknikringen 3 Phone: +46-13-21 46 00 583 30 Link?ping From pantsmetalkid at charter.net Sat Feb 21 00:59:50 2004 From: pantsmetalkid at charter.net (John) Date: Sat, 21 Feb 2004 00:59:50 -0500 Subject: New user needs help References: <103dqa9m48nj792@corp.supernews.com> <64CZb.19719$wD5.7887@nwrddc03.gnilink.net> Message-ID: <103dsrej8i54s3a@corp.supernews.com> Thank you very much. This solved the problem. I now see where the problem was. This was driving me bonkers! I'm sure I will post here frequently so thanks in advance for everyone's help. "omission9" wrote in message news:64CZb.19719$wD5.7887 at nwrddc03.gnilink.net... > John wrote: > > > I am new to using Python. Everytime I run this program it prints "The lowest > > common factor is 0", no matter what numbers I use. Can anybody see anything > > wrong with my program? Thanks in advance. > > > > > > > > def getnum1(a): > > a = input("What is the first number?") > > if a == 0: > > getnum1(a) > > def getnum2(b): > > b = input("What is the second number?") > > if b == 0: > > getnum2(b) > > def euclid(num1, num2, num3, num4): > > if num1 < num2: > > num3, num4 = num1, num2 > > num1, num2 = num4, num3 > > euclid(num1, num2, num3, num4) > > elif num2 != 0: > > num3, num4 = num1, num2 > > num1 = num4 > > num2 = num3 % num4 > > euclid(num1, num2, num3, num4) > > else: > > print "The lowest common factor is: ", num1 > > a = 0 > > getnum1(a) > > b = 0 > > getnum2(b) > > x, y = 2, 100 > > euclid(a, b, x, y) > > This is a nice simple example of what is called "scope" and how it can > trick a beginner. > Put as simply as possible,"a" and "b" are actually defined twice. Once > "locally" in the getnum functions and another time "globally" . When you > set a and b to the user input in the functions the other a and b have no > idea about this assignment. Below is a slight revision which return the > a and b set by the user back to where they are called. By putting a > simple print statement in the script you can see where the values are > set and that can help you. > I hope that helps. There is probbaly a couple of other changes you could > make as well but nothing too major, in my opinion. > > > def getnum1(a): > a = input("What is the first number?") > if a == 0: > getnum1(a) > return a > def getnum2(b): > b = input("What is the second number?") > if b == 0: > getnum2(b) > return b > def euclid(num1, num2, num3, num4): > print num1, num2, num3, num4 > if num1 < num2: > num3, num4 = num1, num2 > num1, num2 = num4, num3 > euclid(num1, num2, num3, num4) > elif num2 != 0: > num3, num4 = num1, num2 > num1 = num4 > num2 = num3 % num4 > euclid(num1, num2, num3, num4) > else: > print "The lowest common factor is: ", num1 > a = 0 > b = 0 > a=getnum1(a) > b=getnum2(b) > x, y = 2, 100 > euclid(a, b, x, y) > From peter at engcorp.com Thu Feb 26 09:36:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Feb 2004 09:36:22 -0500 Subject: Is MVC architecture applicable for web environment?? References: Message-ID: <403E0466.59781611@engcorp.com> ketulp_baroda at yahoo.com wrote: > > Is the true mvc architecture ( with observer-observable pattern as > implemented in JAVA) not applicable for web environment?? > I mean to say that the HTTP protocol is request/response based so > there is no notion of an "event" being notified ... > whereas the observer-observable pattern is based on event. Google might help you: http://www.google.ca/search?q=mvc+architecture+web From nuffsaid at phreaker.net Tue Feb 3 05:48:36 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Tue, 03 Feb 2004 11:48:36 +0100 Subject: Variable scope within a class References: <401f72f4$0$9388$ed9e5944@reading.news.pipex.net> Message-ID: On Tue, 03 Feb 2004 10:11:43 +0000, Graham wrote: > How do I make a variable available to code *inside* my class in such a way > that it is available to all defs in the class? In my example below f is not > accessible within the showVars method. It depends on whether you want to have a class variable or an instance variable; looking at the following variation of your code should make clear the difference: class myClass: f = [1, 2, 3] def showVars(self): print self.f class myClass2: def __init__(self): self.f = ['a', 'b'] def showVars(self): print self.f print myClass.f myc = myClass() myClass.f = [4, 5, 6] myc.showVars() myc2 = myClass2() myClass2.f = ['c', 'd'] # this f is created here!!! print myClass2.f myc2.showVars() +++ OUTPUT +++ [1, 2, 3] [4, 5, 6] ['c', 'd'] ['a', 'b'] Remark: 'Normally', you want something like myClass2. HTH / Nuff From jjl at pobox.com Sun Feb 1 18:59:02 2004 From: jjl at pobox.com (John J. Lee) Date: 01 Feb 2004 23:59:02 +0000 Subject: Loading a Cookie from a Dictonary References: <401d6deb$0$49109$8f4e7992@newsreader.goldengate.net> Message-ID: <87wu76ic6x.fsf@pobox.com> "Michael Sampson" writes: > I'm using the Cookie module. > Say I have something that looks like this > > import Cookie > c = Cookie.Cookie() > c.load(aDictonary) > > What would the format of aDictornary be, I've looked around the net and I > can only find examples on how to format the input to load if it is a string. > The best info on this I could find is [...] What are you actually trying to accomplish? Server? Client? John From theller at python.net Mon Feb 9 05:22:07 2004 From: theller at python.net (Thomas Heller) Date: Mon, 09 Feb 2004 11:22:07 +0100 Subject: OT: Recommended news reader? References: <4f0a9fdb.0402031309.fde7220@posting.google.com> Message-ID: <3c9kv9gw.fsf@python.net> Sean Legassick writes: > In message , Thomas Heller > writes >>But I was very astonished to see that no other mail/news client I have >>examined allows customizing the From: address depending on the folder or >>group you are currently in. Can that really be true? > > Turnpike does . It costs about UKP15 > and there's no eval version, which is terrible marketing on Demon's > behalf. It's a wonderful email and news client with all kinds of great > features (ok, I was responsible for redesigning the UI during my time > at Demon so I'm somewhat biased...) Thanks. Maybe I'll try it out some time. Although Mozilla Thunderbird now also seems to support multiple identities. Thomas From phleum_nospam at chello.se Sun Feb 8 03:31:11 2004 From: phleum_nospam at chello.se (Carl) Date: Sun, 08 Feb 2004 09:31:11 +0100 Subject: How to make a Gaussian Fit? References: <40258ecd$0$16818$a729d347@news.telepac.pt> Message-ID: Xcal wrote: > Anyone knows how to make a Gaussian fit to a histogram data using Python, > or where I can find a library that helps me in this task? > > Tks everyone... > > Paxcal Install the Numeric module, then >>> import MLab >>> a = range(10) >>> mean = MLab.mean(a) 4.5 >>> standard_deviation = MLab.std(a) 3.0276503540974917 Carl From jorgencederberg at hotmail.com Mon Feb 2 05:00:12 2004 From: jorgencederberg at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Mon, 02 Feb 2004 11:00:12 +0100 Subject: Get number of iteration In-Reply-To: References: Message-ID: Jeff Epler wrote: > You're looking for the "enumerate" builtin function in 2.3. > > for i, x in enumerate(l): > print x > print i > print "next" > > You can define a "poor man's" enumerate in 2.2: > > def enumerate(seq): > return zip(range(len(seq)), l) Just nitpicking... :), but I guess you ment: def enumerate(seq): return zip(range(len(seq)), seq) /Jorgen From P at draigBrady.com Thu Feb 19 09:20:19 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 19 Feb 2004 14:20:19 +0000 Subject: os.popen In-Reply-To: References: Message-ID: <4034C623.3030206@draigBrady.com> Bart Nessux wrote: > When using os.popen, at what point is the process actually started? Take > the example below... would the first or second line actually execute the > command? If it's the first line, then why would I want to use the second > line at all unless I wanted to see on the console what happened? > > ping = os.popen('sh ./ping.sh') this will run until the buffer between the ping process and the python app is full. This is 4k under linux. Then the ping process will block until data is read as there is no where to put it's output. > ping.read() This will read what's currently in the buffer between the processes. You will need to do this in a loop. alternatively if you don't care about the output then you can throw it away, and hence remove the need for the ping.read() like: ping = os.popen("sh ./ping.sh > /dev/null") > ping.close() This will wait for the ping process to finish. To tell it to finish you will need to do something like: ping = popen2.Popen3("sh ./ping.sh > /dev/null") os.kill(ping.pid, signal.SIGTERM) ping.wait() -- P?draig Brady - http://www.pixelbeat.org From claird at lairds.com Fri Feb 20 09:24:18 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 20 Feb 2004 14:24:18 -0000 Subject: Python + Visual Basic References: <54073b3d.0402200605.1e2f00d1@posting.google.com> Message-ID: <103c64i9q9c1n98@corp.supernews.com> In article <54073b3d.0402200605.1e2f00d1 at posting.google.com>, Davide wrote: >Hi, >I am just a beginner with Python and I am interested to know >if someone used it to build COM components while GUI was made >in VB in a "real" application. >I made some experiments and results are good so I would like >to know if it is all OK or someone faced to some unexpected problems. . . . Not only have others done so successfully, but, four years ago, Mark Hammond and Andy Robinson published an acclaimed book on this and re- lated themes. Yes, you should anticipate success with your experiments. -- Cameron Laird Business: http://www.Phaseit.net From mogmios at mlug.missouri.edu Sat Feb 28 17:34:26 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 28 Feb 2004 14:34:26 -0800 Subject: detecting the operating system In-Reply-To: References: Message-ID: <40411772.5040804@mlug.missouri.edu> Checking sys.platform is easy enough. I use it to figure out if I'm running on Linux or Windows. For Linux I take the users home directory to put files in. In Windows I check the registry to find out the location of My Documents and then save files there. Checking the Windows registry is a little more work but can make your programs work quite nicely in Windows. >OK, I tried a Google search on this Usenet group but couldn't find a >solution, so I'm posting my question here (if there's a better archive than >the one in Google, please let me know). > >Does anybody know how to detect the operating system under which the current >Python program is running, especially whether it's Windows or Unix? I have a >program that needs to search for files in "c:\test" if it's running under >Windows, and "/home/user/test" if it's running under Unix, so the simplest >solution I can think of is to detect the operating system, but if anyone >could suggest a workaround, that would also be fine. > From mjordan at adobe.com Tue Feb 10 19:23:53 2004 From: mjordan at adobe.com (Michael Jordan) Date: Wed, 11 Feb 2004 00:23:53 GMT Subject: pywin32 COM Problem with Excel Range Offset? Message-ID: I'm hoping that someone here can give me some insight into a problem I'm running into with Python, pywin32 and Excel. All-in-all using Python and pywin32 is great but I've run into a strange problem with the range Offset property, I'm not getting the correct offset and the returned range is a single cell and not the same size as the original range. For example, when I enter the following lines of code in PythonWin : from win32com.client import Dispatch xlApp = Dispatch('Excel.Application') xlApp.Visible = 1 rng1 = xlApp.Range(xlApp.Cells(8,3),xlApp.Cells(20,6)) rng1.Select() rng2 = rng1.Offset(2,2) rng2.Select() rng1 correctly defines and selects cells C8:F20 but rng2 is incorrectly defined as D9 instead of E10:H22. Digging a little further if I look at the cell sizes for the two ranges I get the following: >>> rng1.Count 52 >>> rng2.Count 1 What's going on with the Offset property? If I enter the equivalent VBA code into the Immediate window from the Visaul Basic Editor within Excel I get the correct behavior. Is this a pywin32 bug? My configuration: pywin32 (build 200) {I got the lastest version to see if this would fix the problem - it didn't} Python 2.3.3 MS Excel 2002 Windows XP Any insight into this problem will be greatly appreciated. Michael From geensys at yahoo.com Sat Feb 28 08:41:47 2004 From: geensys at yahoo.com (Ori Y) Date: Sat, 28 Feb 2004 05:41:47 -0800 (PST) Subject: prob. creating deeply nested structures in Py/c api Message-ID: <20040228134147.3336.qmail@web21404.mail.yahoo.com> Hi , i'm having some difficulties regarding using the Python/c api. I'm trying to bulid a deeply nested datastructure (i.e dict within a dict or list within a dict) Building the data stracture seems ok on interperter, but after few calls to the method returning the structure, and aft applying the Ctrl+D to exit interperter i receive a 'segmentation fault'. ?# Further more when calling the program from python i receive the dictionary as a string! "{foo: {1:'blah, 2:'boo'}, bar:1}" (i have a feeling these problems are related). I'm using python 2.3 on a RH9 Linux machine. Advise would be very much appriciated. Here is a shorter example of the consept i'm trying to do : static *PyObject blah (something) { PyObject *dict1; PyObject *dict2; long x; dict1 = PyDict_New(); dict2 = PyDict_New(); x = 1; PyDict_SetItem(dict1, PyString_FromString("foo"),PyInt_FromLong(x)); //setting first dict //setting dict1 in dict2 and returning dict2 PyDict_SetItem(dict2, PyString_FromString("blah"),dict1); // expected {blah:{foo:1}} --------------------------------- Do you Yahoo!? Get better spam protection with Yahoo! Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridharinfinity at yahoo.com Wed Feb 11 08:28:02 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 11 Feb 2004 05:28:02 -0800 Subject: efficient way for building class browsers. References: <930ba99a.0402071805.15b90424@posting.google.com> Message-ID: <930ba99a.0402110528.7918e3f5@posting.google.com> Josiah Carlson wrote in message news:... > > I am looking for a class browser that has these features. > > Only a browser? Text or GUI? What OS? Any particular GUI toolkit? IDE. Linux,Windows,Mac. PyGTK > > Remember I need a class browser, that also tells me the line no in > > source code of that symbol. (So compiler module (ast) can't be used - > > Is it so? ) > > compiler.ast can be used for this, but only produces proper results when > the file has no syntax errors. Don't get me wrong, using the output of > compiler.ast can be a pain in the ass, and slow as hell (5 seconds for > 100k of source on a celeron 400), but it can be used. > > > Are there any better ways for achieving this? > > You can write a limited parser (subject to certain flaws), one that > doesn't use tokenize or compiler.ast, and get pretty fast results. I > wrote one to go into my own editor PyPE (pype.sourceforge.net), and it > has no problems parsing a 100k Python source file and displaying the > source tree in a GUI in less than 1/2 second on a celeron 400. > I'll try that. I have come across tagmanager (C) code written for the Anjuta (http://anjuta.org) project. I should give it a try too. > It wouldn't be too bad to pull the tree portion out, what kind of > browser do you need? I will put it in brief. The class browser can't support all standard and third party python packages, since most of them is available as shared objects. So mine is focused only on the current project, i.e. user created (or application) python files. So the browser should be able to fetch the tags (class, functions, methods) from source code along with the line number information. That's all about. Any further possiblities in this regard is also expected. > - Josiah From peter at engcorp.com Wed Feb 11 12:31:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 11 Feb 2004 12:31:49 -0500 Subject: How to avoid "f.close" (no parens) bug? References: Message-ID: <402A6705.A1C3A9B5@engcorp.com> Skip Montanaro wrote: > > Facundo> #- Warnings... > Facundo> #- > Facundo> #- foo.py:4: Statement appears to have no effect > > Facundo> Why "appears"? > > I think Neal was just being conservative when he wrote that. In fact, today > with properties and such, just the act of getting an attribute can have side > effects. Determining for sure that there were no side effects would > probably require a lot more analysis, if it's even possible to determine > without actually executing the code. Or one might say he wrote that from the point of view of a code reviewer experienced with Python. Yes, the statement *appears* to have no effect, and therefore if it really does have an effect it is a surprising result, and certainly something PyChecker should be pointing out in case it was in fact wrong. -Peter From jcarlson at nospam.uci.edu Thu Feb 12 15:49:47 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Thu, 12 Feb 2004 12:49:47 -0800 Subject: software design question In-Reply-To: References: <6ee58e07.0402080823.75df2850@posting.google.com> <95aa1afa.0402102316.60fb3c22@posting.google.com> Message-ID: > A quick data point: > > >>> import os > >>> wc = os.popen(r'wc D:\Python23\Lib\*py').readlines() > >>> sum([int(x.split()[0]) for x in wc[:-1] if x])/float(len(wc)-1) > 412.61621621621623 > >>> print wc[-1] > 76334 250898 2657018 Totals > > Gotta go... I'm going to have to remember wc. That is sweet. - Josiah From jbublitzno at spamnwinternet.com Sun Feb 15 02:47:33 2004 From: jbublitzno at spamnwinternet.com (Jim Bublitz) Date: Sun, 15 Feb 2004 07:47:33 GMT Subject: PyKDE/PyQT/SIP References: <402ed5d0$0$14898$afc38c87@news.optusnet.com.au> Message-ID: Sam wrote: > Hey people, > I am trying to install these modules to play around with KDE > panel applets, but I am beginning to think it's too much > trouble to be worth it. > I've installed PyQT (as well as the PyQT-devel rpm, which is > apparently needed if I install PyQT from an rpm), PyKDE and the > sip module. When I run the importTest.py script that comes with > PyKDE, I get this: > ------------------------------------- > Testing PyKDE module imports > dcop > /usr/lib/python2.3/site-packages/dcop.py:22: RuntimeWarning: > Python C API version mismatch for module libsip: This Python > has API version 1012, module libsip has version 1011. > import libsip > kdecore > kdesu > kdefx > kdeui > Traceback (most recent call last): > File "importTest.py", line 7, in ? > exec ("import " + mod) > File "", line 1, in ? > File "/usr/lib/python2.3/site-packages/kdeui.py", line 67, > in ? > import libkdeuic > ImportError: libpython2.3.so.1.0: cannot open shared object > file: No such file or directory > --------------------------------- > If anyone could give me an easy solution to the problem (or any > solution, but easy would be preferable ;) that would be > fantastic. I'm not sure what this error is, but libkdeuicmodule should be looking for libpythonize.so.1.0, which should be in /usr/lib and symlinked some other places. The first thing to do is see if libpythonize is in /usr/lib, and if the Makefile in PyKDE-3.8/pythonize LFLAGS includes: -soname,libpythonize.so.1. You can't do panel applets without this. It would also be useful to do: ldd /usr/lib/python/site-packages/libkdeuicmodule.so or whatever the path to that lib is on your system. You can also check the LIBS line in the kdeui/Makefile - should include -lpythonize. It would also help to know what KDE version your running, and which PyKDE release. Either reply here or email me privately (jbublitz at nwinternet.com) and we should be able to get it straightened out. Let me know what you find out. PyKDE-3.8 was a pretty crappy release as far as installation goes (it works great if you can get it installed though). The cause of that has been resolved and the next release should be a lot easier to install. However the next release won't include panel applet support, since that's being split off into a separate package - I'm not maintaining that at the moment and haven't checked on the status lately, but I'll see what I can find out there too. Sorry for the problems. Jim From andymac at bullseye.apana.org.au Fri Feb 20 05:01:33 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 20 Feb 2004 21:01:33 +1100 (EST) Subject: AVPython on ArcGIS? In-Reply-To: References: Message-ID: <20040220205151.Y37600@bullseye.apana.org.au> On Thu, 19 Feb 2004, Bruce Dodson wrote: > AVPython itself will not be ported to ArcGIS 8 or 9. > However, I have been working occasionally to make ArcObjects > accessible from Python. I call it PyArcObjects. I made > some progress, but also found some gotchas in the ArcObjects > typelibs. All in all, this is a much more ambitious project > than AVPython, and will take longer to get right. Damn! gazumped on the name! I'm awaiting legal clearance from my employer to release a ctypes based interface package (which I'd planned to call PyArcObjects) to the ArcObjects COM API, based on the ArcGIS 8.3 typelibs. So far it works well for what I've needed to do. -- 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 jcarlson at nospam.uci.edu Wed Feb 11 02:47:12 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 10 Feb 2004 23:47:12 -0800 Subject: software design question In-Reply-To: <95aa1afa.0402102316.60fb3c22@posting.google.com> References: <6ee58e07.0402080823.75df2850@posting.google.com> <95aa1afa.0402102316.60fb3c22@posting.google.com> Message-ID: > Moreover, I feel much easier to edit simultaneously > three or four buffers than to navigate back and forth on a very long single > buffer. Depending on the features of your editor, going to different locations in the current buffer (even offset by many lines) can be arbitrarily trivial. When you have a source tree, you are a double-click away from any class/function/method (or even properly-formed comments, depending on the editor support). For those cases when keyboards shortcuts are convenient, some editors have per-line bookmarks that allow you to hop to often-used code portions very quickly. I'm sure all of this can be done with Emacs (perhaps even Vim), if you know how to do it. > P.S. once I computed the average lenght of modules in the standard library. > The result was something like 200 lines. Sounds like a histogram is in order. Maybe I'll do it this weekend when I have the time. - Josiah From jeremy at zope.com Thu Feb 5 21:54:11 2004 From: jeremy at zope.com (Jeremy Hylton) Date: Thu, 5 Feb 2004 21:54:11 -0500 Subject: Looking for a DB for object persistance... In-Reply-To: Message-ID: > I need it to: > > Works both in Linux and windoze > Server independent (no Mysql or the like) I'm not sure what you mean by server independent. Do you mean you don't want a solution that requires you to run a separate server process? > Allow simultaneous access by multiple process for read/write operations. > Be able to hold lots of data (close to a gig) > > I tough Berkeley DB with bsddb3 would be the ticket, but I could not > make sense of the installation instructions for win32, no mention of > python. It does work with Python. I've built it for Python 2.3 on Windows NT. There are instructions in the PCbuild subdirectory of the Python source tree. > I am considering Zodb3, but did not find info for simultaneous access > capability. Within a single process, any number of threads can access independent, consistent views of the database. If you run a ZEO server, then clients on any machine can connect to the server to access the database. It works on Windows and Linux, and I'm familiar with several installations that have databases with > 10GB of data. If all you want is a shelve interface, you'd probably do better with BerkeleyDB. ZODB provides a more natural interface for Python programs -- it just stores objects -- but it does have a different programming model than shelve. On the other hand, ZODB is faster than BerkeleyDB for many applications. Jeremy From roy at panix.com Thu Feb 19 20:58:46 2004 From: roy at panix.com (Roy Smith) Date: Thu, 19 Feb 2004 20:58:46 -0500 Subject: Generating a large random string References: <4034D506.2E37519A@netsurf.de> Message-ID: In article <4034D506.2E37519A at netsurf.de>, Andreas Lobinger wrote: > How to generate (memory and time)-efficient a string containing > random characters? Find a perl file on your system and read it? From bignose-hates-spam at and-benfinney-does-too.id.au Mon Feb 9 21:16:02 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 10 Feb 2004 13:06:02 +1050 Subject: approach to writing functions References: Message-ID: On Mon, 09 Feb 2004 21:22:27 -0500, Bart Nessux wrote: > I understand that most people write functions to reuse code, no? No. I write functions to make complex code sequences more simple -- i.e. for abstraction. Parcel up the behaviour that can conceptually be considered a single action, and put it away in a function. This has the valuable benefit that the function can then be re-used in other places needing the same action; but that's not the reason I write them to begin with. > So, I assume it would be better to write functions that are very > specific, as opposed to those that are more generic. I've no idea how "re-use the code" leads you to think of more specific functions -- surely the trend would be to more *generic* functions, that can thus be re-used in more places? > Is this wrong? I know functions were not intended for this, but if I > don't use them in this manner, I might as well do everything globally, > and I don't see any difference in the two approaches. I recommend you get a copy of Code Complete (Steve McConnell, published by Microsoft Press). It is an extremely comprehensive and approachable tome on the actual practice of writing code. In particular, it explains just about every reason to use abstraction in data, code and algorithms. Some you may have heard before, but my feeling from your message is that a lot of it will be new -- and all of it is valuable. -- \ "If you go to a costume party at your boss's house, wouldn't | `\ you think a good costume would be to dress up like the boss's | _o__) wife? Trust me, it's not." -- Jack Handey | Ben Finney From klaus_neuner82 at yahoo.de Wed Feb 4 04:24:23 2004 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 4 Feb 2004 01:24:23 -0800 Subject: assignment statements: lists vs. strings References: <3e96ebd7.0402020750.3b0b9b82@posting.google.com> <3e96ebd7.0402030333.7c303cfb@posting.google.com> Message-ID: <3e96ebd7.0402040124.62db226@posting.google.com> Thanks. From mhammond at skippinet.com.au Mon Feb 9 00:05:38 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 09 Feb 2004 16:05:38 +1100 Subject: Writing Windows performance counters In-Reply-To: References: Message-ID: David Mitchell wrote: > Could someone point me towards some sample code that creates performance > counters and updates them? I suspect it's possible using perfmondata.dll > that comes with win32all, but can't begin to guess how to get started. I thought there was sample code in win32all, but it looks like it never got created - but 1/2 of it is there. The win32\demos\service\install directory has a .h and a .ini file that are used by Windows itself when installing the perfmon data. Somewhere, your runtime code should implement code similar to: counters = [] # Empty list to fill with counters. # Counter of document opens. # Magic numbers (2, 4, 6) must match header and ini file used # at install - could lookup ini, but then I'd need it at runtime counterSomething=perfmon.CounterDefinition(2) counterSomething.DefaultScale = 1 counters.append(counterSomething) counterSomethingElse=perfmon.CounterDefinition(4) counterSomethingElse.DefaultScale = 1 counters.append(counterDocSave) perfObjectType = perfmon.ObjectType(counters) # end of sample The magic numbers must match the .h and .ini (which is a requirement of Windows, not us!) Once the above code has been run, 'counterSomething' and 'counterSomethingElse' can have their 'Increment' method called, to increment the counter. Note that I don't try and hide the win32 gory details here, so you really must read the MS documentation on this complicated mechanism. Let me know if you would like any help. A very useful thing to do would be to create a sub-class of the existing demo service, with the subclass doing nothing other than providing the perfmon data. This was always my intent. If you have trouble getting it going, providing the above as sample code to demonstrate your problem would get a good response ;) Mark. From mcfletch at rogers.com Wed Feb 25 02:55:39 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 25 Feb 2004 02:55:39 -0500 Subject: Sharing accomodation @ PyCon? In-Reply-To: References: Message-ID: <403C54FB.6050307@rogers.com> Aahz wrote: >In article , >Mike C. Fletcher wrote: > > >>I'm still looking for someone with whom to share a room at PyCon. I'd >>prefer the Best Western in Arlington (1 subway stop from PyCon). I'd >>like to book or confirm sharing someone else's booking within the next >>few days. >> >> > >For you or anyone else interested in doing this, it's probably a good >idea to specify which dates you want, given the sprint 3/20-23 and the >conference 3/24-26. > > Good point, I'm planning on attending only the conference, as I'm coming in on the PyCon bus from Toronto. Nights of the 23, 24, 25, 26 (i.e. arriving night before conference, leaving day after). However, I guess everyone posting there itinerary here is silly. Let's use the PyConForCheap page on the Wiki for pairing up... http://www.python.org/cgi-bin/moinmoin/PyConForCheap2004 Scroll to the bottom to see those looking for pairings, add your name if you want to pair or contact compatible person to share. Take your name off the list when you book a room. Have fun all, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From nuffsaid at phreaker.net Fri Feb 6 10:05:02 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 06 Feb 2004 16:05:02 +0100 Subject: How to send a file as an argument when running another file in Python References: Message-ID: On Thu, 05 Feb 2004 13:39:53 -0800, se7en wrote: > I have this file x.py and I need to execute it with y.met as an > argument. Unsure of syntax etc... > > -Python newbie Use: import sys filename = sys.argv[1] print filename Usage: python x.py y.met (sys.argv is a list where the first entry (i.e. sys.argv[0]) is the name of your Python script and the other entries are the command line arguments which you passed to your script.) HTH / Nuff From pythonguy at Hotpop.com Tue Feb 3 03:57:25 2004 From: pythonguy at Hotpop.com (Anand Pillai) Date: 3 Feb 2004 00:57:25 -0800 Subject: How to include schema while creating an xml file References: Message-ID: <84fc4588.0402030057.57ef5376@posting.google.com> This is the wrong forum to post your question. Try one of the xml newsgroups. Anyway to answer your question, here is the way to do it. ... -Anand "bala" wrote in message news:... > Hi, > How to include schema while creating an xmlfile.. > > Regards > Bala > -- From peter at engcorp.com Wed Feb 18 11:41:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Feb 2004 11:41:34 -0500 Subject: PEP218: Representing the empty set References: <403281B3.7E370347@engcorp.com> <7xlln1pfip.fsf@ruckus.brouhaha.com> <40328E21.E451AE5A@engcorp.com> <7xznbh72xp.fsf@ruckus.brouhaha.com> Message-ID: <403395BE.6BE736DC@engcorp.com> Paul Rubin wrote: > > Peter Hansen writes: > > I think the example I would have in mind is a comparison: > > > > if a == []: > > # do something > > if b != {}: > > a.append(b) > > > > or whatever.... If the empty item > > is merely a temporary, to be used and discarded, then the apparent > > extra overhead of the call, and the less succinct syntax, lead me to > > think the short form is preferable. > > But you suffer the overhead either way. The {} syntax may be worse > than the function call syntax because it looks like it avoids the > overhead when it really doesn't. The correct way to avoid the > overhead is with "if len(b) != 0: ... ". Who said this was about overhead? Oh, wait, you thought I did... because of the part where I said "overhead". :-) I didn't mean that what is important is whether or not there *is* actual overhead. Merely that the one approach, with the literal, fits more easily in the brain and "feels" better. Whether this is because one (mistakingly) believes at some low level that it has less overhead or not is irrelevant. Given the option, perhaps even if it had *higher* overhead, I would still prefer the more readable (to me) literal form. -Peter From tjarko at dutlbcz.lr.tudelft.nl Fri Feb 27 10:16:28 2004 From: tjarko at dutlbcz.lr.tudelft.nl (Tjarko de Jong) Date: Fri, 27 Feb 2004 16:16:28 +0100 Subject: wxPython tutorial? References: <36965e8.0402262255.122d167f@posting.google.com> Message-ID: On Fri, 27 Feb 2004 09:38:00 GMT, Greg Krohn wrote: >Jive Dadson wrote: >> I'm trying (without conspicuous success) to start learning >> wxPython. Sooo... I opened the doc page wxPythonManual.html#wxpython-overview. >> The very first example does not work. Try it. I find much of what follows >> to be incomprehensible. Is there a good tutorial for novices? >> >> Here's the example that does not work. ("No module named frame") >> >[snip] > >Weird. I've never seen imports like that with wxPython before. It keeps the namespace clear. see: http://cvs.osafoundation.org/index.cgi/osaf/chandler/wxpython/wxPython/docs/wxPackage.html?rev=HEAD From tjreedy at udel.edu Mon Feb 9 12:27:22 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 9 Feb 2004 12:27:22 -0500 Subject: [pyGame] set position References: Message-ID: "Yomanium Yoth Taripo?t II" wrote in message news:gcMVb.113$Fd.67 at newsr2.u-net.net... > Hi, > > how to set pygame screen position, on the desktop?? > > default create is on center, and i want to change it. > > thx in advance. If you do not get an answer here, try the pygame mailing list, which is the more appropriate place for questions about PyGame rather than Python. tjr From eltronic at juno.com Fri Feb 6 16:25:15 2004 From: eltronic at juno.com (eltronic at juno.com) Date: Fri, 6 Feb 2004 16:25:15 -0500 Subject: new newbie [c.l.py FAQ] Message-ID: <20040206.162516.-203479.3.eltronic@juno.com> On Fri, 06 Feb 2004 19:34:15 GMT not_yet writes: > also wanted to ask is there a faq for this group? > no, there is one for #python on IRC. many of the questions asked here have been answered in the python FAQ. here are a few of the subjects such a FAQ might cover. don't cross post to c.l.* many people read via email and their answers won't travel. language wars are futile because python is a moving target. how much to quote in your reply? remember this list is gated and many people read through email and probably cant refer back to earlier messages, for that matter people reading on other than google might not save every message so please always include enough context that the reply, (even a thankyou if you must) makes sense and stands on its own as a message. don't top post. makes a little sense on google but nowhere else. no exceptions. ask smart questions, get better answers. please do some searching for the answer before you post. add: word +python -monty -snake in your search to improve the chances of getting useful information. you can also search at google or ASPN at ActiveState in only this newsgroup. we will try to guess but for the best chance of getting the answer, properly describe the problem you are having and what you expect. choose a good subject line. "help, nubee problem" etc are not descriptive. heh eliminate inadvertant redundancies in the subject. include modifiers like [OT] off topic, ...(long),ANN: , as applicable. try not to misspell major subject words. give your operating system and version and any relevant hardware info the python version and how it was compiled if known. test any code before you post. don't guess. pare down any examples to the bare minimum to present the error. post a few lines of sample test data. copy & paste any error traceback. don't re edit the code you post from the interpreter. don't post with tabs in outlook express and a few other news/email readers they get deleted. above all don't mix tabs and spaces. get an editor that will translate tabs for you. the act of making a useful post will often provide the answer for yourself. feel free to post the q&a for comment anyway. post text not hTml. please don't post test messages. don't post test messages. test messages, except if your physically working on the email gateway at aspn or python.org are a nuisance even if you say test please don't read etc. there are test groups for that. if your soliciting downloads, please give the file size and any OS restrictions. nothing worse for a window user to see some mac specific stuff 20 minutes after a long download and examining the source for errors. if you've packaged up the executable only version and no source is going to be available many will want to know that too. specify the python version so we can decide if requiring version 2.3 makes sense and give enough details about the program function itself to know what the GUI the potential limitations or any licence restrictions are. if the post seems related to homework expect to get hints and not running examples with all the bells & whistles from every responder. please don't repeat the question with more than one subject line from more than one address more than once in a great while. you didn't see your question because you or something down the line is lagged. give it a day or two at least to reach you. and a few more for someone with a similar interest to respond. in spite of the usual lightning response time normally seen. chances are twisted already does it so please try that first. learn the difference between text and binary mode for files. #when in doubt, import this * some ideas, words and or characters might have been lifted entirely from earlier responses and no credit to them or their bots will be attempted. ** realize that the target audience for this type of information has already proved adverse to guidance before posting. e ________________________________________________________________ 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 jcarlson at nospam.uci.edu Sun Feb 29 15:44:17 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sun, 29 Feb 2004 12:44:17 -0800 Subject: How to use plugins.. In-Reply-To: References: Message-ID: > 1.) > Assume my package is installed on path x and has a subdirectory named > plugins. > If I import my package I want to scan automatically the plugin > directory. os.listdir(path) > 2.) > Plugins should follow a common interface, is there a way to enforce > this? > (Actually I think this might be easy.) use try and except liberally: try: plugin.function(args...) except: #report plugin error - Josiah From dk123456789 at REMOVEhotmail.com Wed Feb 11 19:02:12 2004 From: dk123456789 at REMOVEhotmail.com (Dave K) Date: Thu, 12 Feb 2004 01:02:12 +0100 Subject: str.find for multiple strings References: <402A7FDC.8D47A02B@engcorp.com> Message-ID: <5hel20hgg1cs65rsog2jp0eg35dsn6rrq1@4ax.com> On Wed, 11 Feb 2004 14:48:22 -0500 in comp.lang.python, Bart Nessux wrote: >Peter Hansen wrote: >> Bart Nessux wrote: >> >>>x = str.find(temp, '120.50') >>> >>>I am looking for '120.50' '120.51' '122.78' etc. How can I do this with >>>just one str.find... I can use re if I must, but I'd like to avoid it if >>>possible. >> >> >> In addition to Fecundo's questions, here's another. What does "temp" >> contain? A single temperature string, or a temperature embedded in >> a bunch of other stuff, or a whole series of temperatures, or what? >> >> -Peter > >Here's what I'm doing > >def exclude(): > import os > os.chdir('/home/rbt/scripts') > inputFile = file('ath_ips.txt', 'r') > data = inputFile.read() > inputFile.close() > comment = '#' > net0 = '128.173.120.' > net1 = '128.173.122.' > host0 = ['50','51','52','53','54','55'] > host1 = ['17','25','49','50','55','58','70'] > for h0 in host0: > h0 = net0+h0 > rep0 = comment+h0 > sea0 = str.find(data, h0) > if sea0 >=0: > data = data.replace(h0, rep0) > for h1 in host1: > h1 = net1+h1 > rep1 = comment+h1 > sea1 = str.find(data, h1) > if sea1 >=0: > data = data.replace(h1, rep1) > outputFile = file('ath_ips.txt', 'w') > outputFile.write(data) > outputFile.close() > There's no need to do an explicit find() before replace(). Your 'for' loops can be written as for h0 in host0: data = data.replace(net0+h0, comment+net0+h0) for h1 in host1: data = data.replace(net1+h1, comment+net1+h1) Or reduce it to one 'for' loop with list_comprehensions for host in [net0+h0 for h0 in host0] + [net1+h1 for h1 in host1]: data = data.replace(host, comment+host) Dave From selwyn at aotearoa_is_home.nz Thu Feb 19 02:25:24 2004 From: selwyn at aotearoa_is_home.nz (selwyn) Date: Thu, 19 Feb 2004 20:25:24 +1300 Subject: wxPython progress bar widget In-Reply-To: References: Message-ID: Jani Yusef wrote: > Does wxPython have a progress bar widget for use. If so I can't seem > to find anything via google....... > My app is pythoncard/wxPython based. I'd like to have a graphical bar > meter of some sort to show the status of a recurring lengthy file > upload done by the app. > Any advice or suggestions? > Thanks!! in pythoncard this is a Gauge (which wraps wxGauge) From mhammond at skippinet.com.au Fri Feb 6 18:21:33 2004 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 07 Feb 2004 10:21:33 +1100 Subject: Writing to REG_MULTI_SZ windows registry keys In-Reply-To: References: Message-ID: Pat Blair wrote: > Hello. I'm looking for any information I can get about writing values > to keys in the Windows registry when the value type is a multi-string > (ie. REG_MULTI_SZ). When I get the value of a multi-string value using > winreg functions, I get a tuple with tuple[0] being a list, and tuple[1] > a number. This function will be documented as returning a tuple of (data, data_type). Hence, tuple[0] is your data, which itself is a list. > If I try to write such a tuple back into a multi-string > value, I get the following exception: You pass the type you want to set as one param, and the data as another. Try just passing tuple[0] back into the function (but obviously specifying REG_MULTI_SZ as the type) Mark. From andrew-pythonlist at puzzling.org Tue Feb 24 20:24:41 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 25 Feb 2004 12:24:41 +1100 Subject: xmlprclib/server not reusing connections In-Reply-To: References: Message-ID: <20040225012441.GA4898@frobozz> On Mon, Feb 23, 2004 at 09:57:55PM -0800, Roger Binns wrote: > > You might have better luck with Twisted http://twistedmatrix.com/. > > I did look at twisted but really don't like it. In particular I really > don't like the event driven code, that has to add callbacks and > deal with partial state when called. I was initially skeptical too, but I found that the small cost of using callbacks to be well worth the benefit of avoid threads most of the time. Threads invite all sorts of difficult to reproduce and debug problems like race conditions and deadlocks. That said, event-driven programming doesn't suit every problem. Twisted does try fairly hard to reduce the burden of asynchronous code, though: Deferreds make chains of callbacks easy to handle, and the twisted.flow package uses python 2.2's generators to allow synchronous-looking code to yield to the event loop: http://twistedmatrix.com/documents/howto/flow And of course Twisted's splitting of network code into reactor, factory, protocol and transport objects is a really nice abstraction, but that would probably translate just fine into blocking code too (except perhaps the reactor would be largely irrelevant?). > That is certainly the right way to do things if you want to avoid > using threads. It is however complicated and convoluted. See this > example: > > http://twistedmatrix.com/documents/howto/tutorial#auto20 That example looks fine to me, but perhaps I've been using Twisted too long! :) I certainly have no problems reading that code and immediately understanding what every part of it does. > The model I far prefer is to use multiple threads (available on all > major Python platforms) and use worker threads with work queues. > They turn out to be simpler since they don't have queue callbacks > or effectively be a glorified state machine scattered across > several functions. That's fine. Twisted doesn't prevent you from using threads! reactor.callInThread(func, args...) will run a function inside a thread pool (or you can just start and manage threads yourself), and reactor.callFromThread provides a safe way for a thread to run some code in the main event loop. Twisted itself does this in e.g. the twisted.enterprise.adbapi module, to provide an asynchronous interface around a synchronous DB-API modules. > > Glancing at that, it looks like using Twisted to implement that would be a > > lot easier, and shorter. > > Except it wouldn't unless twisted already had the necessary functionality > which it doesn't. I would have to go through a similar exercise with > twisted, which is far more complicated. Well, Twisted already has persistent HTTP connections and SSL. So e.g. the vast bulk of your XMLRPCRequestHandler.do_POST would disappear, because twisted.protocols.http already does that. Perhaps my point wasn't clear: I wasn't saying that Twisted will inherently make any network code much much shorter[1], I was saying that Twisted already has sufficient HTTP and SSL support to meet your needs, and that you could re-use that. Of course, now that you've written what you need without Twisted, you probably don't care very much :) -Andrew. [1] Although I think on average it probably does, and makes it easier to write, too. The wide variety of protocols available in twisted.protocols suggests to me that I'm at least part right about this... From pinard at iro.umontreal.ca Wed Feb 11 19:30:37 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 11 Feb 2004 19:30:37 -0500 Subject: Checking for usual descriptors in Python 2.3 Message-ID: <20040212003037.GA31543@alcyon.progiciels-bpi.ca> This question is a bit technical, but hopefully, this list will offer me good hints or nice solutions. Happily enough for me, it often does! :-) I would need to recognise and play with descriptor types, like: member descriptors method descriptors getset descriptors wrapper descriptors but do not find how to easily refer to them, either from existing constructor types (like we could do with `property', say), nor from members of the `types' module. I also wonder how much I can "get into" these various descriptors or tear them apart... P.S. - If you are curious, my real goal is creating some metaclass able to build kind-of-shadow classes for various pygtk widgets, lazily, on the fly. If experimentation shows that this is not speedy enough, than I may rather have a pre-processor that would produce Python source instead. In any case, I need to learn how to explore descriptors at run time, rather than working hard at scanning/parsing real pygtk sources. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From gerrit at nl.linux.org Thu Feb 5 15:28:04 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 5 Feb 2004 21:28:04 +0100 Subject: unbuffered input In-Reply-To: <4022A58B.6070903@valdosta.edu> References: <4022A58B.6070903@valdosta.edu> Message-ID: <20040205202804.GA6311@nl.linux.org> michael young wrote: > I have a numbered menu that I want users to from. They choose the > number corresponding to the action they wish to take. > Right now I'm using input() to get the user's responce. They press the > number then press ENTER. I would like to skip the > part where they press ENTER, so that the user presses the number and > then they get the action they chose without having > to press ENTER. Is there a way to do this and how? Yes, but it's not really platform-independent. You can find a way to do this at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 On Windows, you can use the getch() function from the mscvrt module. On Unix, it is a bit more difficult, but the trick is using tty.setraw. On Mac, you use the Carbon package. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From claird at lairds.com Thu Feb 12 19:32:28 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 13 Feb 2004 00:32:28 -0000 Subject: Table Oriented Programming References: <102nomqgcceleac@news.supernews.com> Message-ID: <102o6ost5a80re8@corp.supernews.com> In article <102nomqgcceleac at news.supernews.com>, John Roth wrote: . . . >It's an intriguing idea; I've had the occasional thought of >wanting an in-memory relational algebra implementation (which >is what he's actually specifying once you get him down off of >the hobby-horse he's riding.) > >Put together a package and see whether it flies for real world >problems. That's the usual path for inclusion into Python - put a >pure Python package together, see if you can get people excited >about actually using it, and then propose it for inclusion into the >standard library. > >John Roth > > Notable contributor Jean-Claude Wippler is just now releasing some of his implementations in the area of relational algebra. -- Cameron Laird Business: http://www.Phaseit.net From fuka at fuxoft.cz Sat Feb 7 12:10:49 2004 From: fuka at fuxoft.cz (Frantisek Fuka) Date: Sat, 07 Feb 2004 18:10:49 +0100 Subject: [Twisted] Sessions validity Message-ID: Sorry for posting this here but I got no reaction when asking in twisted-web mailing list: Twisted stores the Session objects using cookies. I'd like to know how long these Sessions last (it seems to be 30 minutes?) and - more importantly - I'd like my application to be able to set different Session timeouts for different users. I need some of the users (just some!) to be able not to click on anything on the site for several hours and still be logged in afterwards, when they click. Is there a way to do this cleanly or do I have to change the Twisted sources? (I admit I am not very proficient with the cookies) -- Frantisek Fuka (yes, that IS my real name) (and it's pronounced "Fran-tjee-shek Foo-kah") ---------------------------------------------------- My E-mail: fuka at fuxoft.cz My Homepage: http://www.fuxoft.cz My ICQ: 2745855 From t-meyer at ihug.co.nz Wed Feb 18 18:46:18 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 19 Feb 2004 12:46:18 +1300 Subject: How do make a function that creates a sequence of n randomnumbers? In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1305255E44@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677995@its-xchg4.massey.ac.nz> > > Thanks, everyone. Also, I'd really like to know how to remove the > > lowest number from the sequence. > Now this really sounds like homework. OT, but if you were a teacher assigning homework like this, wouldn't you read c.l.p to see which of your students asked the homework questions? (Or at the least, google through the list when the homework is handed in?) =Tony Meyer From grahamd at dscpl.com.au Sat Feb 28 19:37:42 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 28 Feb 2004 16:37:42 -0800 Subject: Licensing of wrappers around C/C++ code under more restrictive licensing. References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> Message-ID: Ville Vainio wrote in message news:... > Googling also revealed: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81614 > > But beware: OSE, which that recipe relies on, seems to be licensed > under QPL. That it is currently under the QPL means nothing if you aren't intending to redistribute your own code. Ie., if you are developing a system for in house or personal use, the contentious parts of the QPL don't actually kick in and it should be safe to use. Much the same as the GPL really, where things only apply if you intend to redistribute. The next version of OSE will try to address this issue by allowing use of the Python wrappers under a BSD or Python style license, provided that the C++ layer underneath is left as is. Change the C++ layer underneath and the QPL will apply up through the Python code as well. In other words, there will be an attempt to build a wall between the QPL licensed C++ code and the Python code. It may turn out that this is not a practical thing to do and even if possible, it may still not satsify the GPL license clause about other licenses placing additional restrictions beyond those implied by the GPL. Ie., you still might not be able to validly use the stuff in an application where you also use Python code under the GPL. I would really like to hear other peoples ideas about how to address licensing where the Python code is actually a wrapper around a C/C++ library under a QPL or GPL type license. Some people seem to believe that the use of the scripting language implies a line is drawn when people go to use it and thus what the library underneath is licensed under doesn't matter. Linking of the library still occurs though, so I don't believe this is necessarily the case. So, how can one cast the licensing so as to provide an exception that provided the underlying C/C++ library isn't changed, that the Python wrappers can be used under a less restrictive license. I have control of the licensing on both so can stipulate exceptions, but what is the best way of doing it? Comments? From sschwarzer at sschwarzer.net Sun Feb 8 12:37:01 2004 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 8 Feb 2004 18:37:01 +0100 Subject: [ANN] ftputil 2.0 Message-ID: <20040208183701.6126dcea.sschwarzer@sschwarzer.net> ftputil 2.0 is released! :-) ftputil is a high-level alternative to Python's ftplib module. With ftputil, you can access directories and files on remote FTP servers almost as if they were in your local file system. This includes using file-like objects representing remote files. You can download ftputil from http://www.sschwarzer.net/download/ftputil-2.0.tar.gz For future releases see http://www.sschwarzer.net/python/python_software.html or subscribe to the mailing list at http://codespeak.net/mailman/listinfo/ftputil What's new? ----------- From version 1.1 to 2.0, the following has changed: - ftputil has been re-organized and is now a Python package (the import statement is still the same) - installation via Python distutils - stat, upload_if_newer, download_if_newer etc. work correctly if the server is in another time zone than the client running ftputil (with help from Andrew Ittner); see section "Time zone correction" in the documentation - it's possible to set the directory listing format "manually" (though in most cases it's recognized automatically); see section "Stat'ing files and directories" - added a workaround regarding whitespace in directory names (thanks to Tommy Sundstr?m and H. Y. Chu) - extended documentation and converted it to HTML format (now generated from reStructured Text) - several bugfixes - there's now a mailing list at http://codespeak.net/mailman/listinfo/ftputil (thanks to Holger Krekel) Documentation ------------- The documentation for ftputil can be found in the file ftputil.txt (reStructured Text format) or ftputil.html (recommended, generated from ftputil.txt). License ------- ftputil is Open Source Software. It is distributed under a BSD-style license (see the top of ftputil.py). Stefan From nospam-deets at web.de Thu Feb 26 08:12:26 2004 From: nospam-deets at web.de (Diez B. Roggisch) Date: Thu, 26 Feb 2004 14:12:26 +0100 Subject: Catching exception information from ExpatError References: <88m%b.30631$Da7.12393@newssvr25.news.prodigy.com> Message-ID: python newbie wrote: > Can you suggest something, is it obvious? It is. http://www.python.org/doc/current/lib/expaterror-objects.html -- Regards, Diez B. Roggisch From ahaas at airmail.net Tue Feb 24 11:15:58 2004 From: ahaas at airmail.net (Art Haas) Date: Tue, 24 Feb 2004 10:15:58 -0600 Subject: ANNOUNCE: Twelfth release of PythonCAD now available Message-ID: <20040224161558.GA8066@artsapartment.org> Hi. I'd like to announce the twelfth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or Python 2.3. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twelfth release of PythonCAD contains a large number of internal changes to the program. The class hierarchy for the various entities has been simplified, and the ability to hide or lock entities on an individual basis has been added. The largest change to the code is the incorporation of a messaging system between the entities similar to that in Trolltech's QT framework. Another significant change in this release is the introduction of quadtrees for storing the various entities in a drawing, which should provide faster searching for the location of the entities. A number of code cleanups have also been applied to this release. Numerous deprecated methods have been removed, and several Python function calls that are deprecated or appear to be heading that way have been removed. The code cleanup also exposed various bugs which are now resolved. Changes due to the incorporation of the new messaging system have made a number of entity methods deprecated, so warnings messages will appear if they are called. These newly deprecated methods will be removed in an upcoming release. The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program, and Happy New Year to everyone! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From michele.simionato at poste.it Thu Feb 19 14:28:03 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 19 Feb 2004 11:28:03 -0800 Subject: hmm, lets call it: generic __init__ problem References: <95aa1afa.0402180908.1f7a8b6c@posting.google.com> Message-ID: <95aa1afa.0402191128.3f2e046b@posting.google.com> paul k?lle wrote in message news:... > The solution using super() like Peter suggested is almost perfect > except the name of the class is still hardcoded inside of __init__. > > one(object): > def __init__(self, *args, **kwargs): > super(one, self).__init__() > ^^^^ > r = self.s.get_obj(ldap.schema.ObjectClass, self.__class__.__name__) > ...process r... > > implies to write another __init__ for every subclass, since "one" wouldn > 't match the subclass's name right? Instead of "one" I'd like to have > something that get's the current class at instantiation time. Is that > possible ? > Yes, but it is quite non-trivial to get it right with the current language. I consider it to be a wart of super. See Guido's "autosuper" metaclass and this post of mine for a solution: http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=95aa1afa.0401150715.61e44550%40posting.google.com&rnum=4&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bsuper%2Bgroup%253Acomp.lang.python.*%26btnG%3DCerca%2Bcon%2BGoogle%26meta%3Dgroup%253Dcomp.lang.python.* Warning: it is not for the faint of heart ;) Michele Simionato From tkpmep at hotmail.com Sun Feb 15 19:00:02 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 15 Feb 2004 16:00:02 -0800 Subject: Stopping a program Message-ID: I'd like to stop a program (i.e. terminate its execution) without raising an exception if some condition is met, e.g answer = " " while answer not in "yn": answer = raw_input("y for yes, n for no, enter to exit ") if answer == "" stop/quit/end/whatever it takes to terminate the program elif answer == "y" #Yes . . elif answer == "n" #No . . In Fortran, I'd use a stop command to do this. What is the appropriate equivalent in Python? Thomas Philips From logistix at cathoderaymission.net Thu Feb 19 11:06:52 2004 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 19 Feb 2004 08:06:52 -0800 Subject: Python Virtual Machine Reference References: Message-ID: <3c91a864.0402190806.36b293d2@posting.google.com> Michael Hudson wrote in message news:... > > What happens on the ast-branch (the "new compiler" branch), I'm not so > sure about. An AST (AFAIK different from Lib/compiler's) is involved > somewhere, but I'm not sure how it's produced. > It uses the existing mechanism to generate the parse-tree, and then transforms into a real AST prior to bytecode generation. Writing a new parser-generator has been deferred at this point. From warlock at eskimo.com Fri Feb 20 19:01:15 2004 From: warlock at eskimo.com (Jim Richardson) Date: Fri, 20 Feb 2004 16:01:15 -0800 Subject: Parsing apache log files References: Message-ID: On Fri, 20 Feb 2004 09:20:00 -0800, Josiah Carlson wrote: >> thanks, although reading that re makes my brain hurt! :), and I don't >> think it handles the case where the dashes are something else (the dash >> is a place holder for some data that wasn't there on this request, >> bytelength, referrer, something) but I'll look into it, thanks for the >> example. > > It depends on which dash you were talking about. The dash immediately > after the response code is the number of bytes sent, and is handled by > the regular expression. > > Unless you use identd checks, the first '-' will always be there, though > the second '-' is the identity of the client given through http auth, > which may or may not be important to you. > It was the http auth, which for some reason, show up from time to time, may be a misconfigured router/proxy don't know. But this works, although my brain is still parsing the regexp :) Thank you very much for your help. -- Jim Richardson http://www.eskimo.com/~warlock One man's religion is another man's belly laugh. From jepler at unpythonic.net Wed Feb 18 20:10:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 18 Feb 2004 19:10:06 -0600 Subject: PEP-0315--Enhanced While Loop: An idea for an alternative syntax In-Reply-To: References: <7x65e4j3oa.fsf@ruckus.brouhaha.com> <4033084D.1AEA1ADA@alcyone.com> <40330A95.DF809EAA@alcyone.com> <4f0a9fdb.0402180457.6c96853d@posting.google.com> Message-ID: <20040219011006.GB11071@unpythonic.net> On Wed, Feb 18, 2004 at 05:41:10PM +0000, Terry Carroll wrote: > With read() instead of readline(), then. > > I've certainly run into this using urllib2. Push the "yucky" while 1: loop into a generator function, and then use a regular "for" loop in the multiple places you need to handle a file in this way: def chunks(f, blocksize=512): while 1: b = f.read(blocksize) if not b: return yield b Use it like this: >>> f = open("/etc/fedora-release") >>> for c in chunks(f, 4): print repr(c), ... 'Fedo' 'ra C' 'ore ' 'rele' 'ase ' '1 (Y' 'arro' 'w)\n' The "while 1:" loop is now so short that a simple glance can take it all in, and the site with the logic uses the much clearer 'for' loop. Jeff From dbentley at stanford.edu Thu Feb 12 09:10:01 2004 From: dbentley at stanford.edu (Daniel Timothy Bentley) Date: Thu, 12 Feb 2004 06:10:01 -0800 Subject: correct way of running a sub-process Message-ID: What is the (hopefully unique) obvious way of runnign a sub-process if I want to get the exit code and input without resorting to multi-threading? It seems like I should be able to do the following: foo = popen2.Popen3(cmd) foo.wait() foo.fromchild.read() But, it seems like on my system (a Sun Ultra 30 running Solaris 8) this will hang if the input happens to have more than about 12k of text. I'm guessing this is a buffersize issue, but it would be a mistake to assume at compile time an output size for the child process. Couldn't wait be modified to actually wait until a process exits by buffering? While we're at it, is there any way to read/wait with a time-out? I.e., read more than 0 bytes, unless it takes more than a time-out value, so I can run sub-processes that terminate? -Dan From teiffel at attglobal.net Wed Feb 25 07:39:34 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Wed, 25 Feb 2004 07:39:34 -0500 Subject: os.walk walks too much Message-ID: <403C9786.1040903@attglobal.net> Hello, I am using Pyton 2.3 I desire to walk a directory without recursion this only partly works: def walk_files() : for root, dirs, files in os.walk(top, topdown=True): for filename in files: print( "file:" + os.path.join(root, filename) ) for dirname in dirs: dirs.remove( dirname ) because it skips all the subdirectories but one. this *does not* work at all def walk_files() : for root, dirs, files in os.walk(top, topdown=True): for filename in files: print( "file:" + os.path.join(root, filename) ) dirs = [] This is surprizing to me. Is this a glitch ? How should I implement this ? Maybe it would be good to put it in the os. walk documentation ? Cheers, Marcello From amk at amk.ca Fri Feb 27 21:42:22 2004 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 27 Feb 2004 20:42:22 -0600 Subject: Python as replacement for PHP? References: <403fa54b@news.zianet.com> Message-ID: On Fri, 27 Feb 2004 13:50:09 -0700, Erik Johnson wrote: > 1) PHP seems to have a pretty good integration/driver with PostgreSQL. > If we were to switch to Python, what modules/drivers are available to talk > to PosgreSQL and is it as functional as PHP's support? There are several; for some reason I don't really understand, there are multiple Python/PostgreSQL modules. Most of them will support the standard DB-API described in PEP 249. Personally I use PygreSQL with Quixote as the web framework. Note that I'm one of the developers on a Python web framework called Quixote (www.quixote.ca), so my answers are slanted in that direction. If you're in the Washington DC area, I'll be giving a Quixote tutorial next weekend at a Linux user group meeting; see novalug.tux.org for meeting details. > 3) Does Python have an analog to strtotime()? (For those not familiar > with that function, it converts a wide range of date formats as string into > time_t value. Can handle things like "now", "+24 hours", "-3 days", > "yesterday 06:00PM MST", "January 23, 2004", "2004-02-26 18:00:00 -07", > etc.) mxDateTime has an extensive parsing module. There's a PEP for adding date parsing to core Python, but it may not get done for 2.4. > 4) I am vaguely aware of Apache's modpython. We are currently running > apache, but I'm real green when it comes to configuring/running/managing > Apache. I don't really understand what all modpython does for me. Generally It embeds a Python interpreter in the Apache daemon, so you can intersperse Python processing in Apache's request processing. There's going to be a mod_python tutorial at the upcoming PyCon conference; again, if you're in the DC area you might consider going in order to talk to existing Python/web developers. Note that embedding the interpreter in Apache isn't a requirement; you can also run applications using SCGI, or FastCGI instead. You'd have to carry out benchmarks to see which one ends up running fastest for your application. > 5) A PHP script can freely jump in and out of static HTML and script > code with tags. This is sometimes handy. Can you do the same thing > with Python? There are various templating packages available for Python, such as Cheetah (vaguely PHPish), ZPT (XML-based), or PTL (part of Quixote). Personally I don't find embedding Python code in HTML to be a good idea; it's too difficult to refactor, and PTL has various convenient features for automatically quoting HTML. > a forked process, and if so, is that too expensive? Do you know of > comparable packages for Python? One of the upsides of using Python is that many more non-Web-related packages have been written for it. Scientific programming is a significant application domain for Python, so several graphing packages have been written. You could use Reportlab for PDF generation, Chaco, Gnuplot, or Gist for graphing, or the Python Imaging Library for generating PNGs/JPGs. --amk From bokr at oz.net Fri Feb 6 13:56:03 2004 From: bokr at oz.net (Bengt Richter) Date: 6 Feb 2004 18:56:03 GMT Subject: PEP 327: Decimal Data Type References: <6ltk10h30riel0lghd18t5unjco2g26spi@4ax.com> Message-ID: On 5 Feb 2004 09:16:51 -0500, aahz at pythoncraft.com (Aahz) wrote: >In article <6ltk10h30riel0lghd18t5unjco2g26spi at 4ax.com>, >Stephen Horne wrote: >>On Fri, 30 Jan 2004 09:49:05 -0300, "Batista, Facundo" >> wrote: >>> >>>I'll apreciate any feedback. Thank you all in advance. >> >>My concern is that many people will use a decimal type just because it >>is there, without any consideration of whether they actually need it. >> >>95% of the time or more, all you need to do to represent money is to >>use an integer and select appropriate units (pence rather than pounds, >>cents rather than dollars, etc) so that the decimal point is just a >>presentation issue when the value is printed/displayed but is never >>needed in the internal representation. > >The problem lies precisely in that representation. For starters, a >binary integer is O(n^2) for conversion to decimal printing. Then Please clarify. What is your "n" in that? Regards, Bengt Richter From omission9 at invalid.email.info Sat Feb 21 00:32:50 2004 From: omission9 at invalid.email.info (omission9) Date: Sat, 21 Feb 2004 05:32:50 GMT Subject: New user needs help In-Reply-To: <103dqa9m48nj792@corp.supernews.com> References: <103dqa9m48nj792@corp.supernews.com> Message-ID: <64CZb.19719$wD5.7887@nwrddc03.gnilink.net> John wrote: > I am new to using Python. Everytime I run this program it prints "The lowest > common factor is 0", no matter what numbers I use. Can anybody see anything > wrong with my program? Thanks in advance. > > > > def getnum1(a): > a = input("What is the first number?") > if a == 0: > getnum1(a) > def getnum2(b): > b = input("What is the second number?") > if b == 0: > getnum2(b) > def euclid(num1, num2, num3, num4): > if num1 < num2: > num3, num4 = num1, num2 > num1, num2 = num4, num3 > euclid(num1, num2, num3, num4) > elif num2 != 0: > num3, num4 = num1, num2 > num1 = num4 > num2 = num3 % num4 > euclid(num1, num2, num3, num4) > else: > print "The lowest common factor is: ", num1 > a = 0 > getnum1(a) > b = 0 > getnum2(b) > x, y = 2, 100 > euclid(a, b, x, y) This is a nice simple example of what is called "scope" and how it can trick a beginner. Put as simply as possible,"a" and "b" are actually defined twice. Once "locally" in the getnum functions and another time "globally" . When you set a and b to the user input in the functions the other a and b have no idea about this assignment. Below is a slight revision which return the a and b set by the user back to where they are called. By putting a simple print statement in the script you can see where the values are set and that can help you. I hope that helps. There is probbaly a couple of other changes you could make as well but nothing too major, in my opinion. def getnum1(a): a = input("What is the first number?") if a == 0: getnum1(a) return a def getnum2(b): b = input("What is the second number?") if b == 0: getnum2(b) return b def euclid(num1, num2, num3, num4): print num1, num2, num3, num4 if num1 < num2: num3, num4 = num1, num2 num1, num2 = num4, num3 euclid(num1, num2, num3, num4) elif num2 != 0: num3, num4 = num1, num2 num1 = num4 num2 = num3 % num4 euclid(num1, num2, num3, num4) else: print "The lowest common factor is: ", num1 a = 0 b = 0 a=getnum1(a) b=getnum2(b) x, y = 2, 100 euclid(a, b, x, y) From malkarouri at yahoo.co.uk Fri Feb 27 08:29:57 2004 From: malkarouri at yahoo.co.uk (Muhammad Alkarouri) Date: 27 Feb 2004 05:29:57 -0800 Subject: WSDL in python? Message-ID: After googling for some time, and checking ZSI and other solutions, I have not found a way to write a web service application (server that is) in Python and automatically create a WSDL description for it. The question: - Does such a solution exist (WSDL server support)? - if not, any way to deploy python web services using WSDL, even if it needs learning another package/syntax/...? Please, don't suggest to me xml-rpc, as I have some compatibility issues.. Regards, karouri From peter at cendio.se Tue Feb 17 10:08:33 2004 From: peter at cendio.se (Peter Astrand) Date: Tue, 17 Feb 2004 16:08:33 +0100 (CET) Subject: [Announce] pyobfuscate Message-ID: I've written a Python source code obfuscator. The project home page is http://www.lysator.liu.se/~astrand/projects/pyobfuscate/. I'm including a copy of the README file below. pyobfuscate - Python source code obfuscator =========================================== pyobfuscate is a source code obfuscator: It makes Python source code hard to read for humans, while still being executable for the Python interpreter. Why obfuscate? -------------- Obfuscation makes little sense for Open Source (http://www.opensource.org/) programs, but vendors developing commercial applications are usually not happy with shipping the original source code to customers. Several obfuscators for other languages, like Java, already exists. With Python, the problem is even more severe than with Java, because Python bytecode is not compatible between different Python versions. Also, bytecode is very easy to "decompile" to source code by using "decompyle": http://www.crazy-compilers.com/decompyle/. If shipping original source code is the only option for distributing Python applications, then many vendors might choose another programming language instead. What does pyobfuscate do? ------------------------- pyobfuscate transforms the source code in several ways. Some of these transformations are reversible (can be "un-obfuscated"); some are not. Here's a list of what pyobfuscate currently does: * Removes comments and docstrings (not reversible) * Changes indentation (reversible) * Adds whitespace between tokens (somewhat reversible) * Renames functions, classes and variables (not reversible) * Inserts bogus lines instead of blank lines. Limitations ----------- pyobfuscate operates on one single source file at a time. It does not obfuscate the interface between several files. pyobfuscate cannot obfuscate methods, class variables or other attributes, currently. See the TODO for more information. -- Peter ?strand www.thinlinc.com Cendio www.cendio.se Teknikringen 3 Phone: +46-13-21 46 00 583 30 Link?ping From bhoel at web.de Wed Feb 25 14:56:52 2004 From: bhoel at web.de (Berthold Höllmann) Date: Wed, 25 Feb 2004 20:56:52 +0100 Subject: Problem with OptionParser References: Message-ID: Florian Lindner writes: > Hello, > I've this tiny Python sample: > > - - - - > #!/usr/bin/python > > from optparse import OptionParser, OptionValueError > > def option_callback(option, opt, value, parser, *args, **kwargs): > pass > > optparser = OptionParser() > optparser.add_option("-t", "--type", action="callback", > callback=option_callback, type="string") > (options, arguments) = optparser.parse_args() > - - - - As a workaround you could set "metavar", I posted a first fix to the Optik mailing list. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From haasje at welmers.net Fri Feb 6 05:57:38 2004 From: haasje at welmers.net (Bastiaan Welmers) Date: Fri, 06 Feb 2004 11:57:38 +0100 Subject: Finding messages in huge mboxes References: <401eb54c$0$315$e4fe514c@news.xs4all.nl> <4f0a9fdb.0402022331.394b3002@posting.google.com> Message-ID: <40237350$0$317$e4fe514c@news.xs4all.nl> Miki Tebeka wrote: > Hell Bastiaan, > >> I need find messages in huge mbox files (50MB or more). >> ... >> Anyone who has a better idea? > I find that sometime using the unix little utilties (which are > available for M$ as well) gives very good performance. > Sounds as a very good idea. Tanks. /Bastiaan From uche at ogbuji.net Fri Feb 13 10:20:29 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 13 Feb 2004 07:20:29 -0800 Subject: Splitting a DOM References: Message-ID: brice.vissiere at costes-gestion.net (Brice Vissi?re) wrote in message news:... > Hello, > > I would like to handle an XML file structured as following > > > ... > > > ... > > ... > > > From this file, I want to build an XML file for each STEP block. > > Currently I'm doing something like: > > from xml.dom.ext.reader import Sax2 > from xml.dom.ext import PrettyPrint > > reader = Sax2.Reader() > my_dom = reader.fromUri('steps.xml') > steps = my_dom.getElementsByTagName('STEP') > > i=0 > for step in steps: > tmp = file('step%s.xml' % i,'w') > tmp.write('\n') > PrettyPrint(step , tmp , encoding='ISO-8859-1') > tmp.close() > i+=1 > > But I'm pretty sure that there's a better way to split the DOM ? Here's an Anobind recipe: --- % --- #Boilerplate set-up import anobind from Ft.Xml import InputSource from Ft.Lib import Uri #Create an input source for the XML isrc_factory = InputSource.DefaultFactory #Create a URI from a filename the right way file_uri = Uri.OsPathToUri('steps.xml', attemptAbsolute=1) isrc = isrc_factory.fromUri(file_uri) #Now bind from the XML given in the input source binder = anobind.binder() binding = binder.read_xml(isrc) #File splitting task import tempfile #The direct approach i = 0 for folder in binding.xbel.folder: fout = open('step%s.xml', 'w') folder.unbind(fout) fout.close() i += 1 --- % --- To use XPath replace the line for folder in binding.xbel.folder: With for folder in binding.xpath_query(u'xbel/folder'): Anobind: http://uche.ogbuji.net/tech/4Suite/anobind/ --Uche http://uche.ogbuji.net From rdgentry1 at cablelynx.com Thu Feb 19 19:35:02 2004 From: rdgentry1 at cablelynx.com (P Gentry) Date: 19 Feb 2004 16:35:02 -0800 Subject: Nature of Zope... References: Message-ID: mailslayer99 at yahoo.com (Scott) wrote in message news:... > Greetings everyone, > > I have a couple general questions regarding the nature of Zope? > > Also, please forgive me if this is not the proper forum for this type > of question. If so, please disregard. > > I'm interested in developing business apps, not just developing a > content management site. ... The CM site packages you see are add-on Zope Products, not central to Zope itself. > ... I'm wondering if Zope is right for me. My > programming exposure has been limited to simple PHP and not even from > an OOP perspective, just simply dropping logic into HTML pages? Just the sort of person Zope was meant to help out, by providing pre-built infrastructure and a means of taking advantage of it. > I'm interested in building deployable apps with administration built > into the app itself, not necessarily being administered from within > Zope. For example, I would create an app with its own administrator, > its own staff, and its own technicians. These being completely > separate from the Zope management console. (The users and managers of > this app would be completely unaware of Zope). Already done! You're confusing the Zope Management Interface (ZMI) which is designed to help manage Zope _installations/sites_ with the CM management interface meant to manage the CM app. You can use/extend the facilities of Zope's ZMI to delegate the management of the site or any fraction thereof, and your users don't have to use Zope's web ZMI if you provide something else. But _you_ can take advantage of the underlying facilities. > These users would have certain tasks that they can do based on of > course their ownership and security levels (these also being managed > by the apps administrator and perspective). Can these things be > controlled outside of Zope? ... Why? Zope already provides _precisely_ this facility (and things like proxy roles and acquisition that you'ld likely find _very_ useful). > ... If I did that would it break the core > "point" of Zope? Well, it won't break Zope as you seem determined to hide it as completey as possible in every way possible. And, "Yes, IMO it ignores the whole point of Zope!" It's as if you're saying you want to use Zope precisely to ignore every feature that makes Zope a unique solution. > ... Can and should I create a means to tie into the > ZopeDB from within the app for users and perms or can I store this in > a SQL database. ... Completely up to you and how much work you want to put into it. > ... If I create a deployable package and distribute it, > let it run, and simply restore my MySQL database in the event of a > failure and redeploy my original "Zope Project" after a > re-installation, could I be good to go? Or must I store users, > groups, perms, etc in the ZopeDB, or can I put users and their > permissions in a SQL DB? Zope already provides backup/recovery mechanisms (of sorts) that you can use to suit your situation no matter how you decide to to handle authentication/authorization. Most people use the facilities provided by Zope/ZODB, but some db based apps use the apps db storage. It's up to you. > If Zope is well suited to do this, what is the next step? I've > installed and ran through the tutorial, but It doesn't get into the > nitty gritty, I have no Python experience and no OOP experience. What you propose will not be easy then. You need to take advantage of every pre-built facility possible -- regardless of product/language. Zope just happens to be designed with the goal of helping a "regular joe" get a big jump start. But there is no magic in Zope -- just Python! (Which some of us find just as good as magic) > I plan on designing apps that have a lot of logic tied into it? I > have no idea where I can find out how to do certain things, for > example, making database modifications based on certain criteria that > a user does in the app, modifying the DB schema, creating the actual > HTML forms based on SQL data, dropping in the logic behind the scenes. > The best way I've learned in the past is with tutorials, which > explain things step by step and why. The "core" of Zope provides just these facilities. All the more reason to select a software base with a community that will support your efforts with aid and advice -- one that _you_ are comfortable with. > In order to use Zope, is it mandatory to know Python and OOP to build > complex apps. ... Not to mince words, but Yes! >... The reason for me wanting to use Zope is so I wouldn't > have to learn another language, ... What other language? PHP? Perl? C? Visual Basic? > ... so that development could go fast, so > that a person without extensive programming experience could build a > logical business application. Do you mean "end users"? Again, this is what Zope's design goals are. > If it helps, the three apps I'm working on are: > > One, an asset management database, with admins making schema changes, > and assigning groups and users to modify add certain pieces. Sorta depends on the nature of the assets, doesn't it? And the db backend? Experience is to _never_ let the well intentioned near the schema and choose admins _very_ carfully. You can use Zope's facilities to help (a lot!) or ignore them and roll your own. > And two others, one a change management system and the other a trouble > ticket system, once again admins creating and managing users (staff > and tech), staff members creating and managing tickets and assigning > them to techs, and techs managing their assigned tickets. Everything > is queue based with ownership. This sounds much like a work flow product. Zope has several such beasts available for your pleasure, some fairly "complete" and others just a framework. > Thanks so much for your help and time? You might get a better sense of what your up against trying to do all this by posting to the Zope mailing lists: http://www.zope.org/Resources/MailingLists OTOH Why on earth are you wanting to use Zope to effectively duplicate the infrastructure functionality that Zope was _designed_ to provide? Any number of other software packages will provide web publishing without you having to replicate features (because they are not there) or database access such as PHP provides. Most every item you lisedt is _already_ provided by Zope -- some almost "out-of-the-box". Take a look at _all_ the products available (literally 100s) that already provide pieces of what you want. For someone whose "programming exposure has been limited to simple PHP", the tasks you've set yourself are no easy thing to pull off -- even, in fact, by those working full-time and with greater experience/skills. That's what Zope is for -- take advantage of the work others have provided for you as well as the experince of a community much more familiar with Zope and its innards than you. They are a quite helpful lot. Only you can decide if Zope is a comfortable fit or not. From things you've said above, I don't think you have a very good idea of what Zope provides -- either in the core product or by way of add-on products. The tutorial is notoriously incomplete and inadequate as a means to get familiar with Zope. Read the Zope book. If that's too much for you, then Zope is _not_ for you. Whatever you decide, good luck, prg email above disabled To the NG -- sorry for the long post. From mwilson at the-wire.com Sat Feb 7 10:16:44 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 07 Feb 2004 10:16:44 -0500 Subject: Warnings killing my performance References: <153fa67.0402060933.13840e8c@posting.google.com> <153fa67.0402070445.77121b2e@posting.google.com> Message-ID: In article <153fa67.0402070445.77121b2e at posting.google.com>, kylotan at hotmail.com (Kylotan) wrote: >"Terry Reedy" wrote in message news:... >> "Kylotan" wrote in message >> news:153fa67.0402060933.13840e8c at posting.google.com... >> > And my second is, is there a quick way of taking an integer, shifting >> > it left 13 bits (or multiplying by 2 ** 13, whatever), discarding any >> > excess bits, and which won't cause a warning? >> >> Have you tried masking off the upper 13 bits *before* the shift? So that >> there is no overflow to warn about? Does this make any sense? > >Yes, it makes perfect sense... but unfortunately getting rid of that >specific warning isn't enough. As noted in my first post, something is >going through the warnings mechanism silently. I changed the code to >this: > >def IntToRandFloat(x): > """Given a 32-bit integer, return a float in [-1.0, 1.0]""" > x = int(x) & 0x3FFFF # Preserve lowest 18 bits, to remove >overflow. > x = int(x << 13) ^ x # Shift left 13 bits. > return (1.0-((x*(x*x*15731+789221)+1376312589)&0x7fffffff)/1073741824.0) > >And the profiler is still showing a call to warn() and warn_explicit() >for each call to IntToRandFloat. I'm also having to preserve 18 bits >instead of the desired 19 because the warning displays when I use 18, >presumably because it includes the sign bit. However now I think I am >damaging the distribution of the function (which is supposed to >generate deterministic noise). I notice that you're effectively cubing x, so you could only keep 10 bits of it and be sure of avoiding 32-bit overflow. Maybe a linear pseudo-random formula would save some trouble. But it appears that random.randint also generates invisible warnings. The warnings go away with x = long(x << 13) ^ x Regards. Mel. From theller at python.net Mon Feb 23 11:33:37 2004 From: theller at python.net (Thomas Heller) Date: Mon, 23 Feb 2004 17:33:37 +0100 Subject: python 2.3.2 hangs when returning an int References: Message-ID: rus20376 at salemstate.edu (omission9) writes: > Any advice on the following would be much appreciated. I have thrown > everything I have at it and am completely stumped. I apologize for the > length, I have tried to be as succint as possible. > > I have a pythoncard/wxPython application. The application works well > except that users were reporting occasional crashes. The application > would simply stop and just hang. I was able to reproduce the bug > faithfully and ran the application in the python debugger pdb.py. > The trace is below and I simply cannot understand why it is hanging > where it is. The application gets stuck executing > > return len(self.data[0]) Does pythoncard or wxPython (or your program) use weak references? There have been serious bugs fixed with weakrefs in Python 2.3.3. Thomas From rmkrauter at yahoo.com Wed Feb 4 21:41:43 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed, 04 Feb 2004 21:41:43 -0500 Subject: an ingrate newbie complains In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE0128F37D@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE0128F37D@au3010avexu1.global.avaya.com> Message-ID: <1075948903.4424.57.camel@vaio> I didn't phrase that well. I understand *why* they don't work; I just meant to point out to OP that it's not an issue with the way iterators work in python; its because some of the variables referenced in the some of the list comps had been initialized. So they *appear* to have unexpected behaviour. In the absence of that accidental initialization, they don't work at all, as one should expect, since variables are referenced before they are defined. Thanks for the suggestion, though. Rich On Wed, 2004-02-04 at 21:25, Delaney, Timothy C (Timothy) wrote: > > From: Rich Krauter > > > > Are some of these examples only working because and y have been > > initialized by previous runs? > > I tried deleting x and y between list comprehensions and they > > don't work anymore. > > Indeed. > > >>> f = lambda x,y: x*y+2*pow(y,2) > >>> g = lambda x: 3*pow(x,2) > >>> l = [1,2,3,4,5] > >>> [f(x,y) for (x,y) in [(x,g(x)) for x in l] if y>19] > [1539, 4800, 11625] > >>> del x > >>> del y > >>> [f(x,y) for x in l for y in [g(x)] if y>19] > [1539, 4800, 11625] > >>> del x > >>> del y > >>> [f(x,y) for y in [g(x)] if y>19 for x in l] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > >>> [f(x,y) for y in [g(x)] for x in l if y>19] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > > Try expanding them to the non-list comp form and see where the problems are ... > > Tim Delaney From tjreedy at udel.edu Fri Feb 27 12:54:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Feb 2004 12:54:11 -0500 Subject: When things go badly in PyGC_Collect() References: <403e2bfd.9144015@news.t-online.de> <403f4f86_1@127.0.0.1> <6.0.1.1.2.20040227102910.02e02ec0@mail.fxtech.com> Message-ID: "Paul Miller" wrote in message news:6.0.1.1.2.20040227102910.02e02ec0 at mail.fxtech.com... > I'm running into a situation where the first call to PyCG_Collect during a > Py_Finalize, is dying a horrible death and throwing an exception. It is > after *MANY* iterations of the GC loop, so I haven't pinpointed where > exactly it is happening. > > Some notes - this is with Python 2.3 BTW, on Windows. The most recent one? I belive 2.3.3 had some bug fixes in this area. tjr From sdfATexpertuneDOTcom Mon Feb 23 13:44:04 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Mon, 23 Feb 2004 18:44:04 -0000 Subject: How to code a series of alternatives References: Message-ID: aahz at pythoncraft.com (Aahz) wrote in news:c1dhgu$orm$1 at panix3.panix.com: > > Simplest: > > if testvar in ('fred', 'bob'): > > Fastest: > > options = sets.Set('fred', 'bob'): > > ... > > if testvar in options: Thank you. I'd be embarassed, but I'm only grateful. Scott From aahz at pythoncraft.com Tue Feb 24 10:50:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 24 Feb 2004 10:50:56 -0500 Subject: Typecasting References: <15c2d03b.0402240646.558226ef@posting.google.com> Message-ID: In article <15c2d03b.0402240646.558226ef at posting.google.com>, Marco Aschwanden wrote: > >Don't forget the string-library with its atof-, atoi-, atol-method: > >>>> import string >>>> string.atoi('555') >555 That's deprecated. Use the type objects to convert. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Do not taunt happy fun for loops. Do not change lists you are looping over." --Remco Gerlich, comp.lang.python From amanzini at quercia.it Thu Feb 19 04:08:03 2004 From: amanzini at quercia.it (Andrea Manzini) Date: Thu, 19 Feb 2004 10:08:03 +0100 Subject: threading id generator ? Message-ID: <5.2.1.1.2.20040219095741.01405ac0@polifemo.quercia.it> Hi all, I'm a python newbie with a little problem; my need is to share an incrementing counter between threads; i.e. every time I create a new thread (which handle a single tcp/ip connection), I must assign an unique numeric ID to it, without reuse old numbers... In example: thread-1 id: 1 thread-2 id: 2 thread-3 id: 3 thread-100 id: 100 thread-n id: n which locking semantic I must use to implement a shared generator in a thread ? thanks in advance :) Questo messaggio di posta elettronica contiene informazioni di carattere confidenziale rivolte esclusivamente al destinatario sopra indicato. E' vietato l'uso, la diffusione, distribuzione o riproduzione da parte di ogni altra persona. Nel caso aveste ricevuto questo messaggio di posta elettronica per errore, siete pregati di segnalarlo immediatamente al mittentee distruggere quanto ricevuto (compresi file allegati) senza farne copia. Qualsivoglia utilizzo non autorizzato del contenuto di questo messaggio costituisce violazione dell'obbligo di non prendere cognizione della corrispondenza tra gli altri soggetti, salvo piu grave illecito, ed espone il responsabile alle relative conseguenze. Confidentiality Notice. This electronic mail transmission may contain legally priviledge and/or confidential information. Do not read this if you are not the person(s) named. Any use, distribution, copying or disclosure by any other person is stricly prohibited. If you received this trasmission in error, please notify the sender and destroy the original transmission and its attachments without reading or saving in any manner. From kristofer at hotpop.com Wed Feb 18 09:34:05 2004 From: kristofer at hotpop.com (Kristofer Wouk) Date: Wed, 18 Feb 2004 09:34:05 -0500 Subject: pygame and tutorial In-Reply-To: References: Message-ID: Diez B. Roggisch wrote: > ardechou wrote: > > >>hi >>i want to find a tutorial for pygame >>but not on the site of pygame , just a tutorial for a beginner , to > > > Why not on the site of pygame? There is everything you request there, most > things on site, other tutorials are linked to. > Just agreeing here. In fact, I'm not sure if there is any documentation available for pygame that isn't already on the main pygame site (pygame.org). When it comes to starting an application, putting text in the main window and things like that, I'd say have a look at the "Chimp Line By Line" tutorial on the pygame website. Kris From lubowiecka at go2.pl Mon Feb 16 10:58:45 2004 From: lubowiecka at go2.pl (Ringwraith) Date: Mon, 16 Feb 2004 16:58:45 +0100 Subject: a simple question... how to detect click action in another module? References: <402fef31$0$564$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Uzytkownik "Brian Kelley" napisal > If you could be more specific about what GUI you are using, we could > give you a more specific answer. Oh, I forgot to add that I use Tkinter! Anyway you helped me very much!!!! The link to the 'recipe' describing how to implement the observer pattern in Python was great!!! Thanks to You I solved my problem! Thanks!!! Best Regards, Sylwia From ark at acm.org Wed Feb 18 00:18:50 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 18 Feb 2004 05:18:50 GMT Subject: PEP-315 ("do" loop) References: <10341ha7te8bpb8@news.supernews.com> <7xekstqyzy.fsf@ruckus.brouhaha.com> Message-ID: <_ACYb.41934$hR.981424@bgtnsc05-news.ops.worldnet.att.net> > Most other languages have a way to put the test at the bottom of the loop. > Pythonically that could look like: > > repeat: > line = sys.stdin.readline() > until: line == '\n' > > That would have similar indentation characteristics to try...finally. I believe it would be more useful to allow the test to be anywhere in the loop, not just at the beginning or at the end. Even better would be to allow more than one test. From per.corell at privat.dk Mon Feb 9 18:12:39 2004 From: per.corell at privat.dk (P.C.) Date: Tue, 10 Feb 2004 00:12:39 +0100 Subject: Had Phyton suggested References: <4026488d$0$95048$edfadb0f@dread11.news.tele.dk> <40264f37$0$95017$edfadb0f@dread11.news.tele.dk> Message-ID: <40281346$0$95068$edfadb0f@dread11.news.tele.dk> Hi I am still here, ----- thanks to those who ansvered , need to follow the links before I return. P.C. From jjl at pobox.com Fri Feb 6 19:58:59 2004 From: jjl at pobox.com (John J. Lee) Date: 07 Feb 2004 00:58:59 +0000 Subject: HTTPSConnection Problems References: Message-ID: <873c9niu24.fsf@pobox.com> ngps at netmemetic.com (Ng Pheng Siong) writes: > According to John Glista : [...] > > What I don't understand is why the > > HTTPSConnection is asking for a private key. The private key resides > > on the server; clients do not have access to this. > > You're talking about the server's key and certificate. There are also > *client* keys and certificates: A server may demand a client produces a > certificate and demonstrates possession of the corresponding private key as > a means of authentication and authorisation. [...] That's exactly what the key and cert are for in httplib. There is no support for server auth. I got this backwards too, until Martin v. Loewis set me straight. John From news at yebu.de Thu Feb 19 10:58:02 2004 From: news at yebu.de (Karl Scalet) Date: Thu, 19 Feb 2004 16:58:02 +0100 Subject: multiply utple or list In-Reply-To: References: <4034c694$0$706$5402220f@news.sunrise.ch> Message-ID: Diez B. Roggisch wrote: >> >>> import operator >> >>> [ operator.mul(x,2) for x in (4,5)] > > > Why not simply * ? > > [ x * 2 for x in (4,5)] > oops, of course. I had the map function in mind, which only accepts a function, but this would come to something like: li=(4,5) map(operator.mul, li, (2,)*len(li)) and is certainly worse then list comprehension :-) regards, Karl From fumanchu at amor.org Sun Feb 22 19:33:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 22 Feb 2004 16:33:03 -0800 Subject: Where can I post a new debugger? Message-ID: Ziaran wrote: > I like URLs, they are so easy to click, and there is always > the possibility for pleasant surprises inside. ...and an equal opportunity for unpleasant suprises. No, that's not true. Not equal. The unpleasant:pleasant ratio is more like 1,000,000 to 1. > And here is the link again; hoping this time people in need > will believe it worth while to click: It's all about trust, Ziaran. A URL without explanation undermines trust. A domain named "freehosting.net" undermines trust. A hotmail sending address undermines trust. Etcetera. It might be the greatest code since bread[:], but to "believe it worthwhile to click" has nothing to do with that. Hope you can tell I'm not angry--just informing you why I (and many others) won't click your link. Robert Brewer MIS Amor Ministries fumanchu at amor.org From hauck at gseos.com Mon Feb 16 07:35:14 2004 From: hauck at gseos.com (Tommy Trojan) Date: Mon, 16 Feb 2004 04:35:14 -0800 Subject: Hiding modules References: <4f0a9fdb.0402160359.33f90363@posting.google.com> Message-ID: Mike, thanks for the tip. I thought along the same lines, but that doesn't get around the problem that the user could just embed an import in a script, or import a script that I provide and that internally uses the module that should not be exposed, i.e.: >>> import UserModule in UserModule: import RestrictedModule This would get around the simple loop in checking the input arguments of the interactive prompt. It needs to be a hook that is further down in the system. The problem with an import hook is that it would need to distinguish when it is okay to import the module (when I call it) and when it is not okay (when my user calls it). Thanks, Thomas "Miki Tebeka" wrote in message news:4f0a9fdb.0402160359.33f90363 at posting.google.com... > Hello Tommy, > > > > Is there anything that can be done to import modules conditionally? > > Any ideas? > Writing a custom REPL (read-eval-print-loop) should be easy enough: > import re > split = re.compile("\s+").split > > forbidden = ("os", "sys") > > def repl(): > while 1: > s = raw_input(">>> ").strip() > ok = 1 > if s.startswith("import"): > for module in split(s.strip())[1:]: > if module in forbidden: > print "can't use %s module" % module > ok = 0 > break > if ok: > exec(s) > > while 1: > repl() > > HTH. > Miki From scary at movie.com Wed Feb 4 03:17:01 2004 From: scary at movie.com (marvin) Date: Wed, 4 Feb 2004 03:17:01 -0500 Subject: newbie with a gui question References: <1020nse8569lr70@corp.supernews.com> Message-ID: <1021ak4984ivb20@corp.supernews.com> "niekko" wrote in message news:1020nse8569lr70 at corp.supernews.com... > I wrote a program for a class and now have to > make a gui for it. I've done several hours of > research and am stuck. Can someone point me > in the right direction, please???? > > Here's the original program.. > > > #Petty_Cash.py > from Tkinter import * > import time > import string > > true = 1 > false = 0 > > class Petty_Cash: > def __init__(self, initial): > self.balance = initial > print "Account created. Your beginning balance is", "$", > self.balance > print time.ctime() > > def deposit(self, amt): > self.balance = self.balance + amt > print "$", + amt, "has been deposited to your account." > print "Your new balance is", self.balance > print time.ctime() > > def withdraw(self, amt): > if self.balance >= amt: > self.balance = self.balance - amt > print "$",- amt, "has been withdrawn from your account." > print "Your new balance is", "$", self.balance > print time.ctime() > else: > print "Insufficient funds in account to withdraw", "$", amt > print "Please ensure sufficient funds exist for withdrawl > amount" > print "Your current balance is", "$", self.balance > print time.ctime() > > def getbalance(self): > print time.ctime() > return self.balance > > hi- why not give this a try. i never tried it myself. it claims to be really easy ...function driven. . what the hell is lamda anyways? sounds like some kind of greek organization. http://www.ferg.org/easygui/index.html if this is a series of programs that you will be doing and fancy events are going to be needed you will have to look at something like tkinter or wxpython when it gets more advanced. this class is interesting. we had an exercise with an elevator. our teacher said if we made an error we'd send the elevator through the roof like the cartoons :-) have fun! later, marvin From post400 at prontomail.com Wed Feb 18 18:10:14 2004 From: post400 at prontomail.com (post400) Date: 18 Feb 2004 15:10:14 -0800 Subject: the best book for learning python !? References: Message-ID: Hi, thanks for your opinions ! Terry , you're saying that you keep The Pyhton Cookbook in your bathroom !? That's why I asked about books ! It's a lot easier to keep them in bathrooms and read while doing stuff ! PDAs , laptops or listings are not exactly perfect for bathrooms ! bye post400 From anhtt at hotmail.com Mon Feb 23 01:21:47 2004 From: anhtt at hotmail.com (Tran Tuan Anh) Date: 22 Feb 2004 22:21:47 -0800 Subject: Help: Is Python suitable? Message-ID: Hi, I have an programming assignment, and would like to try out Python. I need to read in a simple textual language (does Python have a scanner, and parser?), and do some processing. After that, generate some codes in an other language. Basically, the program generates code for another program based on some textual input. I can do it in Java of course. However, it will be quite cumbersome. I wonder if Python is more suitable for this kind of job? Hope someone could enlighten me on this matter? Thanks a lot! Tuan Anh P/S: I knew Java, Pascal very well. I also touch a bit on C/C++, Scheme, SML. From tkpmep at hotmail.com Sun Feb 22 15:13:12 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 22 Feb 2004 12:13:12 -0800 Subject: Reading from text files Message-ID: In the course of playing around with file input and output, I came across some behavior that is not quite intuitive. I created a simple text file, test.txt, which contains only 3 lines, and which I expect will have 5 characters (the digits 1, 2, and 3, and two newline characters, the first after 1 and the second after 2). Here it is in all its glory: 1 2 3 However, when I read it using open()and then view it using >>> file.seek(0); file.read(); file.tell() I get: '1\n2\n3' 7L Python thinks there are 7 characters in the file! If I type >>> file.seek(1); file.read() OR >>>file.seek(2); file.read() I get '\n2\n3' but >>> file.seek(3); file.read() gives me what I expected to get with file.seek(2); file.read() '2\n3' It appears that Python sometimes counts each of the newline escape sequences as 2 separate characters and at other times as 1 indivisible character. What is the appropriate way to think about these characters? Thomas Philips From alloydflanagan at comcast.net Tue Feb 17 11:50:46 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 17 Feb 2004 08:50:46 -0800 Subject: python memory usage References: Message-ID: Peter Maas wrote in message news:... > In a recent discussion somebody claimed that python executable has > a huge memory consumption compared to perl and tcl, about 18 MB. > I didn't believe that and checked on my machine (SusE 7.3, Linux > 2.4, Perl 5.6.1, Python 2.3.2, Tcl 8.3), command > ps -o "cmd rss vsize", results in kBytes: > > CMD RSS VSZ > perl 984 2760 > python 2556 4188 > tclsh8.3 1100 2316 > Has anybody got comparable figures for a Java process? From jimmy at retzlaff.com Thu Feb 26 04:18:11 2004 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Thu, 26 Feb 2004 01:18:11 -0800 Subject: Some language proposals. Message-ID: Jacek Generowicz writes: > > >>> class foo: pass > ... > >>> class callable: > ... def __call__(self): print self > ... > >>> instance = callable() > >>> def meth(self): print self > ... > >>> foo.meth = meth > >>> foo.instance = instance > >>> f = foo() > >>> f > <__main__.foo instance at 0x815fa64> > >>> f.meth() > <__main__.foo instance at 0x815fa64> # self == f > >>> f.instance() > <__main__.callable instance at 0x815f624> # self != f > >>> f.meth > > > >>> f.instance > <__main__.callable instance at 0x815f624> # Hmm, it's not a method > >>> > > meth behaves like a Python method, instance does not. > > Find some way of making callable [from above] use > types.FunctionType.__get__. I don't see what code examples could > possibly help in specifying the problem more clearly (unless the code > is the solution, of course). The function new.instancemethod will build an instance method for you, but your callable needs two selves, one for the instance of callable and another for the instance of foo so that it can access the state of each: >>> class foo: pass ... >>> class callable: ... def __call__(self_callable, self_foo): ... print self_callable, self_foo ... >>> instance = callable() >>> import new >>> foo.instance = new.instancemethod(instance, None, foo) >>> f = foo() >>> f <__main__.foo instance at 0x008FAB70> >>> instance <__main__.callable instance at 0x008FABE8> >>> f.instance() <__main__.callable instance at 0x008FABE8> <__main__.foo instance at x008FAB70> >>> f.instance > > But please don't bother unless you really want to do it for your own > entertainment. Writing Python code is always entertaining. :) Jimmy From stephan.diehlNOSPAM at gmx.net Fri Feb 27 07:15:31 2004 From: stephan.diehlNOSPAM at gmx.net (Stephan Diehl) Date: Fri, 27 Feb 2004 13:15:31 +0100 Subject: Internet-scale distributed computing? References: Message-ID: Skip Montanaro wrote: [...] > > 2. Are there tools available to make it easier to build such > applications? http://www-106.ibm.com/developerworks/edu/gr-dw-grpintro-i.html Maybe this has something usefull for you. Stephan > > Thx, > > Skip From newsgroups at jhrothjr.com Mon Feb 9 12:36:35 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 9 Feb 2004 12:36:35 -0500 Subject: converting base class instance to derived class instance References: <930ba99a.0401200413.5fae6fb9@posting.google.com><100qm0soklj3439@news.supernews.com> Message-ID: <102fhd93l1resfa@news.supernews.com> "Fran?ois Pinard" wrote in message news:mailman.1372.1076344361.12720.python-list at python.org... [John Roth] > If you want to do a little bit of deep magic, a factory function can > create an instance by calling object(), plug in whatever attributes > it wants and then change the __class__ attribute to whatever class it > wants before it returns the newly minted instance. It doesn't have > to go near anything that resembles a constructor (other than calling > object() to get a new instance, of course.) Hello, John, and gang! :-) How one does that? I'm merely curious. Using Python 2.3.3, the result of `object()' does not have a `__dict__', and seemingly may not be given a `__dict__' either. See: [John's answer] My goof. The correct call is: object.__new__(klas) where klas is the class object you want the instance constructed for. John Roth -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From dhwild at argonet.co.uk Tue Feb 24 17:02:15 2004 From: dhwild at argonet.co.uk (David H Wild) Date: Tue, 24 Feb 2004 22:02:15 +0000 (GMT) Subject: Thoughts about Python References: <15c2d03b.0402240311.395f5382@posting.google.com> <15c2d03b.0402241237.708cb4e8@posting.google.com> Message-ID: <4c85f44896dhwild@argonet.co.uk> In article <15c2d03b.0402241237.708cb4e8 at posting.google.com>, Marco Aschwanden wrote: > > Forget the speed and memory difference. The main argument for tuples > > as a separate type are to use as dictionary keys. How do you propose > > to handle dictionary keys without tuples? > Maybe I don't get the point here: Why do dictionaries need tuples to > work? I know that tuples can be used as keys... but how many times do > you need tuples as dictionary keys (it would be simple to turn a list > into an immutable string if really needed ("::".join(["a","b"]). But > maybe tuples are used within dictionary in a way I don't know. One of the reasons for doing this is that you can use a dictionary to represent points with coordinates in a space of two or more dimensions. In this case you need an immutable type, and you may need to get at its elements. -- __ __ __ __ __ ___ _____________________________________________ |__||__)/ __/ \|\ ||_ | / Acorn StrongArm Risc_PC | || \\__/\__/| \||__ | /...Internet access for all Acorn RISC machines ___________________________/ dhwild at argonet.co.uk From nir1408 at hotmail.com Mon Feb 23 11:45:53 2004 From: nir1408 at hotmail.com (Ziaran) Date: Mon, 23 Feb 2004 18:45:53 +0200 Subject: python 2.3.2 hangs when returning an int References: Message-ID: <403a2e62$1@news.bezeqint.net> I guess it is a thread synchronization progblem In that case some other thread modifies self.data leaving it empty in the time between the if statement expression is evalutaed and the time the return statement is executed. Can this be the case? "omission9" wrote in message news:defa238f.0402230806.69f365a0 at posting.google.com... > Any advice on the following would be much appreciated. I have thrown > everything I have at it and am completely stumped. I apologize for the > length, I have tried to be as succint as possible. > > I have a pythoncard/wxPython application. The application works well > except that users were reporting occasional crashes. The application > would simply stop and just hang. I was able to reproduce the bug > faithfully and ran the application in the python debugger pdb.py. > The trace is below and I simply cannot understand why it is hanging > where it is. The application gets stuck executing > > return len(self.data[0]) > > which is in this function > > def GetNumberCols(self): > if len(self.data) <= 0: > return 0 > else: > return len(self.data[0]) > > This works many many times during the applications execution, indeed > several successful runs of this line are visible immediatley above the > hang. I have also printed out the value of self.data. This is a list > containing 12 inner lists each of length 3 at the point of the hang and > is never larger than that. > What on earth could cause this to stop the interpreter cold in its > tracks without an exception being thrown? CPU usage on the machine is > high throughout the application's execution and stays as such after the > "hang" begins. I eventually kill the app although I have let it run for > a long time and it never leaves this line. > For what its worth, I am using python 2.3.2 on windows2k. > > Anyone have idea what could be happening? > > c:\python23\lib\site-packages\wxpython\grid.py(664)_setOORInfo()->None > -> return val > (Pdb) s > --Return-- > c:\python23\lib\site-packages\wxpython\grid.py(850)__init__()->None > -> self._setOORInfo(self) > (Pdb) s > > > c:\cygwin\home\ar881\development\bt_analysis\console\ndbbtable.py(17)__init > > __() > -> self.data = data > (Pdb) s > > > c:\cygwin\home\ar881\development\bt_analysis\console\ndbbtable.py(18)__init > > __() > -> self.colLabels = headings > (Pdb) s From maxm at mxm.dk Sun Feb 8 04:21:35 2004 From: maxm at mxm.dk (Max M) Date: Sun, 08 Feb 2004 10:21:35 +0100 Subject: ANNOUNCE: Build 200 of the pywin32 extensions (win32all) available In-Reply-To: References: Message-ID: <4025ff9f$0$197$edfadb0f@dread12.news.tele.dk> Mark Hammond wrote: > Hi all, > I have released a new version of the win32all extensions. I have also > changed significantly the way I release them. Great stuff Mark! It's an invaluable tool for us Windows drones. regards Max M From rus20376 at salemstate.edu Tue Feb 10 14:30:00 2004 From: rus20376 at salemstate.edu (omission9) Date: 10 Feb 2004 11:30:00 -0800 Subject: wxPython error "can't set focus to invalid window" References: Message-ID: rus20376 at salemstate.edu (omission9) wrote in message news:... > An application I have written is, suddenly it seems, throwing the > following error after being left in use for several hours. This does > not seem to occur with lighter usage. I am not 100% sure what causes > this? Anyone have any advice? Seen it before? > > Traceback (most recent call last): > File "PythonCardPrototype\binding.pyo", line 304, in _dispatch > File "wxPython\events.pyo", line 23, in GetEventType > wxPython.wxc.wxPyAssertionError: C++ assertion "wxAssertFailure" > failed in e:\Projects\wx2.4\src\msw\window.cpp(454): can't set focus > to invalid window To clarify this further this seems to occur when the application has been left running for several hours and the application has been minimized to the Windows task bar. The error happens when the user tries to maximize the window. The application has a child thread running(simply polls a dircetory and processes some text files) in the background. Does this help jog anyone's memory of what his could be? Blame windows? ;) From CGStartup at earthlink.net Sun Feb 1 00:20:26 2004 From: CGStartup at earthlink.net (Stan Schwartz) Date: 31 Jan 2004 21:20:26 -0800 Subject: Programmers Wanted for Computer Graphics Startup Near Philadelphia References: <2da21d6c.0401310807.671be3b7@posting.google.com> <%rUSb.37510$Wa.14668@news-server.bigpond.net.au> Message-ID: <2da21d6c.0401312120.4e9b7a8e@posting.google.com> "Neil Hodgson" wrote in message news:<%rUSb.37510$Wa.14668 at news-server.bigpond.net.au>... > Mikl?s: > > > Software patents are evil. > > Hell to them. > > Unfortunately, software patents are part of the business landscape now. > They often seem to be comfort blankets for investors ("we have something > unique that absolutely preserves our market position") rather than anything > real. To succeed in an interview, one must avoid laughing at the claims to > uniqueness and refrain from pointing out that the patent actually describes > a sub-optimal solution. > > Neil If you had a friend in the states who could show me that my work was sub-optimal, I would certainly want to hire him or her. Stan From kalab at gmx.net Mon Feb 16 04:06:57 2004 From: kalab at gmx.net (Gerhard Kalab) Date: Mon, 16 Feb 2004 09:06:57 GMT Subject: Easy way to make EXEs... References: <3ce219d4.0402131914.4c0be0b@posting.google.com> Message-ID: <4030857d.328688438@News.CIS.DFN.DE> I also find it convenient to add the following lines to setup.py (found in a sample somewhere): if len(sys.argv) == 1: sys.argv.append("py2exe") That way you can simply double-click on setup.py to create an executable. Gerhard On 13 Feb 2004 19:14:24 -0800, billludden at msn.com (Bill Ludden) wrote: >Voila! Yeah! >Thank You, Lucas! > >Newbs appreciate people like you. >We have to search Google for hours to find a post that will put it on our level. >I can't tell you how much I appreciate the step-by-step. >Now I understand the process and the syntax. > > >Gracias!!!! >Grazie !!! >Thx.!!! > > > > > > > > > > > >"Lucas Raab" wrote in message news:... >> "Xero Limit 126" wrote in message >> news:NMDRb.28013$i4.26542 at newsread1.news.atl.earthlink.net... >> > Okay, I am completely new to Python, and I really dont understand much, >> but >> > I was wondering how to make a python script/program into a standalone >> .EXE? >> > I dont understand py2exe at all, so if someone could tell me or find me an >> > easy (For a newbie) to convert Python scripts to EXEs, please let me know! >> > >> > Thanks for any help! >> > >> > >> You should have no trouble with py2exe at all. A simple setup script would >> be: >> >> #setup.py >> from distutils.core import setup >> import py2exe >> >> setup(name="myfile.py", >> scripts=["myfile.py"], >> ) >> >> Then to compile that file, go to the command prompt and switch to the >> directory that the file is in. For example on my machine I would do the >> following: >> >> Microsoft Windows XP [Version 5.1.2600] >> (C) Copyright 1985-2001 Microsoft Corp. >> >> C:\Documents and Settings\Lucas Raab>cd C:\Python23 >> >> C:\Python23>python setup.py py2exe >> >> Wait a few moments for py2exe to compile your script and Voilla!! you have >> an executable. From jcarlson at nospam.uci.edu Tue Feb 3 22:36:13 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Tue, 03 Feb 2004 19:36:13 -0800 Subject: wxPython issues In-Reply-To: <5onv10pd080l2jkufaigdtcn21p2735jpf@4ax.com> References: <5onv10pd080l2jkufaigdtcn21p2735jpf@4ax.com> Message-ID: >>>No, the thing is: >>> >>>It is a (still primitive) filemanager, where copy should be run in a >>>worker thread >>>in background (you can copy 1 GB file), and you should be able to work >>>with the >>>program without waiting >> > [snip] > > thank you again for your valuable Information! No problem. I've spent more time that I'd like to admit playing with threads. I do enjoy playing with wxPython though...it is fun. - Josiah P.S. If you are looking for a good editor for Python, I wrote one: http://pype.sourceforge.net From steve at ninereeds.fsnet.co.uk Sun Feb 22 03:26:48 2004 From: steve at ninereeds.fsnet.co.uk (Stephen Horne) Date: Sun, 22 Feb 2004 08:26:48 +0000 Subject: class vs function ??? References: <1c764367.0402210857.579f59ab@posting.google.com> <1c764367.0402212226.7002821f@posting.google.com> Message-ID: On 21 Feb 2004 22:26:14 -0800, gveda at iitk.ac.in (Gaurav Veda) wrote: >My basic doubts were : >1) I am allowed to write things in the class body without the need for >encapsulating them in functions. Moreover, they are executed as soon >as I define the class. Infact, I can also call functions in the class >body (the way I called fun2). All this, while I am just defining the >class ! -- I still don't understand why are classes implemented in >this way in pyhton. Well, I think of it this way. Some time back in ancient prehistory, Python didn't have classes - but it did have simple imperitive code. At some point, someone needed to add classes in. The options were... 1. Make a minimal change, exploiting the existing functionality to allow quite sophisticated classes to be defined relatively easily using normal code and concepts that were already familiar to Python users and which could potentially benefit from updates to the core language. 2. Treat class bodies as a completely new thing, and define a new 'sublanguage' for them from the ground up which, once developed, Python users would have to learn as an extra thing in addition to the existing non-class aspects of Python, and which could not benefit from future useful additions to the core language unless their implementation was explicitly duplicated in the class definition sublanguage. The first choice might seem odd if your experience up to now is mostly of statically typed languages (where it isn't really an option) but for a scripting language like Python, IMHO it is the most rational choice. >PS : No Steve, I am not trying out any tricks here. Believe me, I know >too little to do any of that :) OK, I guess I'll accept that - but I'm still keeping my eye on you BTW Python itself is already a compiler - a bytecode compiler - so if you really need to write your own compiler I'd suggest taking a look at how the PYC files are generated, and seeing if you can just wrap them (or something similar) in an exe that embeds the Python interpreter (or a subset of it, including at least the bytecode interpreter and its dependencies). Keep in mind that converting a sequence of text statements into a sequence of function calls (doing little more than parsing and linearising expressions) may be a bit simplistic, but it works - and doing anything noticably more sophisticated would probably be pretty hard work. I assume that's the approach taken by the existing Py2exe (http://starship.python.net/crew/theller/py2exe/index.html). If you need to write something more advanced, using static analysis to do special case optimisations when possible, there was a project doing something similar a little while back but I forget the name. I've done some googling and keep finding references to Viperc, but I don't think that's the one I'm thinking of. If you can find it (whatever it's called) I imagine you'll find it pretty clueful too. If your aiming for more of a Python-like but not entirely compatible language, Pyrex (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/) may also provide some useful hints. It supports some static typing syntax, which allows it to safely use more efficient compiled code in many special cases (without requiring it to use psychic powers in its static analysis). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From et472 at FreeNet.Carleton.CA Sat Feb 21 12:50:40 2004 From: et472 at FreeNet.Carleton.CA (Michael Black) Date: 21 Feb 2004 17:50:40 GMT Subject: Python Productivity Gain? References: <403687e1$1@nntp0.pdx.net> <40368BF3.2FE82B1A@engcorp.com> <103etl21cvjaq2a@corp.supernews.com> Message-ID: Cameron Laird (claird at lairds.com) writes: > In article , > Thomas Heller wrote: > . > . > . >>Hm, no, not hex. This was an IM6100 microprocessor from intersil, a >>clone of the DEC PDP-8 on one chip. The 8080 was too expensive for me. >>Around 1976..., built on a kind of wire wrap board - there were no >>prefabricated kits at that time. > . > . > . > IMSAI actually announced its first product at the end of > '75 > but I think they were hard to come by. This has suddenly been crossposted, so I didn't see the earlier messages. But what's the connection between the IM6100 and the IMSAI? Intersil made the IM6100, and there were never any major "home computers" that used the CPU. There were either very small hobby outfits, and their names will not come to mind at this point, or in engineering circles where there was good reason to be able to put together small controllers that were very much like the PDP-8. And if IMSAI is brought in for some claim to an early computer, it came late. The ALtair 8800 came out in late 1974. Michael From miki.tebeka at zoran.com Thu Feb 26 11:58:54 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: 26 Feb 2004 08:58:54 -0800 Subject: Signal question References: <30875970.0402251600.c5020bf@posting.google.com> Message-ID: <4f0a9fdb.0402260858.3e2e6bd7@posting.google.com> Hello Ian, > I am on WinXPPro and want to catch the keyboard interrupt signal. > Will Python 2.3.3 signal handler catch it? from signal import SIGINT, signal from time import sleep def sigint_handler(signum, frame): print "OUCH" signal(SIGINT, sigint_handler) while 1: sleep(1) print "BEEP" > Cannot find this in the Pyt docs,http://www.python.org/doc/current/lib/module-signal.html > Mind nor can I find `inc += 1` statement that I find a poor substitute for `i++`!! Python tries to keep the language as compact as possible. There is no intension to make it look like C/C++. I don't find these 2 extra chars annoying. HTH. Miki From fortepianissimo at yahoo.com.tw Sun Feb 8 10:29:10 2004 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 8 Feb 2004 07:29:10 -0800 Subject: regex searching hangs Message-ID: Could someone explains why the following code hangs (Python 2.3.3)? --- CODE STARTS --- import re p=re.compile(r'\S+(?:\.\S+)+\.com') t='......................................' p.search(t) --- CODE ENDS --- >From the syntax and semantics of regex, the entire t should be consumed by the pattern '\S+(?:\.\S+)+' and the search() call should return None. Is search() doing a depth-first search and can't pulling itself out? It doesn't seem right to me, or I'm missing something? BTW, I don't think any regex matching should ever hang in any circumstances - correct me if I'm wrong: is halting problem a problem here? Thanks! From sandip at linux-delhi.org Sat Feb 28 19:19:36 2004 From: sandip at linux-delhi.org (Sandip Bhattacharya) Date: Sun, 29 Feb 2004 05:49:36 +0530 Subject: Reading text lines from a socket In-Reply-To: <40412589.40704@venix.com> References: <40412589.40704@venix.com> Message-ID: [Reposting to the general list too] Lloyd Kvam wrote: > Sockets deal with packetized data. The network protocols do not guarantee > keeping the data in line oriented chunks - even if the data starts out > that way. > > You need to deal with extracting lines from chunks. So long as the > connection is > working properly, this is easy. The challenge occurs when the remainder > of a line > never gets delivered. The best strategy depends upon the details of > what you are > doing. I understand that. In Python using sockets is like using sockets in C. However, I was looking for a python equivalent of the perl idiom of opening a socket and getting a file handle ... and then reading this file handle as any other line oriented file using $socket->readline I am trying to write a simple Netcraft style script which tries the HEAD method on a webserver and reads the Server: header from the response. I would not like to use urllib, because even a call to something like urllib.info() reads in the complete webpage on an open(). Even if this particular problem could be done elegantly, I would be interested to know the answer to my original question because the feature of reading a line at a time from a socket will help me in a lot of other places in the future. - Sandip -- Sandip Bhattacharya sandip (at) puroga.com Puroga Technologies Pvt. Ltd. Work: http://www.puroga.com Home: http://www.sandipb.net GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From feb04.20.netman at spamgourmet.com Fri Feb 20 09:28:37 2004 From: feb04.20.netman at spamgourmet.com (Chris) Date: Fri, 20 Feb 2004 14:28:37 GMT Subject: eval ? References: Message-ID: One way to do this is: for index in range(1,4): list=[] for index in range(1,7): if : list.append(1) locals()['list_'+str(index)] = list Of course this isn't going to work the way you expect, because you're assigning a pointer to "list" to "list_n" with each iteration, and at the end, all of your "list_n" variables are going to reference the same object, the one orginally referenced by "list" Perhaps you are looking for something like: >>> dict([('list_'+str(n), [1,]*n) for n in xrange(1,7) if ]) so if condition is "n in (2,4,6)", you'd get output like: >>> foo = dict([('list_'+str(n), [1]*n) for n in xrange(1,7) if n in (2,4,6)]) >>> foo {'list_2': [1, 1], 'list_6': [1, 1, 1, 1, 1, 1], 'list_4': [1, 1, 1, 1]} >>> foo['list_4'] [1, 1, 1, 1] Note that I'm createing a brand new list (via "[1]*n") with each iteration of the list comprehension, rather than using a reference to a previously created list. HTH Chris "Angelo Secchi" wrote in message news:mailman.104.1077277571.27104.python-list at python.org... > > I'm trying to use eval (is the right function? ) to generate empty lists > with different names(es. list_1, list_2, list_3, ...) in a loop similar > to: > > for index in range(1,4): > list=[] > for index in range(1,7): > if : > list.append(1) > foo='list_'+str(index)+'=list' > eval(foo) > > I am not a programmer as you probably see from the code and I do not > even know if this is the right approach to do that in Python (I used > this structure with Matlab that I want now to dismiss ...) > > Any help? > Thanks > angelo > From jcarlson at nospam.uci.edu Wed Feb 18 14:11:11 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Wed, 18 Feb 2004 11:11:11 -0800 Subject: PEP-315 ("do" loop) In-Reply-To: References: Message-ID: > 1. It's clever, addresses a definite "wart", and is syntactically > similar to try/except. But it's syntax seems like an acquired taste to me. Clever, perhaps. Ugly and confusing, yes. Solves a 'problem' that isn't a problem, most definitely. > while 1: > line = sys.stdin.readline() > if line == "\n": > break I use these all the time, and find them conceptually convenient. Most Junior/Senior undergraduate computer science majors have no problems understanding this concept, so I don't think it is necessary to change the while syntax. > until line == "\n": > line = sys.stdin.readline() > > Would be defined to work exactly like a while loop except the test is > not evaluated the first time through the loop. Wouldn't this be akin to > checking at the end of the loop, while maintaining a more while-ish syntax? As others have said, it is not obvious that until implies "don't test the condition the first time through". > Is this at all useful or is something of the order of PEP-315 the way to > go? Personally, I find altering the syntax of while, or adding the 'do' to be a wart. I've never had problems understanding or writing code like the following; while 1: #setup if : break #body If I had a vote, I'd be -1 on PEP 315. - Josiah From jdhunter at ace.bsd.uchicago.edu Fri Feb 27 12:15:01 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 27 Feb 2004 11:15:01 -0600 Subject: Plotting modules In-Reply-To: (DG's message of "Thu, 26 Feb 2004 20:36:45 -0500") References: Message-ID: You may want to look at matplotlib - http://matplotlib.sourceforge.net. You can embed it in a number of GUIs (Wx, GTK and Tk) or use it simply for image generation. Tk is in CVS and will be released next week. DG> Cross platform (linux and windows) and can build into binary DG> form, or easy to install form on linux and windows. All releases have windows installers. Easy build on linux (python setup.py install) DG> Hopefully still maintained (unlike biggles) Very actively, by yours truly :-) DG> Easy to use (like scipy.gplt) You may want to check out the tutorial, to see if it looks easy for you - http://matplotlib.sourceforge.net/tutorial.html I use matplotlib in applications that run on windows and linux. I haven't tried to package it up into a single all inclusive installer, eg, py2exe or McMillan, however, so I can't give you any information there. John Hunter From Moosebumps at Moosebumps.Moosebumps Sat Feb 21 17:37:44 2004 From: Moosebumps at Moosebumps.Moosebumps (Moosebumps) Date: Sat, 21 Feb 2004 22:37:44 GMT Subject: list partition Message-ID: Is there a function that takes a list and predicate, and returns two lists -- one for which the predicate is true and one for which it is false? I know I can call filter(p, list) and filter( not p, list) or something like that, but I assume it would be more efficient to do it in one pass. Actually I probably can't call "not p", I would have to wrap p in a function notP or something. Or is there a shortcut for lambda(x) : not p(x)? I guess it isn't that long : ) MB From wfolta at netmail.to Fri Feb 6 13:06:00 2004 From: wfolta at netmail.to (Wayne Folta) Date: Fri, 6 Feb 2004 13:06:00 -0500 Subject: Best Beginner's Guide To Python? In-Reply-To: References: <3b48d777.0402052148.3cd8e16c@posting.google.com> Message-ID: <1EB8E5AE-58CF-11D8-A168-000A959CB2EC@netmail.to> > When you say you must indent every line and then undent every > line....are you using an editor that knows how to do a block > shift-right and shift-left? In emacs, you just grab the code with a Agreed. Python is more dependent on a reasonable editor than other languages, if only for this feature. Depending on the OS you're using, you may already have such editors. For example, vi (or better vim) is available on all UNIX-based systems. Most IDEs should support block indent/undent as well. Another widely-used editor in MacOS X (if that's what you're using) is BBEdit which also supports this. If nothing else, a reasonable editor also supports syntax coloring which I used to scoff at but now find quite useful. With something like BBEdit, you simply select the lines in question and press CMD-] to indent and CMD-[ to undent. It's faster and more reliable than killing/adding braces at both ends. I also agree with the 2nd ed Learning Python recommendations. I've programmed for over 20 years, so it might be a little hard to tell what a total novice needs, but it is well-written and looks useful for all levels. From bdesth.quelquechose at free.quelquepart.fr Thu Feb 5 14:42:52 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Feb 2004 20:42:52 +0100 Subject: where does Python stand? In-Reply-To: References: Message-ID: <402297a3$0$11234$626a54ce@news.free.fr> Ben wrote: > Hi all! > > I learned Python as part of my university coursework... I enjoyed it. > Now I'm just wondering how Python compares with asp, jsp, php and what > not?? I don't have slightest knowledge about these languages... ASP (Active Server Page) is a technology, not a language - you can code ASP with at least VB, Jscript and C#. JSP (Java Server Page) is mostly a way of embedding Java code in a web page. Here again, more a techno than a language by itself. VB, C# and Java *are* general purpose programming languages. PHP, even if it's true that it began as a web scripting language, is now usable as a stand-alone, 'general purpose' programming language (there's even a Gtk+ binding...). > Are > they more advanced than Python? Depends... What does 'more advanced' mean ? > Can Python be integrated with > Dreamweaver? I don't think so, at least not like PHP or ASP ir like. If you plan to use Python for web development, there are many other solutions - Zope, Spyce, etc, Google is your friend !-) > Hope some of you can get me out of confusion... Hope we did !-) Bruno From roy at panix.com Sun Feb 1 19:44:03 2004 From: roy at panix.com (Roy Smith) Date: Sun, 01 Feb 2004 19:44:03 -0500 Subject: advice on programming style: is multiple inheritance bad? References: <401d5562$0$318$e4fe514c@news.xs4all.nl> Message-ID: Joe Mason wrote: > When profiling a large app at work, we discovered that in C++ accessing > every parent class after the first is quite slow. We were able to just > flip the order of inheritance for some classes, but if you're planning a > complex use of multiple inheritance you should keep that in mind. (I'm > just assuming it has the same effect in Python.) The execution environments of C++ and Python are completely different. Compiled vs. interpreted. Dynamic vs. static binding. There's no reason to believe that what's fast or slow in one language should be fast or slow in the other, especially with such low-level details of how inheritance works. Your comment about profiling is a good one, though. If you want to see what makes an application slow, profile it. Measuring always works better than guessing. And that's true in any language. From mwh at python.net Thu Feb 26 11:39:27 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 26 Feb 2004 16:39:27 GMT Subject: python-dev Summary for 2004-01-01 through 2004-01-31 References: <8ab0589d.0402251718.5b728a3@posting.google.com> Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article , > Michael Hudson wrote: > >aahz at pythoncraft.com (Aahz) writes: > >> How's it a pain? Just write a Python script that does > >> an scp of the file to creosote, then rsh/ssh to run another Python script > >> on creosote that does the mailing. > > > >Via which SMTP server, exactly? > > creosote's, of course I think I just learnt something about the way email works... Cheers, mwh -- Java sucks. [...] Java on TV set top boxes will suck so hard it might well inhale people from off their sofa until their heads get wedged in the card slots. --- Jon Rabone, ucam.chat From JoeSmith at IDontWantSpam.bogus.bogusaddress.com Sun Feb 15 15:53:39 2004 From: JoeSmith at IDontWantSpam.bogus.bogusaddress.com (JoeSmith) Date: Sun, 15 Feb 2004 20:53:39 GMT Subject: Win32: Running python programs from a Cygwin shell In-Reply-To: References: Message-ID: You could probably write a replacement for env that uses cygpath -m on the script file. So, your env could call original env then do cygpath -m on the second paramter. The one thing to think about is what the shell might do to other file/directory paramters passed to your script. So, does it convert foo.py . into: python /cygdrive/h/bin/foo.py python /cygdrive/h/bin/ Then your python script might not work. So, do you run cygpath on all paramters? The other option would be to write a special alias/script just for foo.py to handle on the oddities. This is what I did to get it to execute gvim for win32. I wrote a shell function to go through all paramters and run cygpath -m on everything that does not begin with a '-'. If cygwin normalized everything to the cygpath -m, then I think that the integration with win32 would be substantially better. So, in the above scenario, you would have gotten: python h:/bin/foo.py python h:/bin/ Both cygwin and win32 can handle this. There would be problems when passing to CMD.exe because it would see the "/"'s and barf. I seem to remember that therewas some setting to get command.com or cmd.exe to change the switch char. Jorgen Grahn wrote: > I couldn't think of a good solution, and it's hard to Google for... > > I write python command-line programs under Win2k, and I use the bash shell > from Cygwin. I cannot use Cygwin's python package because of a binary > module which has to be compiled with Visual C 6. > > My scripts start with a '#!/usr/bin/env python' shebang, as God intended. > > Now, I assume I can make cmd.exe run foo.py by asociating *.py with the > python interpreter. > > However, if foo.py is in my path and I try to run it from bash, what happens > is: > > - bash runs env /cygdrive/h/bin/foo.py > - env runs something like 'python /cygdrive/h/bin/foo.py' > - ... and python (which doesn't know about Cygwin-style paths) > croaks on this, of course > > Is there a way around this, which doesn't make my script unusable if I moved > it to a Unix box, or ran it from cmd.exe? > > I'd prefer not to write wrapper scripts in perl/bash/BAT... > > /Jorgen > From chouyiyu at hotmail.com Tue Feb 10 15:55:32 2004 From: chouyiyu at hotmail.com (Yi-Yu Chou) Date: Tue, 10 Feb 2004 20:55:32 +0000 Subject: Lots of Actors Message-ID: Dear all, I want to use line segments to display a 3D vector field. However, my progrm becomes very slow when displaying this vector field if the number of lin segments is very huge. Is there any better method to do it ? Thanks in advance !!! Below is my code : line = [] line_mapper = [] self.line_actor = [] for i in range(0, vf_points.num): line.append(vtkLineSource()) line[i].SetPoint1(vf_points.x[i],vf_points.y[i],vf_points.z[i]) line[i].SetPoint2(vf_points.x[i] + vf.vx[i],vf_points.y[i] + vf.vy[i],vf_points.z[i] + vf.vz[i]) line_mapper.append(vtkPolyDataMapper()) line_mapper[i].SetInput(line[i].GetOutput()) self.line_actor.append(vtkActor()) self.line_actor[i].SetMapper(line_mapper[i]) self.line_actor[i].GetProperty().SetLineWidth(1) self.line_actor[i].GetProperty().SetColor(0,1,1) self.line_actor[i].PickableOff() self.tar_renderer.AddActor(self.line_actor[i]) _________________________________________________________________ ?? MSN ???????????????????? http://groups.msn.com?pgmarket=zh-tw From ketulp_baroda at yahoo.com Thu Feb 26 05:05:00 2004 From: ketulp_baroda at yahoo.com (ketulp_baroda at yahoo.com) Date: 26 Feb 2004 02:05:00 -0800 Subject: Is MVC architecture applicable for web environment?? Message-ID: Hi Is the true mvc architecture ( with observer-observable pattern as implemented in JAVA) not applicable for web environment?? I mean to say that the HTTP protocol is request/response based so there is no notion of an "event" being notified ... whereas the observer-observable pattern is based on event. From and-google at doxdesk.com Thu Feb 26 04:47:14 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 26 Feb 2004 01:47:14 -0800 Subject: Python scripts in IIS References: Message-ID: <2c60a528.0402260147.42b9e635@posting.google.com> Robert Brewer wrote: >> Note: you really want - >> ...python.exe -u %s %s (Note to self and Google: you *really* want: ...python.exe -u "%s" %s just in case the filename has space characters in.) > What you *really* want ;) is to avoid allowing users to pass arbitrary > strings on the command line, which is what happens with this technique. ? IIS passes arbitrary strings, not the user. Of course the 'check file exists' option should be set to avoid parameter injection, but that's common sense, and the IIS5 default. > You should seriously look into ASP, mod python, or some other means of > more safely connecting python to a web server. I can't agree with this at all. CGI is the only standard we can currently use to write cross-platform scripts. ASP is fine if you want to be locked to IIS; coding to mod_python limits you to Apache. CGI is also a well-understood protocol with widely-used implementations. mod_python, judging by the recent repeated appearance of security problems, is not yet at quite this level of maturity. Writing secure web applications is an issue in itself, without having to worry about whether your application server/interfacing layer is going to let you down. Yes, CGI is slow, and it does have a few practical problems in the area of HTTP Authentication. But until WEB-SIG comes up with a standard webapp encapsulation interface it's the only write-once-run-anywhere standard we've got. I'm not saying that ASP or mod_python are unworthy technologies, but choosing one of them will tie your subsequent choices a tad. Convenience is a good reason for choosing either of them over CGI; security is not. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From jacek.generowicz at cern.ch Thu Feb 26 06:39:22 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 26 Feb 2004 12:39:22 +0100 Subject: Some language proposals. References: Message-ID: "Jimmy Retzlaff" writes: > The function new.instancemethod will build an instance method for > you Ah yes, I remember putting instancemethod through its paces, and even discovering the undocumented feature of it accepting None as an instance ... my recollection is that it did not work with callable instances as the callable, but clearly I'm misremembering. I can't find a problem with builtins either ... but a little voice is telling me that I came across some problem with this approach, somewhere along the line. Oh well, thanks for showing me that this approach works better that my recollection of it. From bnet at ifrance.com Mon Feb 9 11:34:14 2004 From: bnet at ifrance.com (Benoit Dejean) Date: Mon, 09 Feb 2004 17:34:14 +0100 Subject: fork, exec, and disown References: <7iy8rdd51u.fsf@enark.csis.hku.hk> <7in07tj59r.fsf@enark.csis.hku.hk> Message-ID: > So double forking has its merits, since it is per-child rather than > per-parent. And modern OS actually do fork() rather efficiently anyway. thank you, i'll keep the double fork. From http Sun Feb 1 18:34:32 2004 From: http (Paul Rubin) Date: 01 Feb 2004 15:34:32 -0800 Subject: OT: why do web BBS's and blogs get so slow? References: <7xbrojk9rk.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xk736s7av.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Much as I'm loathe to mention it, you might might also want to take a > look at LiveJournal to see how they do it. But LiveJournal is another one of those sites that slows to a crawl when loaded. I want to know how the FAST sites do it. From ken at perfect-image.com Fri Feb 6 10:06:10 2004 From: ken at perfect-image.com (Ken Godee) Date: Fri, 06 Feb 2004 08:06:10 -0700 Subject: Qt/PyQt license confusion In-Reply-To: <30260531.0402051512.4924a4a9@posting.google.com> References: <30260531.0402040954.68209983@posting.google.com> <30260531.0402051512.4924a4a9@posting.google.com> Message-ID: <4023AD62.5030609@perfect-image.com> >>Under windows commercial, you could distribute, but... >>it has to been done in a way that does not allow >>user direct access to the underlying Qt/Pyqt base >>code. So they could not use to create there own programs. > > Does this mean I couldn't distribute the Qt/PyQT DLL's still as they > could be used to run other Py[Qt] apps, I guess static (McMillan > Installer) binaries would be OK.... > The PyQt site has some Howto's on how to package up your apps under win/linux. > I wonder if it might be worth getting BA for the PyQt license and the > book for the full Qt license (i.e. it works with C++ too) although > that's $110+ now.... If you buy the BA lic. you get current version of Qt/PyQt combo for win/linux. $80.00 If you buy the book, you get NON-COMMERCIAL Qt only, which you already got with BA. I've got a copy of the book coming as we speak, $31 @ amazon I think $31 just to have the book as a reference by itself is worth the money and as far as these types of books go, that's a very resonable price. Wanna buy a shelf full of Perl books? >>I went through the same thing, going back >>and forth with wxpy/pyqt, installed and have >>used both. I'm staying in the PyQt camp and >>have found very little use (none yet) for win >>or commercial use. The little tool kit one >>can put together is outstanding..... >>Qt, Qt Assistant, Qt Designer, >>PyQt, pyuic, eric3, etc...... > > > Well I'm not a very "visual" style programmer so Designer/pyuic are > not really for me, but the Python version of Assistant looks very > promising (as I hate the C++ docs, when you're coding Python!) I tell ya, using Designer/pyuic one can belt out a pretty complex form in a fraction of the time. If you haven't atleast gave it a good go, you should. I'm sure you know already, but you can buy just the Qt c++ docs converted to PyQt for $20 as a stand alone. From aahz at pythoncraft.com Wed Feb 25 14:55:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 25 Feb 2004 14:55:17 -0500 Subject: Some language proposals. References: Message-ID: In article , Jacek Generowicz wrote: > >Sure. I have some stateful methods of classes (which I create >dynamically and stick onto the class as the information about the >existence of the method becomes available). By implementing them as >closures I can just stick them on to the class. If I were to implement >them as instances then I'd have to reimplement all the descriptors >that take care of turning functions into bound or unbound methods. Why not use callable instances? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Do not taunt happy fun for loops. Do not change lists you are looping over." --Remco Gerlich, comp.lang.python From florianlink at gmx.de Sat Feb 28 06:45:51 2004 From: florianlink at gmx.de (Florian Link) Date: Sat, 28 Feb 2004 12:45:51 +0100 Subject: Python C Interface: finding out the called method's name in C PyMethod? Message-ID: <5.2.0.9.0.20040228124547.00bb0c68@pop.gmx.net> Purpose: Dynamically multiplex PyMethodDefs to QT Slots Hi, I would like to create a PyObject using the C API which can dispatch calls to it's methods to just ONE C function, which then forwards the call depending on the method name and argument types/number to other classes. E.g. I would dynamically create: PyMethodDef methods_QObject[] = { {"method1", methodHandler, METH_VARARGS, NULL}, {"method2", methodHandler, METH_VARARGS, NULL}, {"method3", methodHandler, METH_VARARGS, NULL}, ... more methods, read dynamically from a C++ Runtime system... } static PyObject *methodHandler(PyObject *sipSelf,PyObject *sipArgs) { // Now my problem arises, all methods point to this dispatcher // and I would like to know the called method name something like: const char* method = Py_..._getCurrentInvocationName(sipSelf); // now do something dependend on method and sipArgs... qobject->qt_invoke(method,args) } Your will say, hey, why does he want to do that, since I could just implement "method1Handler", "method2Handler", ... BUT, this would mean creating wrapper code like in the SIP library or SWIG etc. which needs to be compiled on each change. I want to do it dynamically, since I have a generic way to forward the calls and I don't want to recreate the wrappers just to create some dummy forwarders. I can create PyMethodDef dynamically, but I cannot create C forwarder functions dynamically. So, it there a way to find out the called method name from a PyMethod C function? Or maybe there is a way deeper in Python, can I extend the method dispatcher of a PyObject, so get all call before the lookup to tp_dict is done? best regards, Florian From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Feb 19 13:33:26 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 19 Feb 2004 19:33:26 +0100 Subject: Socket Programming in Python In-Reply-To: References: Message-ID: <40350176$0$573$e4fe514c@news.xs4all.nl> Premshree Pillai wrote: > For the uninitiated: "Socket Programming in Python" at > evolt.org: http://evolt.org/article/Socket_Programming_in_Python/17/60276/index.html Hmm. I'd stick to http://www.amk.ca/python/howto/sockets/ But, ofcourse, only if you really need to use raw socket communication ;-) --Irmen From j-y.nief at wanadoo.fr Sun Feb 8 10:12:36 2004 From: j-y.nief at wanadoo.fr (Jean-Yves Nief) Date: Sun, 08 Feb 2004 16:12:36 +0100 Subject: retrieving a return code from a thread Message-ID: <402651E4.1050509@wanadoo.fr> hi all, I would like to know how I can retrieve in my main program the return code from a thread that I launched: class example(threading.Thread): def __init__(self, filename): self.filename = filename threading.Thread.__init__(self) self.start() def run(self): ........ rc = os.system("command example") in the main thread: ..... thrdExample = [] thrdExample.append(example(file)) ..... # once it's not active anymore, test of the return code for thrdExample[i] ?? thanks in advance, JY From http Fri Feb 13 03:57:38 2004 From: http (Paul Rubin) Date: 13 Feb 2004 00:57:38 -0800 Subject: Understanding CHMOD References: <8089854e.0402130055.35ed927f@posting.google.com> Message-ID: <7xy8r72w71.fsf@ruckus.brouhaha.com> What's your question? I think you need to look at the chmod(1) and chmod(2) Linux man pages, not a Python manual. From fake at fake.net Wed Feb 25 13:29:07 2004 From: fake at fake.net (Andrei) Date: Wed, 25 Feb 2004 19:29:07 +0100 Subject: Fast File Input References: Message-ID: <17hgq7530uwnb.74u1mjdzjbb9$.dlg@40tude.net> Scott Brady Drummonds wrote on Wed, 25 Feb 2004 08:35:43 -0800: > Hi, everyone, > > I'm a relative novice to Python and am trying to reduce the processing time > for a very large text file that I am reading into my Python script. I'm > currently reading each line one at a time (readline()), stripping the > leading and trailing whitespace (strip()) and splitting it's delimited data > (split()). For my large input files, this text processing is taking many > hours. An easy improvement is using "for line in sometextfile:" instead of repetitive readline(). Not sure how much time this will save you (depends on what you're doing after reading), but it can make a difference at virtually no cost. You might also want to try rstrip() instead of strip() (not sure if it's faster, but perhaps it is). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From theller at python.net Mon Feb 16 15:28:44 2004 From: theller at python.net (Thomas Heller) Date: Mon, 16 Feb 2004 21:28:44 +0100 Subject: Is there Multi-media support in Python ? References: Message-ID: "Will" writes: > Is there multi-media support in Python? So I can... > > 1 - play video in all the standard formats... windows & Mac? > 2 - play flash files > 3 - Power Point > 4 - Standard graphic formats > 5 - Sound in all the standard formats > 6 - etc > > Please note requirements: And, on video's, flash files, Power Point, Graphic > files, I need to have those show within my programs "window" along with some > other text... so I need to be able to size the video and locate it in the > window... so if the program simply pop's up the Windows Media Player or > QuickTime or whatever as a separate window... no good... it all needs to be > integrated into a single window along with text and other stuff... > > If so, is it in the standard release or has someone created a module just > for multi-media integration? Well, maybe pygame contains something like this. OTOH, there's Henk Punt's venster library, which is based on the ctypes module. (If you use windows you may want to look into ctypes anyway - it allows to make windows api calls even when they are not wrapped by Mark Hammond's win32all extensions.) venster contains samples which embed the internet explorer webbrowser control in a window, it can has a sample which plays flash files in a window, and it shows how to embed the windows media player. You can probably to something similar using the pythonwin application framework in win32all (oh, wait, the official name is now pywin32) which is based on a python wrapping of the mfc. Thomas From grahamd at dscpl.com.au Sun Feb 29 01:55:38 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: Sun, 29 Feb 2004 17:55:38 +1100 Subject: Licensing of wrappers around C/C++ code under more restrictive licensing. In-Reply-To: <404173FA.3040503@rogers.com> References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> <404173FA.3040503@rogers.com> Message-ID: <48560634-6A84-11D8-B77C-000393DCF16E@dscpl.com.au> On 29/02/2004, at 4:09 PM, Mike C. Fletcher wrote: > Graham Dumpleton wrote: >> So, how can one cast the licensing so as to provide an exception that >> provided the underlying C/C++ library isn't changed, that the Python >> wrappers can be used under a less restrictive license. I have control >> of >> the licensing on both so can stipulate exceptions, but what is the >> best way of doing it? >> > Sounds like what you really want is the LGPL for the C/C++ library? > That would keep the GPL-like restrictions for the C/C++ library, but > allow linking it into proprietary Python software. It would *not* > however restrict based on whether it's a Python or C/C++ application > doing the linking. It would also explicitly *not* prevent changes to > the C/C++ library (the whole point of Open Source licenses, > particularly GPL and LGPL being to allow the user to fix bugs and > change operation of the software). > > You could add a clause to your license doing something silly like > requiring that a Python DLL be linked into the process to enable the > less restrictive license, but doing that means that you've suddenly > got a non-standard license, which requires everyone to hire a lawyer > to explain it to them, check for incompatibilities with other > software, ad nauseam. > > Of course, the point of the GPL license (among other things) is to > strongly encourage others to use the license in order to give to users > access to ever-more GPL'd code. The so-called "viral" effects are > intentional. If I understand correctly, the QPL is basically a dual > license encouraging you to either pay Trolltech or GPL your software. > Finding ways *around* these licenses (I'm assuming that the QPL is > being inherited by including Qt or the like) might be considered rude > at the least if the license involves code which is not your own. > > So, my suggestion would be (assuming this is possible (you own *all* > copyrights involved)): > > * Ditch QPL, license the C/C++ library as LGPL, license the Python > library as BSD/MIT or LGPL. > ... Thanks for the comments. It gives me more things to think about. As far as ditching the QPL for the C/C++ library and using the LGPL, I am not sure that I can. The whole situation is made more complicated for me, because although I wrote all the code, it was originally developed while I worked for a specific company. I did obtain a license from that company to continue to develop the code and to distribute the result, including being able to sub-license others to also distribute the code, but the language of that license may well prevent me from applying a license such as the LGPL. This is because with the LGPL, someone could cherry pick code out of the library and use it in something else to the extent that the LGPL allows. At least I don't believe the LGPL would stop this although the application or library which used the "cherry picked" code would itself have to be LGPL or GPL I would imagine. The reason why the QPL is working for me so far is that the QPL essentially restricts someone to distributing it as is. That is, any changes must be distributed as a separate patch. This in effect means that someone can't just cherry pick code from it and use it separately. To that end I believe I am working within the spirit of my original license obtained from the company who I was originally working for as the manner in which I am licensing it and distributing it preserves the integrity of the package and people in the main have to use it as distributed. They can still make changes if they need to, but if distributing it further, these would have to be as a patch. I'll have to look more at my license for using the original code, but I think I would be pushing it to release my current C++ code, based on the original code, under a license that allows a free for all. My Python wrappers don't have this problem as such because I developed them all on my own time and by itself it doesn't include any of the original code. Now one may say that I should have negotiated a better license on the original code, but this was back in 1993 before Open Source took off to the extent that it has. It wasn't necessarily possible back then to anticipate how things would change Thanks again. From gerrit at nl.linux.org Sat Feb 14 17:18:39 2004 From: gerrit at nl.linux.org (Gerrit) Date: Sat, 14 Feb 2004 23:18:39 +0100 Subject: mailing list problems? Message-ID: <20040214221839.GA22649@nl.linux.org> Hi, I have today seen only 5 mailing list messages to the python-list. I see >30 messages in c.l.py newsgroup. Do other people experience problems as well, or do I have a problem at my end? Gerrit. -- Weather in Twenthe, Netherlands 14/02 21:25 UTC: 7.0??C wind 1.3 m/s W (57 m above NAP) -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From nuffsaid at phreaker.net Fri Feb 6 09:48:17 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Fri, 06 Feb 2004 15:48:17 +0100 Subject: Custom operator References: <2066c50.0402051336.1e8e7ee4@posting.google.com> <20040205220748.GA8055@nl.linux.org> Message-ID: On Fri, 06 Feb 2004 07:56:28 +0100, mathias.foehr wrote: > I want to define new operators because mathematicians use special operators ( > eg circle plus (+), circle times (*), arrows -> > ) since centuries. It increases readability in this area and people have > got used to it. But there are so many of them ... :-) Mathematicians are e.g. also used to LaTeX terminology for writing their papers; so it might be a better approach to define a set of functions, classes, methods etc. using names from LaTeX (instead of trying to add 'real' new operators to Python). Moreover: observe, that e.g. oplus (+) has different meanings (depending on what area of maths you are working in). The same holds for almost all operators. HTH / Nuff From mwh at python.net Thu Feb 5 07:29:20 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 5 Feb 2004 12:29:20 GMT Subject: advice on programming style: is multiple inheritance bad? References: <401d5562$0$318$e4fe514c@news.xs4all.nl> Message-ID: Uwe Mayer writes: > Michael Hudson wrote: > > > Uwe Mayer writes: > > > >> BTW: when doing m.i. you can't mix new-style and old-style objects, or > >> else Python exits with a Segmentation Fault. :) > > > > Uhh, really? Example please. > > Seems only to occur in connection with Qt. :( Ah, good, not a problem I can fix . > Code as the one below, inheriting from some Qt Widget and using > m.i. with new-style classes cause a Segmentation Fault on my > machine: Weird. I take it you've reported this to the PyQT folks? Cheers, mwh -- 7. It is easier to write an incorrect program than understand a correct one. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From mcfletch at rogers.com Tue Feb 24 16:30:50 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 24 Feb 2004 16:30:50 -0500 Subject: Thoughts about Python In-Reply-To: <15c2d03b.0402241237.708cb4e8@posting.google.com> References: <15c2d03b.0402240311.395f5382@posting.google.com> <15c2d03b.0402241237.708cb4e8@posting.google.com> Message-ID: <403BC28A.9020507@rogers.com> Marco Aschwanden wrote: ... >Maybe I don't get the point here: Why do dictionaries need tuples to >work? I know that tuples can be used as keys... but how many times do >you need tuples as dictionary keys (it would be simple to turn a list >into an immutable string if really needed ("::".join(["a","b"]). But >maybe tuples are used within dictionary in a way I don't know. If you >could clarify on this point I will never ever say anything about >"useless" tuples... instead I will start asking for "immutable >dictionaries" 8o) > > x = [1,2] d = { x : 32 } x.append( 3 ) d[ [1,2] ] Does that last line raise a key-error, or return 32? Tuples are useful as keys precisely because they are immutable, and hash based on their contents/value. Mutable keys in dictionaries either need to be "identity" based (which is far less useful that "value" based, (as then you can only test whether a particular list is used as a key, not any list with the same value)), or have some funky book-keeping rules regarding what happens when the key changes (for example, convert the key to a tuple under the covers so that all further changes to the key are ignored in the dictionary). To clarify regarding identity: x = (1,2) d = { x : 32 } d[ x ] d[ (1,2) ] because they hash and compare based on value, tuples here can unambiguously be used as value-based keys. With a list, were we to use identity-based comparisons: x = [1,2] d = { x : 32 } d[ x ] # would return a value d[ [1,2] ] # would raise a key-error, # defeating one of the most common usage patterns for tuples-in-dictionaries while if we were to use value-based comparisons set at key-specification time: x = [1,2] d = { x: 32 } x.append( 3 ) # possibly done in another thread... del d[ x ] # would raise a key-error to do lots of common operations (such as iterating through the keys of a dictionary and deleting those which meet a particular test) in this scenario you'd need to be able to return a static key in order to be sure not to have it mutate while you're working, so you'd need an exposed list-like immutable data-type (sound familiar). Now, as shown above, we could do an explicit cast on setting a dictionary value to make a list a tuple "under the covers" and thus get back... but this is another "explicit is better than implicit" things. The magic would up and bite in debugging weird corner cases more times than it saved you a few seconds of thinking in the design stage. We still have the static type, it would need to be dealt with in code, and it would be surprising to see it show up instead of the lists we originally used as the keys. Using lists forced to strings would be a difficult sell even without the problems described above, particularly as you can quite readily have strings as keys already, so you get difficult-to-debug collisions where a string just happens to equal the string-ified list representation of some other value. The "explicit is better than implicit" axiom of "import this" would then suggest that having an explicitly defined immutable type (tuple) that hashes by value and is used to set keys in a dictionary is a better choice than automagically coercing the lists to a hidden type (or a string). Don't worry about asking questions like this, by the way, it's good for the perceptions of the community to be stirred every once in a while. Enjoy yourself, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From merkosh at hadiko.de Tue Feb 3 09:57:24 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 03 Feb 2004 15:57:24 +0100 Subject: advice on programming style: is multiple inheritance bad? References: <401d5562$0$318$e4fe514c@news.xs4all.nl> Message-ID: Michael Hudson wrote: > Uwe Mayer writes: > >> BTW: when doing m.i. you can't mix new-style and old-style objects, or >> else Python exits with a Segmentation Fault. :) > > Uhh, really? Example please. Seems only to occur in connection with Qt. :( Code as the one below, inheriting from some Qt Widget and using m.i. with new-style classes cause a Segmentation Fault on my machine: -- example -- from qt import QWidget, QApplication import sys class A: def __init__(self): print "in A" class B(object): def __init__(self): print "in B" class C(QWidget,A): def __init__(self): QWidget.__init__(self) A.__init__(self) print "in C" class D(QWidget,B): def __init__(self): QWidget.__init__(self) B.__init__(self) app = QApplication(sys.argv) C() #works D() #fails -- example -- Ciao Uwe From aahz at pythoncraft.com Thu Feb 5 16:10:18 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 Feb 2004 16:10:18 -0500 Subject: Funnying the From (was: OT: Recommended news reader?) References: <4f0a9fdb.0402031309.fde7220@posting.google.com> <10257t58fdgvi67@corp.supernews.com> Message-ID: In article , Bert Hyman wrote: >claird at lairds.com (Cameron Laird) wrote in >news:10257t58fdgvi67 at corp.supernews.com: >> >> I didn't know that "From:" *could* be customized through >> common configurations. Does anyone know how to set it >> with trn(1)? > >Does "trn" still post through the external "Pnews" program? If so, >you can edit your post before sending it to include a "From:" header >of your liking and the server ->should accept it. > >The last time I saw it, Pnews was a Bourne shell program, so you >could find the copy on your system, copy it and change it any way you >like. That's exactly what I do, though it's also simple enough to change the From: line manually. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From david.grant-NOSPAM at telus.net Fri Feb 27 17:34:48 2004 From: david.grant-NOSPAM at telus.net (DG) Date: Fri, 27 Feb 2004 17:34:48 -0500 Subject: Plotting modules In-Reply-To: References: Message-ID: <403FC608.1010008@telus.net> Jeremy Sanders wrote: > On Thu, 26 Feb 2004 20:36:45 -0500, DG wrote: > > >>I need a plotting program this is: >>-Cross platform (linux and windows) and can build into binary form, or >>easy to install form on linux and windows. >>-Hopefully still maintained (unlike biggles) >>-Easy to use (like scipy.gplt) > > > I'm working on a PyQt-based plotting package called Veusz > http://home.gna.org/veusz/ (not really ready for use yet). > > Unfortunately AFAIK, there is no Free Edition of Qt for Windows, so it > wouldn't be cross-platform enough for you. Nice output. Looks almost biggles-ish, maybe better. Dave From tjreedy at udel.edu Thu Feb 12 14:12:42 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Feb 2004 14:12:42 -0500 Subject: How to avoid "f.close" (no parens) bug? References: <96F3EC4BDF504540BB9715CBE9DACB8B081B0DB2@pa-mail1.legato.com> <402BB684.4010807@prescod.net> Message-ID: "Paul Prescod" wrote in message news:402BB684.4010807 at prescod.net... > Michael Pyle wrote: > > try: > > sys.frozen > > except AttributeError: > > options.append( 'debug-on' ) > > A cleaner and probably more efficient way of doing this is: Since I expect, based on old posts but without testing the current interpreter, the fixed cost of hasattr to be between the two costs of successful and exception-generating tries (the latter much higher), I would expect relative efficiency to depend on the relative proportion of try outcomes. But the difference should seldom be enough to be a deal breaker either way. Regardless of speed, I like the below better. The bare attribute access is a bit jarring to me, though I can see how it might become an in-house idiom. > if not hasattr(sys, "frozen"): > options.append("debug-on") But for similar reasons, even if there were no use for bare names, I would be opposed to breaking the currently simplicity of 'name recalls object'. In any case, a Python compiler cannot, in general, know what type of object a name will be bound to at runtime. The parens following a name (or expression) amount to a behavioral-type promise by the programmer that the resulting object will be callable. If not, then a *runtime* exception gets raised. In return, the interpreter promises to make the call if at all possible. Terry J. Reedy From jcarlson at nospam.uci.edu Sat Feb 7 14:36:44 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 07 Feb 2004 11:36:44 -0800 Subject: Print function and spaces In-Reply-To: References: Message-ID: > Josiah> I could have sworn there was a function to disable/enable > Josiah> placing spaces between objects printed using the print > Josiah> statement. I've looked all over, but I couldn't find it, so > Josiah> apparently it doesn't exist. > > I think file().softspace is what you're looking for. That is it. Checking the docs, it doesn't seem to do what I thought it did, nor what the parent author had desired, and testing confirms this. Ah well. - Josiah From fpetermaas at netscape.net Wed Feb 25 09:43:45 2004 From: fpetermaas at netscape.net (Peter Maas) Date: Wed, 25 Feb 2004 15:43:45 +0100 Subject: Locate python home In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > Thomas Aanensen wrote: > Never trust the assumption: > > >>> import os > >>> os.path.isfile( os.path.join(os.path.dirname( sys.executable ), > 'python.exe' )) > False If Thomas wants to find the console version he should start a console script: python checkpath.py (assuming python is in the PATH). sys.executable delivers always the executable that executes the script. If python is not in the PATH there's no safe way to find python.exe as far as I know. 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 jcb at iteris.com Fri Feb 20 01:03:51 2004 From: jcb at iteris.com (MetalOne) Date: 19 Feb 2004 22:03:51 -0800 Subject: PEP-0315--Enhanced While Loop: An idea for an alternative syntax References: Message-ID: <92c59a2c.0402192203.66ee4f16@posting.google.com> I don't like the syntax. I find the indentation counter-intuitive. From bubbarichau at warmmail.com Wed Feb 25 15:09:02 2004 From: bubbarichau at warmmail.com (rich hammett) Date: Wed, 25 Feb 2004 20:09:02 -0000 Subject: Tkinter on RedHat Linux 9.0 References: <103pvjni4vc587e@corp.supernews.com> Message-ID: <103q06u9koeq30e@corp.supernews.com> Sen j?lkeen, kun Perry Mason oli pahoinpidellyt h?nt?, rich hammett yll?tti tuomarin todistamalla: > Sen j?lkeen, kun Perry Mason oli pahoinpidellyt > h?nt?, Thomas Korb yll?tti tuomarin todistamalla: >> On Sat, 10 May 2003 14:34:05 -0600, Don Donigan wrote: >>> >>> Can anyone tell me how to install Tkinter on RedHat Linux 9.0? >>> I have not need successfull as of yet. Thanks in advance. >>> >> You have to install the following 4 RPM packages: >> 1. python 2. tcl 3. tk 4. tkinter > Is there any way to update the python.org webpage for > Tkinter? It currently says you never need to download > tkinter separately, which has had me chasing my tail > here for a few days. In fact, the python rpm from redhat CLAIMS to include Tkinter already. I'm pretty sure it doesn't. rich > rich >> Use 'rpm -qi ' to see, which packages are already >> installed on your system (e.g.: rpm -qi tkinter). >> To install a package, use 'rpm -ihv '. This command >> will i.p. tell you, if other packages must be installed first >> (e.g. 'itcl' or 'tix' might be necessary). >> You will find the RPM 'packagefiles' on your Red Hat 9 CDs, but >> it is often easier (and faster) to download them directly from the >> Red Hat Network (http://rhn.redhat.com) or from any other good RPM >> archive. -- -to reply, it's hot not warm +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ \ Rich Hammett http://home.hiwaay.net/~rhammett / "Better the pride that resides in a citizen of the world; \ than the pride that divides / when a colorful rag is unfurled." From LittleDanEhren at yahoo.com Mon Feb 2 19:48:12 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 2 Feb 2004 16:48:12 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> Message-ID: <711c7390.0402021648.325d7760@posting.google.com> > If you've switch from Python to Io, what will you do with the answers > to these questions? Use them for good or evil? Will you switch back > from Io to Python? > --dang If there are good enough responses, I'll use Python. I just wanted to know a reason why Python is better. Also, these responses might be used to make Io better (since it's a young language). Daniel Ehrenberg From loic at yermat.net1.nerim.net Mon Feb 23 17:24:40 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Mon, 23 Feb 2004 23:24:40 +0100 Subject: Library for handling GNU parameters In-Reply-To: <403A7946.378FE946@engcorp.com> References: <403A7946.378FE946@engcorp.com> Message-ID: Peter Hansen a ?crit : > Florian Lindner wrote: > >>is there a python library available for handling GNU parameters. For >>example: >> >>prog --filename=foo.bar is the same as prog -f foo.bar >> >>or >> >>prog --execute == prog -e >> >>I look for a library for parsing these string and represent the values in a >>list. > > > The standard library module getopt can do that, at least for the sort > of example you show, and I suspect the newer standard library module > optparse could also handle it (but haven't tried myself). > > -Peter Standard Module optparse http://www.python.org/doc/2.3.3/lib/module-optparse.html Note that if you do not have python2.3 you can just put the optparse.py and put it in you python2.2 directory, it will work ! -- Yermat From noemail at noemail4u.com Fri Feb 6 16:34:41 2004 From: noemail at noemail4u.com (Dang Griffith) Date: Fri, 06 Feb 2004 21:34:41 GMT Subject: where does Python stand? References: <6ee58e07.0402051148.25add90e@posting.google.com> Message-ID: On 5 Feb 2004 19:30:42 -0800, crescent_au at yahoo.com (Ben) wrote: >I still need to ask something... Let me be more specific. I wanna >create a web page where I want to put photos taken by me... There are >lots of them. I also want to include a search capability in my web >page for users to search my photos by name (topic)... For this, I >would like to use a database which includes the location of my photos >on the server along with names and sizes... I would also like to make >it easier for me to add more photos in the future with ease. Also if >possible, try to generate html pages on the fly as I upload photos on >the server. In other words, I wanna make my web design efficient with >least amount of manual work. Well, this is pretty much the scenario. > >What do you think would be a best design technique that I should >follow? I know Dreamweaver, Python, Java, JavaScript, CGI using >python, C, C++... What programming languages do I need to learn in >order to accomplish my task? If I need to choose between ASP and JSP, >I'd rather go for JSP cause it'll be easier for me to migrate as I >don't know much about VB, Jscript and C#. What are some of your >recommendations? I don't want to sound like a heretic (cuz I'm not religious about languages), but from the sounds of your requirements and current knowledge base, PHP will satisfy your needs in the most direct fashion. It's easy to learn and can be worked in with DreamWeaver. You can use mySql (sp?) with PHP to map keywords/search criteria to the filenames of your photos. Your PHP code will take the user's input, form an SQL statement to determine which photos to display, and then put them into a web page. Poof! --dang p.s. I only spearminted with PHP for a little while, and am no expert. But as I said, based on your requirements, I think it fits the bill. From LittleDanEhren at yahoo.com Sun Feb 1 14:26:44 2004 From: LittleDanEhren at yahoo.com (Daniel Ehrenberg) Date: 1 Feb 2004 11:26:44 -0800 Subject: Python vs. Io References: <711c7390.0401291301.3f95794@posting.google.com> <711c7390.0401301710.4353274@posting.google.com> <711c7390.0401311220.763be80a@posting.google.com> Message-ID: <711c7390.0402011126.23590f05@posting.google.com> > I've always presumed that if I wanted an ultra-pure OO language I would > use Smalltalk. Obviously IO's big difference is prototype rather than > class-based inheritance. But that's a difference, not (necessarily) a > benefit. Could you please describe what would attract one to IO over > Smalltalk? > > Paul Prescod In short, Io isn't as "ultra-pure" as Smalltalk. Here are some things that Io supports and Smalltalk doesn't: *Standard operator precedence *Normal function syntax *Standalone functions *Everything is public (like Python) *Interpreted and no monolithic system image like Smalltalk *Better block syntax (no cryptic square brackets or variable symbols) *Prototypes (which *is* a benefit, not just a difference) *Not obsessively object oriented (for stuff like flow control) *Growing, not shrinking community *Inplace mathematical operations *Much smaller implimentation and good for embedding *More flexible for syntax extension *Everything is anonymous (yet there is still some introspection for names) *Functions are first class objects, not merely messages *The ability to change what it inherets from *More flexible scoping *Writing self can be left out when sending messages to the current object *Speed on par with Python *Optionally non-strict functions (but usually strict anyway) Note that Python lacks some of these things too. Daniel Ehrenberg From frank at chagford.com Fri Feb 6 00:09:01 2004 From: frank at chagford.com (Frank Millman) Date: 5 Feb 2004 21:09:01 -0800 Subject: Any problems with *lots* of attributes? References: <246a4e07.0402040703.2be902a9@posting.google.com> <246a4e07.0402042327.5192034a@posting.google.com> Message-ID: <246a4e07.0402052109.3992aeba@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message: > > You're mostly worrying about nothing; your analysis is essentially > correct. > Thanks a lot, everybody, for the replies. I will proceed on the assumption that I do not need to worry about this. I have to change a lot of things in my app if I switch from lists to attributes, and I was nervous of doing all the changes and then finding that I had a problem. I am now reasonably confident that I will not have a problem, and the code should be cleaner and faster when I have finished, so I will get stuck in. Thanks again Frank From mauricio.inforcati at cenpra.gov.br Wed Feb 11 13:26:08 2004 From: mauricio.inforcati at cenpra.gov.br (=?iso-8859-1?Q?Mauricio_Infor=E7ati?=) Date: Wed, 11 Feb 2004 15:26:08 -0300 Subject: Mouse Cursors on Tkinter Message-ID: <002b01c3f0cc$86954530$447290c8@luz> Hi, How can I change my mouse cursor to an own file.cur cursor? I tried setting "cursor" option to the file(widget['cursor']='file.cur'), to a pointer of this file (@widget['cursor']='file.cur'), to a Image instance of this cursor and none of this options worked. What can I do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Fri Feb 13 19:21:29 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 Feb 2004 19:21:29 -0500 Subject: help! multi-threading problem on hyperthreading smp linux server References: <2004021110421076514154@k2.sage.att.com> Message-ID: In article <2004021110421076514154 at k2.sage.att.com>, Garry Hodgson wrote: >aahz at pythoncraft.com (Aahz) wrote: >> >> What happens if you only start ten threads (fifty >> threads isn't huge, but it's definitely large)? > >same thing. works fine for 1 thread :-). > >> Have you applied all relevant OS patches and/or tried upgrading to a >> newer kernel? > >it's looking like this may be the problem, since the machine it fails on >is running the oldest linux kernel of all of them. all are 2.4.20's, but >with different minor release numbers. Those two combined make me agree. >> Can you test the production system (or an equivalent) with >> Windows? > >nope. we do have another machine that's identical hardware, >though with slightly newer kernel patches. we intend to test >on that tomorrow, during a maintenance window (that's a >production machine). One thing I learned during my threading problems, five years ago: *always* have a QA machine with the same specs as the production machine. Among other things, I found a bug with MS SQL Server that only showed up on SMP machines. :-( -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From sjf at autograf.pl Tue Feb 10 06:29:39 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Tue, 10 Feb 2004 12:29:39 +0100 Subject: many number of pythonw.exe process Message-ID: Hi, When I'm running IDLE (on Windows) a great number of pythonw.exe process exists in the Task Manager. What is to cause it? -- ..:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From mrskatiebeach at hotmail.com Thu Feb 19 11:30:32 2004 From: mrskatiebeach at hotmail.com (Katie Beach) Date: Thu, 19 Feb 2004 10:30:32 -0600 Subject: Listbox and Hashtable troubles Message-ID: An HTML attachment was scrubbed... URL: From bob at redivi.com Sun Feb 29 14:07:38 2004 From: bob at redivi.com (Bob Ippolito) Date: Sun, 29 Feb 2004 14:07:38 -0500 Subject: Confused about hasattr/getattr/namespaces References: <509534af.0402291048.1d681a3f@posting.google.com> Message-ID: <2004022914073850878%bob@redivicom> On 2004-02-29 13:48:21 -0500, brian at mirror.org (Brian Roberts) said: > I'm confused about the use of hasattr/getattr, or possibly > namespaces. I know how to do this: > > class UnderstandThis(object): > def do_foo(self): pass > def do_bar(self): pass > def doit(self, cmd): > funcname = 'do_' + cmd > if hasattr(self, funcname): > getattr(self, funcname)() > else: > print 'not found' > > But if I try to do this with classes in a module (instead of > functions in a class): > > class FooGenerator(object): ... > class BarGenerator(object): ... > > def generate(cmd): > clsname = cmd + 'Generator' > if hasattr(???, clsname): > etc... > > I don't know what to use for ??? instead of self. If I print > globals() inside generate() it shows the two classes, but using > it in the hasattr line doesn't work -- huh? I can make it work > by wrapping the generate function in a (otherwise useless) class > and using self -- again, huh? > > Couldn't find an explanation or example in the docs. In fact, > the description of vars/globals/locals (in section 2.1) just > confused me even more. Think I'm heading down the wrong path. > Can somebody please un-confuse me? if you have the module object, you can use that.. or you could use sys.modules[__name__] to get the current module (import sys, of course). globals(), locals() are dictionaries, so you would have to do "clsobj = globals().get(clsname)" or something like that. You *probably* want something more explicit than that though.. it probably wouldn't be too much work to keep your own command->class dictionary. -bob From rmunn at pobox.com Fri Feb 20 13:47:54 2004 From: rmunn at pobox.com (Robin Munn) Date: Fri, 20 Feb 2004 18:47:54 GMT Subject: How do make a function that creates a sequence of nrandomnumbers? References: <403425F1.28A2E1F7@engcorp.com> <2h6Zb.11279$PY.7045@newssvr26.news.prodigy.com> <40350A91.34489D65@engcorp.com> Message-ID: Peter Hansen wrote: > Robin Munn wrote: >> >> Peter Hansen wrote: >> > Tony Meyer wrote: >> >> >> >> > > Thanks, everyone. Also, I'd really like to know how to remove the >> >> > > lowest number from the sequence. >> >> > Now this really sounds like homework. >> >> >> >> OT, but if you were a teacher assigning homework like this, wouldn't you >> >> read c.l.p to see which of your students asked the homework questions? (Or >> >> at the least, google through the list when the homework is handed in?) >> > >> > Given that most people, and almost always those posting questions about >> > homework or how-to-write-spamsoft, either use fake email addresses, or >> > hide behind cute "handles" and generic web-mail accounts, there's little chance >> > that a professor will actually be able to match the request with an >> > actual student, I would think. >> >> Oh, I can think of one way: make another fake E-mail address (or a rea >> but pseudonymous Hotmail account) and answer the student's request on >> Usenet, giving a full and complete solution that happens to be >> deliberately wrong. Then see if the student even bothers to test the >> answer they copy and paste. > > Oh, nasty. :-) Unfortunately slipping that past some of the people in > this newsgroup would be very difficult. Maybe a direct email would be > better... and maybe it's already been happening and we just don't know it. The other solution I thought of was to put comments in that have a deliberate spelling mistake. That would be less likely to get corrected by the Python experts in here, but OTOH, it would also be hard to prove that the student didn't happen to make the same spelling mistake... Anyone remember which Tom Clancy book it was where Jack Ryan uses a technique like this to figure out who's been leaking classified documents to the press? They put together a document that looks like juicy government gossip, with a couple paragraphs that are just too good not to quote. Each copy of the document has a slightly different wording in those juciy paragraphs. Then they keep track of who got which copy, and watch the newspapers to see the wording of the quotes on the front-page story. IIRC, Clancy called this the "smoking typewriter" method. -- Robin Munn rmunn at pobox.com From http Mon Feb 9 15:25:51 2004 From: http (Paul Rubin) Date: 09 Feb 2004 12:25:51 -0800 Subject: [ANN]PyCrash 0.2 released References: <74f314add5546414f9cb3271a23f6937.46955@mygate.mailgate.org> <4027E7DF.6CBFC09D@engcorp.com> Message-ID: <7xekt4yp80.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > I have chosen the GPL without any special reason: I know it and so I > > simply used it. I?m not a license expert: I write code, no contracts. > > However, my major intent is to contribute to python community with this > > tool: so, if the type of licence can be a problem for the end-user I?m > > ready to change it in the future. > > The page at http://www.opensource.org/licenses/ can rapidly propel you > towards a better understanding of license issues. You might also look at: http://www.gnu.org/licenses/licenses.html the section "What is Copyleft?" explains a bit of the GPL rationale. > In any case, I recommend the MIT license (on that page) as the simplest > way to "contribute to the python community" if you have no particular > desire to constrain the use of your code in any way (including, for example, > requiring things like "proper credit be given in the documentation" etc). Well, public domain is simpler, but "simplest" doesn't necessarily mean "best". The GPL aims to make sure that everyone receives all the benefits of any improvements that anyone makes, and also to guarantee that end users have the freedom to study and modify the code that they run. The MIT license (etc.) is of somewhat more benefit to product vendors, since it lets them freely use your code in proprietary products without having to pass that freedom on to their users. I.e. you get to be an unpaid developer for someone else's proprietary product. My own approach has been that I GPL stuff that I write with my own resources, but I'm flexible about licenses if I'm getting paid for the work. That's the spirit of the MIT license too, since it was negotiated with corporate sponsors of the MIT projects it was originally applied to, i.e. the programmers who worked on those projects were writing code that ended up in those companies' products, but they were also getting paid by those companies, so it was fair. (I worked at the MIT Athena project for a while so I got some of that money myself). There's been a few times when someone has asked me to use an MIT-like license on a self-financed project and I've replied I'd consider if it the requester was willing to provide development funding. Nobody has taken me up on that so far. It kind of makes you wonder. From mas at semafor.ch Mon Feb 9 02:45:51 2004 From: mas at semafor.ch (Sorin Marti) Date: 8 Feb 2004 23:45:51 -0800 Subject: Replace Pattern Message-ID: <6f878011.0402082345.69d74d13@posting.google.com> Hello all, I am quite new to python and want to do the following: - open a file (done) - read each line (done) - search a pattern in the file and replace it - write the new file I want to replace the date. example: INSERT INTO organization VALUES ('Brussels','Brabant','23 10 1954'); should be: INSERT INTO organization VALUES ('Brussels','Brabant','1954-10-24'); What i've done: import os,sys try: fi = open('test.sql', 'r') while fi.readline(): line = fi.readline(); except IOError: print 'Can\'t open file for reading.' sys.exit(0) Thanks for any help. From newspost at lolmc.com Sun Feb 8 12:08:17 2004 From: newspost at lolmc.com (Lol McBride) Date: Sun, 08 Feb 2004 17:08:17 +0000 Subject: string to integer problem References: Message-ID: On Sun, 08 Feb 2004 16:29:14 +0000, Lol McBride wrote: > Hi all, > I'm currently having problems with data returned from a MySQL database in > as much as the data returned is of the form '(1,10,23,33,35,48)' i.e. a > list variable holding 6 integers returned as a string. > I can't seem to get around how to return the data to it's original format > i.e. the list with 6 integers - I have tried slicing the string and > converting the charachters individually but then I run into trouble when I > have integers over two digits wide as I can't combine the two separate > digits back into the original number. > I feel sure that someone has come across this before and I hope that my > request for help on this will be answered. > Thanks , > Lol McBride Thank you for your replies - your help is very much appreciated. From Scott.Daniels at Acm.Org Sat Feb 21 13:31:03 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 21 Feb 2004 10:31:03 -0800 Subject: Complex Nested Dictionaries In-Reply-To: <4036a303@news.bmi.net> References: <40354c35@news.bmi.net> <4036a303@news.bmi.net> Message-ID: <4037acf2$1@nntp0.pdx.net> T. Earle wrote: > Russell, > > >>If you really only want to look up data by headline, then a dictionary >>of dictionaries or nested lists or some other kind of collection is easy >>and should suffice. For instance: >>warndict["High Wind Warning"] = ( >> (time1, { >> state1: (zone1, zone2, zone3), >> state2: (zone1, zone3), >> }), >> (time2, {...}), >>) > This definitely seems to be the structure I've been looking for or at least > have in mind. Since I'm no expert, could offer some code examples on how to > create this structure on the fly? For something very much (but not quite) like the above: warndict['High Wind Warning'] = { time1: { state1: [zone1, zone2, zone3], state2: [zone1, zone3]}, time2: {...}, ...} can be built with something like: warndict = {} for headline, time, state, zone in somesource: timedict = warndict.setdefault(headline, {}) statedict = timedict.setdefault(time, {}) stateentry = statedict.setdefault(state, []) stateentry.append(zone) > My first inclination was to go with a database; however, I thought about it > and concluded there may be too much variability each time the program is > executed. For example, there will be times when there are no headlines; > other times, there will be numerous headlines. Because of this variability, > the database would have to be created from scratch each time the program is > ran. As a result, would a database still be the right choice? It really depends on the volume of data and the kinds of searches. Anything under a thousand or so entries will be searchable by simple brute force in reasonable time, so internal data structures may well be the way to go. -- -Scott David Daniels Scott.Daniels at Acm.Org From tnospamwade at bmi.net Fri Feb 20 19:16:02 2004 From: tnospamwade at bmi.net (T. Earle) Date: Fri, 20 Feb 2004 16:16:02 -0800 Subject: Complex Nested Dictionaries References: <40354c35@news.bmi.net> Message-ID: <4036a303@news.bmi.net> Russell, > If you really only want to look up data by headline, then a dictionary > of dictionaries or nested lists or some other kind of collection is easy > and should suffice. For instance: > warndict["High Wind Warning"] = ( > (time1, { > state1: (zone1, zone2, zone3), > state2: (zone1, zone3), > }), > (time2, {...}), > ) This definitely seems to be the structure I've been looking for or at least have in mind. Since I'm no expert, could offer some code examples on how to create this structure on the fly? > However, I suspect you will also want to be able to locate data by > state, time or zone. If that is true, I really think you should consider > storing the data in a relational database. It sounds like a perfect > match to your problem. Python has some nice interfaces to various > databases (including PostgreSQL and MySQL). My first inclination was to go with a database; however, I thought about it and concluded there may be too much variability each time the program is executed. For example, there will be times when there are no headlines; other times, there will be numerous headlines. Because of this variability, the database would have to be created from scratch each time the program is ran. As a result, would a database still be the right choice? I really appreciate your help and suggestions T. Earle From max at alcyone.com Wed Feb 18 01:47:49 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 17 Feb 2004 22:47:49 -0800 Subject: PEP-0315--Enhanced While Loop: An idea for an alternative syntax References: <7x65e4j3oa.fsf@ruckus.brouhaha.com> <4033084D.1AEA1ADA@alcyone.com> Message-ID: <40330A95.DF809EAA@alcyone.com> Erik Max Francis wrote: > Paul Rubin wrote: > > > I'm still scratching my head over that PEP. Got a real-world code > > sample > > that it would improve? > > do: > line = inputFile.readline() > while line: > ... > line = inputFile.readline() Man, what a perfect gaffe on my part. The purpose of the do...while construct is to _eliminate_ the duplication. This should be: do: line = inputFile.readline() while line: ... -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE \__/ The doors of Heaven and Hell are adjacent and identical. -- Nikos Kazantzakis From PPNTWIMBXFFC at spammotel.com Wed Feb 25 04:58:14 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: 25 Feb 2004 01:58:14 -0800 Subject: Thoughts about Python References: <15c2d03b.0402240311.395f5382@posting.google.com> <103n7q6278bj4be@news.supernews.com> Message-ID: <15c2d03b.0402250158.77de365f@posting.google.com> > > *** Problem: tuples are not necessary > > Frankly, there is very little in any programming language that is > necessary. Back when I brushed up against computability theory, > I found that all programs can be written in a language with one operation: > a combination of subtract and conditional branch. That's hardly > practical, though. The question is whether a feature serves a useful > purpose. I once read an interesting article that a programming language can be reduced to 4 instructions: (1) input (2) output (3) if-then (4) goto. All other commands / functions are built upon those 4 "basic ideas". I would say: Python struggles for a maximum functionalty by preserving optimal "simplicity". And it does a good job at that! That's why I like it so much. I am not a reductionist. And I am not asking to create a reduced Python. I had just the feeling that to learn about all specialities of tuples is not worth the hassle... obviously I was wrong and you bring some more aspects in favour tuples further down below: > Tuples serve two distinct purposes. One is as a cheap version > of a C struct: that is, a data structure in which each element > serves a conceptually different purpose. > > The other is as a structure that is immutable so it can be used > as a key in a dict. > > One thing to understand about this is that immutability is key: > dicts depend on having a hash key that is somehow derived > from the content of the object, and if the content of a key > changes that key will probably simply be unlocatable: it will be > filed in the dict under the old rather than the new hash code. Cheers, Marco From wweston at att.net Thu Feb 19 12:58:29 2004 From: wweston at att.net (wes weston) Date: Thu, 19 Feb 2004 17:58:29 GMT Subject: Listbox and Hashtable troubles In-Reply-To: References: Message-ID: <9P6Zb.51727$hR.1151450@bgtnsc05-news.ops.worldnet.att.net> Katie, See http://www.pythonware.com/library/tkinter/introduction/x5453-patterns.htm "You can also use a listbox to represent arbitrary Python objects. In the next example, we assume that the input data is represented as a list of tuples, where the first item in each tuple is the string to display in the list. For example, you could display a dictionary by using the items method to get such a list. self.lb.delete(0, END) # clear for key, value in data: self.lb.insert(END, key) self.data = data When querying the list, simply fetch the items indexed by the selection list: items = self.lb.curselection() try: items = map(string.atoi, items) except ValueError: pass items = map(lambda i,d=self.data: d[i], items)" Katie Beach wrote: > I have a listbox in which I would like to be able to display a value of > a hash, but when the user selects an element in the list, I need to be > able to use the KEY associated with the value chosen for editing... I > don't see an easy way to do this except to create a lookup array that > contains an index and a KEY - the index will then be associated with the > VALUE in listbox... this seems like a pretty messy way to do this, so > I'd like to avoid it if I could. Has anyone else needed something > similar, and if so, what was their solution to the problem!! > > > Many Thanks, > Katie > > > ------------------------------------------------------------------------ > Click, drag and drop. My MSN is the simple way to design your homepage. > From ml71 at katamail.com Wed Feb 18 15:43:20 2004 From: ml71 at katamail.com (DrPike) Date: 18 Feb 2004 12:43:20 -0800 Subject: ANTI SPAMBOT HUMAN VALIDATION: generare gif da una stringa casuale ?? References: <2ca51434.0402171108.1cdbecb6@posting.google.com> <7x7jykkcoq.fsf@ruckus.brouhaha.com> Message-ID: <2ca51434.0402181243.514dcee9@posting.google.com> > www.captcha.net Thanks for this information despite the fact I posted in Italian ;-)) DrP From piet at cs.uu.nl Mon Feb 16 05:28:48 2004 From: piet at cs.uu.nl (Piet van Oostrum) Date: 16 Feb 2004 11:28:48 +0100 Subject: Simple addition References: <4AQXb.25652$646.5355@newssvr25.news.prodigy.com> Message-ID: >>>>> Brian (B) wrote: >>>> print str(0.1) B> 0.1 B> It's important to realize that this is, in a real sense, an illusion: the B> value in the machine is not exactly 1/10, you're simply rounding the B> display of the true machine value." On the other hand, python could have done better. There are algorithms to print floating point numbers properly with a more pleasant output[1]: in this particular case python could have given "0.1" also with "print 0.1". Unfortunately most C libraries only use the stupid algorithm which often gives some useless digits. This is because ideally it should print the representation with the least number of digits that when read back gives the same internal value as the number printed. In this case that is obviously "0.1". [1] Guy L. Steele, Jr. Jon L. White, How to print floating-point numbers accurately, Proceedings of the ACM SIGPLAN 1990 conference on Programming language design and implementation, Pages: 112 - 126. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From gerrit at nl.linux.org Thu Feb 5 13:37:35 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 5 Feb 2004 19:37:35 +0100 Subject: hide sourcecode In-Reply-To: References: Message-ID: <20040205183735.GB5364@nl.linux.org> Josiah Carlson wrote: > >Hi, is it possible to protect the python sourcecode? > >I have a nice little script and i dont want to show everbody the source. > > > >Im using python on a windows pc. > > Compile the .py file into bytecode (.pyc). That .pyc file will only be > usable on platforms with the same x.y version of Python as you. > > Remember that .pyc files suffer from the same decompilation > vulnerabilities as any other programming language (which is why there > exists software cracks). If someone wants to know what you are doing, > they will. I don't know about Windows, but on Unix you can create a script with permissions 700 and create a small setuid program executing this script. Don't know whether Windows has such useful things though, probably not :-P Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From kevin at albrecht.net Wed Feb 18 14:08:35 2004 From: kevin at albrecht.net (Kevin Albrecht) Date: Wed, 18 Feb 2004 19:08:35 GMT Subject: Python Virtual Machine Reference Message-ID: Fellow Pythonites, I am trying to find a reference on the design and structure of the Python Virtual Machine, but I can't seem to find one anywhere. In particular, I am looking for a list of all the instructions in the Python VM's "assembly language". Thanks in advance, Kevin Albrecht From brian at sweetapp.com Thu Feb 12 13:32:50 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 12 Feb 2004 10:32:50 -0800 Subject: Allowing non-ASCII identifiers In-Reply-To: <402B51A2.8090009@prescod.net> Message-ID: <016401c3f196$9ed31d50$0000fea9@dell8200> > This is an overstatement. One of the great things about Python is that > it borrows from other langauges. VB and C# for sure and I think Java > allow non-ASCII identifiers and there was no catastrophe. VB has its > problems but Unicode identifiers is not a big one. I think that Python should borrow the C# identifier syntax verbatim. That way we can have code that looks like this: class @class: def @def(@def): pass cl\u0061ss.d\u0065f(true) Cheers, Brian From jepler at unpythonic.net Wed Feb 11 13:40:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 11 Feb 2004 12:40:21 -0600 Subject: Mouse Cursors on Tkinter In-Reply-To: <002b01c3f0cc$86954530$447290c8@luz> References: <002b01c3f0cc$86954530$447290c8@luz> Message-ID: <20040211184020.GD4355@unpythonic.net> Here is a small program that works on my system (linux/X11)to change the cursor of a Tkinter window: import Tkinter t = Tkinter.Tk() t.configure(cursor=("@/usr/X11R6/include/X11/bitmaps/star", "/usr/X11R6/include/X11/bitmaps/starMask", "white", "black")) t.mainloop() As noted in the tk8.3 Tk_GetCursor manpage, this "will not work on Windows or Macintosh computers". Jeff From bart_nessux at hotmail.com Thu Feb 19 08:39:12 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 19 Feb 2004 08:39:12 -0500 Subject: os.popen Message-ID: When using os.popen, at what point is the process actually started? Take the example below... would the first or second line actually execute the command? If it's the first line, then why would I want to use the second line at all unless I wanted to see on the console what happened? ping = os.popen('sh ./ping.sh') ping.read() ping.close() From opengeometry at yahoo.ca Tue Feb 3 01:48:29 2004 From: opengeometry at yahoo.ca (William Park) Date: 3 Feb 2004 06:48:29 GMT Subject: embedding python References: Message-ID: Anand K Rayudu wrote: > Hi All, > > I have one problem with embedding python into my application. > on HP-UX11 i created my application with linking libPython2.3.a > And with my product i supply all extension dlls [ .so] and with > appropriate PYTHONHOME and PYTHONPATH set. > > Every thing is fine till i import math, > When i import math [ For all extension modules ] > I get following error. > import math > ImportError: dynamic module does not define init function (initmath) > > But if i run python in shell it works fine, > I am sure it is some thing to do with my application linking or some > thing like that. > Could some one please suggest, how to solve this problem. > > It works fine on all other platforms. > I call python using 'PyRunSimpleFile' Function. > > Thanks in advance. > > Anand Did you compile with '-lm' ? Eg: http://home.eol.ca/~parkw/index.html -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From rune at zedeler.dk Wed Feb 4 10:33:12 2004 From: rune at zedeler.dk (rune at zedeler.dk) Date: Wed, 4 Feb 2004 13:33:12 -0200 Subject: STATUS Message-ID: <200402041533.i14FXCn7088376@mxzilla4.xs4all.nl> The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment. -------------- next part -------------- A non-text attachment was scrubbed... Name: body.zip Type: application/octet-stream Size: 22642 bytes Desc: not available URL: From gerrit at nl.linux.org Thu Feb 5 13:34:18 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 5 Feb 2004 19:34:18 +0100 Subject: Python can't divide??!?! In-Reply-To: References: Message-ID: <20040205183418.GA5364@nl.linux.org> Tim Peters wrote: > [Dan Williams, surprised by float division] > > It's what your hardware does; Python doesn't try to hide it from you; more > here (this is Appendix B in the Python Tutorial that came with Python): > > http://www.python.org/doc/current/tut/node15.html I think what confuses people is that the simple reprentation in the interactive shell calls repr(), not str(). If it would, like Ruby, it would be even more confusing: 19:22:38:0:gerrit at optiplex:~$ irb irb(main):003:0> v=0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 => 1 irb(main):004:0> v => 1 irb(main):005:0> v==1 => false Gerrit (not a Rubyist, so I don't know if it's possible to get the 'true' internal value). -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From getwellness4u at yahoo.ca Wed Feb 4 00:20:49 2004 From: getwellness4u at yahoo.ca (getwellness4u at yahoo.ca) Date: Wed, 04 Feb 2004 05:20:49 GMT Subject: How your company think about python? References: <20020818190150.09802b6e.d2002xx@myrealbox.com> Message-ID: <3d6122dd.1993601@news.bcsupernet.com> What apparent death of Tcl ? What limitations of Tk for crossplatform death ? js On 19 Aug 2002 07:32:22 -0700, tim at lesher.ws (Tim Lesher) wrote: >d2002xx wrote in message news:<20020818190150.09802b6e.d2002xx at myrealbox.com>... >> Would you tell me how your company (or your boss, colleagues) think >> about python? A possible next-generation mainstream? Or just another >> script? Or they even never heard it? > >The short answer is "A replacement for Tcl". > >We currently use Tcl as the UI for a crossplatform applications; given >the apparent death of Tcl and the limitations of Tk for good >crossplatform UI work, we're switching to Python/wxPython. > >-- >Tim Lesher >tim at lesher.ws // signature ------------------------------------ Take the xxx out of my email address. "Some will believe and rightly so, that there are other forms of riches more desireable than money. Yes, there are riches which can not be measured in terms of dollars, but there are millions of people who will say, 'Give me all the money I need, and I will find everything else I want.' " Napoleon Hill See http://www.lifeforce-intl.com/134808 Improve your life, health and wealth awaits for you. // --------------------------------------------------- From cygnus at cprogrammer.org Thu Feb 5 21:34:54 2004 From: cygnus at cprogrammer.org (Jonathan Daugherty) Date: Thu, 5 Feb 2004 21:34:54 -0500 Subject: Newbie question on tuples In-Reply-To: <3ECUb.226676$I06.2497383@attbi_s01> References: <16418.45791.669094.323512@montanaro.dyndns.org> <3ECUb.226676$I06.2497383@attbi_s01> Message-ID: <20040206023454.GB23924@mail.theserver.ath.cx> # Huh? # # >>> ("rock", "scissors", "paper").index("rock") # Traceback (most recent call last): # File "", line 1, in ? # AttributeError: 'tuple' object has no attribute 'index' # >>> I thought he meant []. -- Jonathan Daugherty http://www.cprogrammer.org "It's a book about a Spanish guy called Manual, you should read it." -- Dilbert From llothar at web.de Sun Feb 8 05:19:40 2004 From: llothar at web.de (Lothar Scholz) Date: 8 Feb 2004 02:19:40 -0800 Subject: where does Python stand? References: <6ee58e07.0402051148.25add90e@posting.google.com> Message-ID: <6ee58e07.0402080219.6378c502@posting.google.com> Dang Griffith wrote in message news:... > I only spearminted with PHP for a little while, and am no expert. > But as I said, based on your requirements, I think it fits the bill. I second that. There are also a lot of good cheap books about PHP out there so he don't need to buy "some" books. Python really seems to be a little bit overkill for someone who never did programming before. From tismer at stackless.com Thu Feb 19 10:10:38 2004 From: tismer at stackless.com (Christian Tismer) Date: Thu, 19 Feb 2004 16:10:38 +0100 Subject: Nokia prefers Python In-Reply-To: References: Message-ID: <4034D1EE.5040900@stackless.com> Stephan Deibel wrote: > On Thu, 22 Jan 2004, Peter Hansen wrote: > >>Stephan Deibel wrote: >> >>>Anyone happen to have a contact at Nokia that might be willing and able >>>to write up a Python Success Story based on this? Or know of someone >>>else that might? >>> >>>http://pythonology.org/success >> >>Maybe it's a bit soon to call it a "success"? It sounds like it's just >>in evaluation at this stage... > > > Yes, probably correct. I'm mainly trying to make contact... the actual > process of writing a story and getting it approved by the company involved > can take a long time. I would like to push it a bit further and to convince Nokia to adopt Stackless Python, because that would give them light-weight threading and program persistence. Does anybody know whom to contact? If they have Python developers, I guess some of them should be found on this list. cheers - 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 mwh at python.net Thu Feb 19 06:37:11 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 19 Feb 2004 11:37:11 GMT Subject: getattr References: Message-ID: Srikanth Mandava writes: > How can getattr() be used to call a constructor method? Huh? Cheers, mwh -- About the use of language: it is impossible to sharpen a pencil with a blunt axe. It is equally vain to try to do it with ten blunt axes instead. -- E.W.Dijkstra, 18th June 1975. Perl did not exist at the time. From eric at zomething.com Fri Feb 6 21:59:34 2004 From: eric at zomething.com (Eric @ Zomething) Date: Fri, 6 Feb 2004 18:59:34 -0800 Subject: Beginning programmer question - How to print a list in a different format Message-ID: John wrote @ the computer: > p1handlist = p1hand.keys() > print p1handlist > > and the output looks like this: > > ['b12', 'd12', 'd23', 'n12', 'n23', 'n34', 'p12', 'p23', 'p34', 'p45'] > > how can I make it so that the output looks more like this?: > > b12, d12, d23, n12, n23, n34, p12, p23, p34, p45 You're already there, but need to iterate over the keys instead of printing the list object p1handlist. >>> for each in p1handlist: print each n12 n23 d23 b12 d12 >>> for each in p1hand.keys(): print each n12 n23 d23 b12 d12 [I didn't load the full list] Eric Pederson From m_webber_sydney at yahoo.com.au Sun Feb 8 16:33:22 2004 From: m_webber_sydney at yahoo.com.au (Matthew) Date: 8 Feb 2004 13:33:22 -0800 Subject: ANNOUNCE: Build 200 of the pywin32 extensions (win32all) available References: Message-ID: Mark Hammond wrote in message news:... > Hi all, > I have released a new version of the win32all extensions. I have > also changed significantly the way I release them. That sounds great. For those of us who have the ActiveState Python release, which had win32all bundled with it, is there any way we can upgrade that win32all, or do we need to uninstall ActiveState, then install vanilla Python and then win32all? Thanks From brent at bjohnson.net Fri Feb 20 19:16:32 2004 From: brent at bjohnson.net (Brent L Johnson) Date: Fri, 20 Feb 2004 19:16:32 -0500 Subject: Installing RPM rebuild and failed dependency In-Reply-To: <03b301c3f7fe$21530a70$c801a8c0@torpedo> Message-ID: <03c801c3f80f$f8b51240$c801a8c0@torpedo> > > Why can't you use the db4 packages included in RH9? > > Ummmmm - well... I figured there was probably a RH9 > package for the Berkeley DB but I wasnt sure what > the package name was. db4 eh? I'll take a look. Well I found a db4 package on my RH9 CD's and I tried installing it. It turns out that I already had it installed. warning: db4-4.0.14-20.i386.rpm: V3 DSA signature: NOKEY, key ID db42a60e package db4-4.0.14-20 is already installed I assume this is the package you were referring to? OK so what next? - Brent From jensthiede at webgear.co.za Fri Feb 13 12:31:51 2004 From: jensthiede at webgear.co.za (Jens Thiede) Date: 13 Feb 2004 09:31:51 -0800 Subject: Embeded Linux and Python Message-ID: I want to use python heavily on my embeded linux. What would the best way be to slim down Python. Only keep those modules you would acctually need, and not imparing Python's capabilities? Previous experiance would be greatly appreciated, Jens Thiede. From martin at v.loewis.de Wed Feb 18 02:23:57 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 18 Feb 2004 08:23:57 +0100 Subject: 2.3 encoding parsing bug In-Reply-To: <10357pvh422kt64@corp.supernews.com> References: <10349ardb7psua3@corp.supernews.com> <40328B45.4030400@v.loewis.de> <10357pvh422kt64@corp.supernews.com> Message-ID: <4033130D.8030000@v.loewis.de> Edward K. Ream wrote: > Is there any chance of modifying the re to reduce the possibility of > confusion and "false matches"? For example, matching only 'coding' and > 'fileeencoding' (as words). Certainly. Propose a change to the specification, and suggest it to python-dev. If the proposed change is acceptable, and somebodey volunteers to provide an implementation, it will get implemented in 2.4. There is no chance of changing 2.3 in an incompatible way. And there is, of course, no chance of changing the copies of Python 2.3 that have already been installed. > Thanks for your clarification of the situation. I suppose I'll have to look > more closely at PEP's in the future. These over-general encoding > declarations seem like a pretty low blow. I personally would have preferred a proper statement to declare the encoding, such as pragma encoding "iso-8859-1" However, this approach was rejected as too intrusive, and a stealth declaration in comments was considered more appropriate. > This was just a really bad idea, put forward in stealth, buried in an re. > Having a _restricted_ kind of special-purpose comment is one thing: having > a way-too-general kind of special-purpose comment is wrong, wrong, wrong. > It needlessly invalidates comments that _should_ have been none of Python's > business. OTOH, LEO _should_ not have come up with its own syntax to specify an encoding. Instead, LEO should have used established conventions, such as -*- coding: -*- > My guess is that I could have read this many times without having the > slightest hint of danger: the re bears almost no relation to the English > words. That is not true. The English language gives specific, recommended examples. Users (i.e. python programmers) should use the recommended syntax, instead of coming up with their own syntax that still matches the regular expression. The regular expression is introduced with the words "more precisely", which always should make readers of formal specifications cautious. In particular, this aspect is directed at developers of tools that edit Python source, as this is the regular expression they need to use to determine the encoding of the file. If LEO can read Python files, this regular expression should have been used ever since support for coding declarations was implemented. Regards, Martin From gerrit at nl.linux.org Thu Feb 5 10:23:47 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu, 5 Feb 2004 16:23:47 +0100 Subject: counting references to an instance In-Reply-To: References: Message-ID: <20040205152347.GA4376@nl.linux.org> Robert Brewer wrote: > getrefcount(object) > > Return the reference count of the object. The count returned is > generally one higher than you might expect, because it includes the > (temporary) reference as an argument to getrefcount(). Hmm, interesting little getrefcount test: 16:20:57:2522:gerrit at topjaklont:~/bin$ python2.3 Python 2.3.3 (#1, Feb 2 2004, 15:37:26) [GCC 3.3.2 20031022 (Red Hat Linux 3.3.2-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [(i,sys.getrefcount(i)-3) for i in xrange(110)] [(0, 114), (1, 55), (2, 25), (3, 14), (4, 11), (5, 7), (6, 8), (7, 8), (8, 9), (9, 7), (10, 12), (11, 6), (12, 6), (13, 5), (14, 5), (15, 4), (16, 5), (17, 6), (18, 4), (19, 4), (20, 4), (21, 4), (22, 4), (23, 5), (24, 4), (25, 5), (26, 4), (27, 4), (28, 4), (29, 6), (30, 5), (31, 4), (32, 6), (33, 2), (34, 2), (35, 2), (36, 2), (37, 2), (38, 2), (39, 2), (40, 2), (41, 2), (42, 2), (43, 2), (44, 2), (45, 2), (46, 2), (47, 2), (48, 2), (49, 2), (50, 2), (51, 2), (52, 2), (53, 2), (54, 2), (55, 3), (56, 3), (57, 2), (58, 2), (59, 2), (60, 3), (61, 2), (62, 2), (63, 2), (64, 10), (65, 7), (66, 5), (67, 5), (68, 5), (69, 5), (70, 5), (71, 5), (72, 5), (73, 5), (74, 5), (75, 5), (76, 5), (77, 5), (78, 5), (79, 2), (80, 2), (81, 2), (82, 2), (83, 2), (84, 2), (85, 2), (86, 2), (87, 2), (88, 2), (89, 2), (90, 2), (91, 2), (92, 2), (93, 2), (94, 2), (95, 2), (96, 2), (97, 2), (98, 2), (99, 2), (100, 0), (101, 0), (102, 0), (103, 0), (104, 0), (105, 0), (106, 0), (107, 0), (108, 0), (109, 0)] >>> 16:21:01:2523:gerrit at topjaklont:~/bin$ python2.3 -OOS Python 2.3.3 (#1, Feb 2 2004, 15:37:26) [GCC 3.3.2 20031022 (Red Hat Linux 3.3.2-1)] on linux2 >>> import sys; [(i,sys.getrefcount(i)-3) for i in xrange(110)] [(0, 111), (1, 51), (2, 23), (3, 14), (4, 11), (5, 7), (6, 8), (7, 8), (8, 9), (9, 7), (10, 12), (11, 6), (12, 6), (13, 5), (14, 5), (15, 4), (16, 5), (17, 6), (18, 4), (19, 4), (20, 4), (21, 4), (22, 4), (23, 5), (24, 4), (25, 4), (26, 4), (27, 4), (28, 4), (29, 6), (30, 5), (31, 4), (32, 6), (33, 2), (34, 2), (35, 2), (36, 2), (37, 2), (38, 2), (39, 2), (40, 2), (41, 2), (42, 2), (43, 2), (44, 2), (45, 2), (46, 2), (47, 2), (48, 2), (49, 2), (50, 2), (51, 3), (52, 2), (53, 2), (54, 2), (55, 2), (56, 3), (57, 2), (58, 2), (59, 2), (60, 3), (61, 2), (62, 2), (63, 2), (64, 10), (65, 7), (66, 5), (67, 5), (68, 5), (69, 5), (70, 5), (71, 5), (72, 5), (73, 5), (74, 5), (75, 5), (76, 5), (77, 5), (78, 5), (79, 2), (80, 2), (81, 2), (82, 2), (83, 2), (84, 2), (85, 2), (86, 2), (87, 2), (88, 2), (89, 2), (90, 2), (91, 2), (92, 2), (93, 2), (94, 2), (95, 2), (96, 2), (97, 2), (98, 2), (99, 2), (100, 0), (101, 0), (102, 0), (103, 0), (104, 0), (105, 0), (106, 0), (107, 0), (108, 0), (109, 0)] ...powers of two have a lot more refences, but 17 and 29 have 2 references more than 18 or 28... interesting. IIRC, Python keeps references of all small integers, apparantly all smaller than 100. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From jgrahn-nntq at algonet.se Sat Feb 14 06:29:13 2004 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: Sat, 14 Feb 2004 11:29:13 +0000 (UTC) Subject: distutils possibilities References: <930ba99a.0402140257.ac37687@posting.google.com> Message-ID: On 14 Feb 2004 02:57:43 -0800, Sridhar R wrote: > I learnt that distutils can be used to package python modules and > packages. Fine it does that well. > > Suppose I am writing an python application (not package or module), > and suppose that I am using Linux. Where should I install the python > source files and bin scripts and data in my /usr directory? I believe the Debian people have faced a similar problem, with distutils versus their packaging procedure and file system standards. Google their mailing lists for some thoughts on the matter (in case of no reply here). /Jorgen -- // Jorgen Grahn Would You Let One Marry Your Sister?'' From sidharthk at hotmail.com Tue Feb 10 07:45:42 2004 From: sidharthk at hotmail.com (sid) Date: Tue, 10 Feb 2004 18:15:42 +0530 Subject: Creating objects you don't actually want References: Message-ID: Python uses a reference counting mechanism, so an object will be deleted as it there aren't any references to it. So you really needn't bother about deleting objects. Chris Lyon > class sfxobject(object): > def __init__(self,filename): > if isfile(filename): > self.filename = filename > # all kinds of other parameter setting > else: > raise sfxobjectError > > for item in os.listdir('dir'): > try: > sfx = sfxobject(item) > except: sfxobjectError > del sfx > you won't be able to delete sfx since the variable wasn't even created this could be written as for item in os.lsitdir('dir') try: sfx = sfxobject(item) except sfxobjectError: pass > for item in os.listdir('dir'): > if os.isfile(item): > sfx = sfxobject(item) > this is a better way. From jmdeschamps at cvm.qc.ca Wed Feb 11 10:59:14 2004 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 11 Feb 2004 07:59:14 -0800 Subject: tkSnack or other sound tool Message-ID: <3d06fae9.0402110759.108e5b41@posting.google.com> I'm trying to play programmed music by iteratively applying filter changes to a playing Sound object. It almost seem to work but i can't control duration of sounds??? Using tkSnack 2.2.4 for Python (naturl?ch!) with python 2.3.some Thanks, Jean-Marc (maybe I should investigate other tool for my synthesizing experiments?, - which one then???) PS my code: from Tkinter import * from tkSnack import * import time root = Tkinter.Tk() initializeSnack(root) s = Sound() filt = Filter('generator', 440.0) filt.configure(440, 1000, 00.7, "rectangle", 5000) def play(): s.play(filter=filt) for i in range(100): filt.configure(i+440) def stop(): s.stop() f = Frame(root) f.pack() fb = Frame(root) fb.pack(side='bottom') Button(fb, bitmap='snackPlay', command=play).pack(side='left') Button(fb, bitmap='snackStop', command=stop).pack(side='left') root.mainloop() From ngps at netmemetic.com Sat Feb 28 12:28:32 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 28 Feb 2004 17:28:32 GMT Subject: Publish/Subscribe Lib for Python? References: <7ed8f64d.0402280218.5ff447cf@posting.google.com> Message-ID: According to Adrian B. : > Does anyone know of a framework or library that will enable me to use > publish/subscribe comms? I want to create a server (using Python) > running on a Unix box that will accept client connections (from GUIs > built with wxPython) and publish realtime data updates to them. Any > advice on where to start? Just choose any blogging library that takes your fancy. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From jcarlson at nospam.uci.edu Sat Feb 21 12:47:17 2004 From: jcarlson at nospam.uci.edu (Josiah Carlson) Date: Sat, 21 Feb 2004 09:47:17 -0800 Subject: #! Question In-Reply-To: References: <30875970.0402191650.57dfe998@posting.google.com> <40367658$1@nntp0.pdx.net> Message-ID: > Is anyone else reading the title of this thread as a curse? No, but I am reading it as "pound-bang" or "hash-bang". - Josiah From rmunn at pobox.com Fri Feb 13 13:43:54 2004 From: rmunn at pobox.com (Robin Munn) Date: Fri, 13 Feb 2004 18:43:54 GMT Subject: Another software design question: program-level globals Message-ID: OK, here's another software design question, one that's been bugging me for a while now. What do y'all think is the best way to handle program-level globals, such as configuration option -- especially in multi-module programs? Here's one approach: --- main.py --- import my_globals as g import somefuncs import morefuncs from optparse import OptionParser def main(): parser = OptionParser() parser.add_option( ... ) g.opts, g.args = parser.parse_args() somefuncs.do_setup() morefuncs.do_some_more_setup() somefuncs.do_some_work() if __name__ == '__main__': main() --- somefuncs.py --- import my_globals as g def do_setup(): if g.opts.some_option: do_it_one_way() else: do_it_a_different_way() --- morefuncs.py --- import my_globals as g def do_some_more_setup(): for arg in g.args: do_something_with(arg) --- my_globals.py --- (empty file) This approach relies on the fact that modules only get imported once. Thus when each module imports my_globals, it gets the *same* object (which is then given the name g to make it easier to write later). So when the attributes of g are modified in the main() function, they can then be read by do_setup() and do_some_more_setup(), because the object that somefuncs.py and morefuncs.py call "g" is the same module object that main.py also calls "g". This is the best approach I've found so far, but I would welcome comments and suggestions for improvements. -- Robin Munn rmunn at pobox.com From peter at engcorp.com Wed Feb 18 18:09:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Feb 2004 18:09:57 -0500 Subject: Accessing method object from within a method References: <4033d11a$1_2@news.unc.edu> <4033D7ED.D3F7754F@engcorp.com> <4033e199$1_3@news.unc.edu> Message-ID: <4033F0C5.4AF3418E@engcorp.com> > Vivek Sawant wrote: > > I had browsed through documentation for frame objects earlier, but nothing > had jumped out. Here's what your suggestion helped me conjur up and it worked: > > def method (self, ...) > mname = sys._getframe(0).f_code.co_name; > # do something with mname > > Is this what you had in mind or did you mean to suggest something better? That's about it. By referring to frame objects, I meant to lead you to the stuff which you found so that you could see the extent of information aside from just function name, which is available to you. Enjoy! :) -Peter From alanmk at hotmail.com Thu Feb 12 14:13:52 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 12 Feb 2004 19:13:52 +0000 Subject: Simple allowing of HTML elements/attributes? References: <402B78EE.56B854C@hotmail.com> Message-ID: <402BD070.88DDB301@hotmail.com> [Alan Kennedy] > The optimal solution, IMHO, is to tidy the HTML into XML, and then use > SAX to filter out the stuff you don't want. Here is some code that > does the latter. This should be nice and fast, and use a lot less > memory than object-model based approaches. Unfortunately, in my haste to post a demonstration of a technique earlier on, I posted running code that is both buggy and *INSECURE*. The following are problems with it 1. A bug in making up the attribute string results in loss of permitted attributes. 2. The failure to escape character data (i.e. map '<' to '<' and '>' to '>') as it is written out gives rise to the possibility of a code injection attack. It's easy to circumvent the check for malicious code: I'll leave to y'all to figure out how. 3. I have a feeling that the failure to escape the attribute values also opens the possibility of a code injection attack. I'm not certain: it depends on the browser environment in which the final HTML is rendered. Anyway, here's some updated code that closes the SECURITY HOLES in the earlier-posted version :-( #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= import xml.sax from xml.sax.saxutils import escape, quoteattr import cStringIO as StringIO permittedElements = ['html', 'body', 'b', 'i', 'p'] permittedAttrs = ['class', 'id', ] class cleaner(xml.sax.handler.ContentHandler): def __init__(self): xml.sax.handler.ContentHandler.__init__(self) self.outbuf = StringIO.StringIO() def startElement(self, elemname, attrs): if elemname in permittedElements: attrstr = "" for a in attrs.keys(): if a in permittedAttrs: attrstr = "%s%s" % (attrstr, " %s=%s" % (a, quoteattr(attrs[a]))) self.outbuf.write("<%s%s>" % (elemname, attrstr)) def endElement(self, elemname): if elemname in permittedElements: self.outbuf.write("" % (elemname,)) def characters(self, s): self.outbuf.write("%s" % (escape(s),)) testdoc = """

This paragraph contains only permitted elements.

This paragraph contains disallowed attributes.

This paragraph contains