itools 0.13.9 released
itools is a Python library, it groups a number of packages into a single meta-package for easier development and deployment: itools.catalogitools.http itools.tmx itools.cmsitools.i18n itools.uri itools.csvitools.ical itools.web itools.datatypes itools.resourcesitools.workflow itools.gettextitools.rss itools.xhtml itools.handlers itools.schemas itools.xliff itools.html itools.stl itools.xml Changes: URI - Fix the mailto scheme, return always a Mailto object, by Hervé Cauwelier [#421]. CSV - Fix deleting rows, by Hervé Cauwelier [#423]. - Fix index initialization, by Hervé Cauwelier [#339]. Web - More robust code to load requests. - Change a little the error log format, add the date. CMS - Now views can have a URI query, by Hervé Cauwelier [#308]. - Update access control declarations, by Hervé Cauwelier [#446]. Resources - Download http://download.ikaaro.org/itools/itools-0.13.9.tar.gz Home http://www.ikaaro.org/itools Mailing list http://mail.ikaaro.org/mailman/listinfo/itools Bug Tracker http://bugs.ikaaro.org -- J. David Ibáñez Itaapy http://www.itaapy.com Tel +33 (0)1 42 23 67 45 9 rue Darwin, 75018 Paris Fax +33 (0)1 53 28 27 88 -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Help in string.digits functions
Anoop wrote: Hi All I am getting two different outputs when i do an operation using string.digits and test.isdigit(). Is there any difference between the two. Your first sentence appears to answer that ..but yes, there's quite a difference. Have you read the manual? I have given the sample program and the output There is a much better way to try out very small snippets of code than putting them in a script: use the Python interactive prompt. import string string.digits '0123456789' '0' in string.digits True '9' in string.digits True '90' in string.digits False '90' in string.digits False '123' in string.digits True 'oo' in 'Anoop' True '' in 'Anoop' True Manual: For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so in abc will return True. Changed in version 2.3: Previously, x was required to be a string of length 1. '12345'.isdigit() True ''.isdigit() False 'xyz'.isdigit() False '123xyz'.isdigit() False '123 '.isdigit() False ' 123'.isdigit() False Manual: isdigit( ) Return true if all characters in the string are digits and there is at least one character, false otherwise. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
building an index for large text files for fast access
Hi, I need to read specific lines of huge text files. Each time, I know exactly which line(s) I want to read. readlines() or readline() in a loop is just too slow. Since different lines have different size, I cannot use seek(). So I am thinking of building an index for the file for fast access. Can anybody give me some tips on how to do this in Python? Thanks. Yi -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression - matches
On 22/07/2006 2:18 AM, Simon Forman wrote: John Salerno wrote: Simon Forman wrote: Python's re.match() matches from the start of the string, so if you (1) Every regex library's match() starts matching from the beginning of the string (unless of course there's an arg for an explicit starting position) -- where else would it start? (2) This has absolutely zero relevance to the match whole string or not question. want to ensure that the whole string matches completely you'll probably want to end your re pattern with the $ character (depending on what the rest of your pattern matches.) *NO* ... if you want to ensure that the whole string matches completely, you need to end your pattern with \Z, *not* $. Perusal of the manual would seem to be indicated :-) Is that necessary? I was thinking that match() was used to match the full RE and string, and if they weren't the same, they wouldn't match (meaning a begin/end of string character wasn't necessary). That's wrong? Yes. If the default were to match the whole string, then a metacharacter would be required to signal *don't* match the whole string ... functionality which is quite useful. My understanding, from the docs and from dim memories of using re.match() long ago, is that it will match on less than the full input string if the re pattern allows it (for instance, if the pattern *doesn't* end in '.*' or something similar.) Ending a pattern with '.*' or something similar is typically a mistake and does nothing but waste CPU cycles: C:\junkpython -mtimeit -simport re;s='a'+80*'z';m=re.compile('a').match m(s) 100 loops, best of 3: 1.12 usec per loop C:\junkpython -mtimeit -simport re;s='a'+8000*'z';m=re.compile('a').match m(s) 10 loops, best of 3: 1.15 usec per loop C:\junkpython -mtimeit -simport re;s='a'+80*'z';m=re.compile('a.*').match m(s) 10 loops, best of 3: 1.39 usec per loop C:\junkpython -mtimeit -simport re;s='a'+8000*'z';m=re.compile('a.*').match m(s) 1 loops, best of 3: 24.2 usec per loop The regex engine can't optimise it away because '.' means by default any character except a newline , so it has to trundle all the way to the end just in case there's a newline lurking somewhere. Oh and just in case you were wondering: C:\junkpython -mtimeit -simport re;s='a'+8000*'z';m=re.compile('a.*',re.DOTALL).match m(s) 100 loops, best of 3: 1.18 usec per loop In this case, logic says the '.*' will match anything, so it can stop immediately. I'd test this, though, before trusting it. What the heck, I'll do that now: import re re.match('ab', 'abcde') _sre.SRE_Match object at 0xb6ff8790 m = _ ??? What's wrong with _.group() ??? m.group() 'ab' print re.match('ab$', 'abcde') None HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: building an index for large text files for fast access
Yi Xing wrote: I need to read specific lines of huge text files. Each time, I know exactly which line(s) I want to read. readlines() or readline() in a loop is just too slow. Since different lines have different size, I cannot use seek(). So I am thinking of building an index for the file for fast access. Can anybody give me some tips on how to do this in Python? Thanks. Hey Yi, The standard library module 'libcache' does exactly what you're considering implementing. -alex23 -- http://mail.python.org/mailman/listinfo/python-list
Re: building an index for large text files for fast access
Yi Xing: Since different lines have different size, I cannot use seek(). So I am thinking of building an index for the file for fast access. Can anybody give me some tips on how to do this in Python? It depends on the size of the files and the amount of memory and disk you may use. First suggestion would be an in-memory array.array of 64 bit integers made from 2 'I' entries with each 64 bit integer pointing to the start of a set of n lines. Then to find a particular line number p you seek to a[p/n] and then read over p%n lines. The factor 'n' is adjusted to fit your data into memory. If this uses too much memory or scanning the file to build the index each time uses too much time then you can use an index file with the same layout instead. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: building an index for large text files for fast access
alex23 wrote: The standard library module 'libcache' does exactly what you're considering implementing. I believe the module you're referring to is `linecache`. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis It is from numberless diverse acts of courage and belief that human history is shaped. -- John F. Kennedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem
Dennis Lee Bieber wrote: On Mon, 24 Jul 2006 17:35:50 -0300, Gerhard Fiedler [EMAIL PROTECTED] declaimed the following in comp.lang.python: It is surprising in the sense that binding seems not to be necessary for read access. It does, I would agree, seem a little counter-intuitive that assignment (or binding) forces the name to be considered local. That's just one of Python's features. Binding is the process of attaching the LHS NAME to the OBJECT that is RHS result. Python does not use the mailbox model of variables. In the mailbox model (think of a post office sorting table, or the customer boxes in the lobby), each box has one, and only one, name. A = B means take the contents of box B, make a copy of those contents, leave the original contents in B, and put the copy into box A Python has what I refer to as the Post-It Note Model. A = B means find the box that has a post-it note with 'A' (if there isn't one, get a blank note and put 'A' on it), take that post-it note and move it to the box that already has a post-it note with 'B' . Notice that this means that THAT box (the object) NOW has TWO Post-It notes, each with a different name. I've never really understood the value of the Post-It analogy. Despite the fact that it allows you to explain that objects can have several names, it doesn't really help in explaining that the names themselves live in particular namespaces and have lifetimes largely independent of the objects to which they refer. It really seems easier (to me) to explain that names are references or pointers to values, and that the names live in scopes that can disappear (for example when a function or method returns). This also allows one to explain that a function can return references to (one or more) objects, and if those references are saved by the caller then the lifetime of the referenced object(s) can be longer than the lifetime of the namespace in which they were originally created. Lists/dictionaries/tuples, etc. complicate this a small bit. What you now have is the object (the box with the name of the list on it) having a lot of pieces of string -- each string is stuck to a post-it note with the final object. This is why A[1] = B is not a rebinding of A. It looks for the box with the post-it of A, then gets the second (0 is first) string and follows that string to the post-it it is stuck on... That end of the string is then moved to the post-it with the name B Well here I'd rather simply say that references can also be saved in container objects, with all the same implications as when they are saved in names. This is explained extremely well in Ascher and Lutz's Learning Python (at least in my first edition copy) using diagrams that make it obvious how objects are created and what their lifetimes are likely to be. All this business about Post-It notes and pieces of string seems artificial in the extreme, not to say a little unhelpful. Maybe I've just been programming too long ... Perhaps you'd like to try explaining argument passing in terms of Post-Its? That might be amusing ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: prob with struct and byte order
Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], nephish wrote: tohex gave me '53 54 58 S T X 00 00 00 34 Length!? Decimal 57. 3 * 16 + 4 - 52 where I come from -- assuming hex means hexadecimal and not witchcraft :-) 00 00 00 c8 Type!? Decimal 200. 70 69 76 6f 74 72 61 63 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74 72 61 63 31 70 69 76 6f 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Payload!? 45 4e 58' E N X this is the login message (message type 200) The problem I see is the length. The payload without STX, ENX and the two numbers in front is 47 bytes so there's a 5 byte difference. I don't think so. You have to look at some more messages to get an idea how the length corresponds to the actual payloads length. Yes, but not because of the 5-difference problem. The OP has favoured us with 3 messages (in 3 different formats), 2 x login and 1 of some sort of data. See below. 8--- script start import struct def unhex(s, spaced): return ''.join([chr(int(s[x:x+2], 16)) for x in xrange(0, len(s), 2 + spaced)]) # gasp hex1 = 535458002c00ea31373538343636383535d6090d54454e58 txt1 = unhex(hex1, 0) txt2 = 'STX\x00\x00\x004\x00\x00\x00\xc8stateman\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00state1man\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ENX' hex3 = '53 54 58 00 00 00 34 00 00 00 c8 70 69 76 6f 74 72 61 63 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74 72 61 63 31 70 69 76 6f 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 4e 58' txt3 = unhex(hex3, 1) for msgno, msg in enumerate((txt1, txt2, txt3)): print \nMessage %d: length of actual string is %d % (msgno + 1, len(msg)) print Has STX/ENX:, msg.startswith(STX) and msg.endswith(ENX) print repr:, repr(msg) print hex :, ' '.join([%02x % ord(x) for x in msg]) msg_len, msg_type = struct.unpack('II', msg[3:11]) print Internal len: %d; type: %d % (msg_len, msg_type) 8--- end script, start output Message 1: length of actual string is 54 Has STX/ENX: True repr: 'STX\x00\x00\x00,\x00\x00\x00\xea1758466855\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd6\t\rT\x00\x00\x00\x00ENX' hex : 53 54 58 00 00 00 2c 00 00 00 ea 31 37 35 38 34 36 36 38 35 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 d6 09 0d 54 00 00 00 00 45 4e 58 Internal len: 44; type: 234 Message 2: length of actual string is 61 Has STX/ENX: True repr: 'STX\x00\x00\x004\x00\x00\x00\xc8stateman\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00state1man\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ENX' hex : 53 54 58 00 00 00 34 00 00 00 c8 73 74 61 74 65 6d 61 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 73 74 61 74 65 31 6d 61 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 4e 58 Internal len: 52; type: 200 Message 3: length of actual string is 62 Has STX/ENX: True repr: 'STX\x00\x00\x004\x00\x00\x00\xc8pivotrac\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00trac1pivot\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ENX' hex : 53 54 58 00 00 00 34 00 00 00 c8 70 69 76 6f 74 72 61 63 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74 72 61 63 31 70 69 76 6f 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 4e 58 Internal len: 52; type: 200 8--- Messages 1 and 3 tend to indicate that external_len == internal_len + 10 ... maybe there's been a copy/paste problem somewhere along the line with message 2; perhaps the OP could check this. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Mr. Roboto wrote: Folks: I want to embark on a project to add Python (actually, wxPython or PythonWin) to a new Windows app I want to start writing soon. Essentially, I want to take VB6 (or pos Delphi) and construct the app framework/core functionality using one of those languages, then extend the app w/ Python, the same way one can extend the MS Office apps using VBA. The core Python docs provide the fundamental info one needs to get started. But, I've been looking for some pointers to articles/web pages that will bootstrap the effort, so I won't have to completely reinvent the wheel. So far, the c.l.p ngroup traffic (and the web in general) that speaks to this subject is apparently pretty sparse. Since I'm a one-man show, it would be helpful if anyone could offer pointers to sites/pages/books that address some of these issues: You almost certainly would regard a copy of Hammind and Robinson's Python Programming on Win32 as remarkable value for money. It's an axcellent book, and even has examples fo how you can make a VBA application scriptable in Python. If you are more interested in developing functionality that experimenting, buying that book would save to a huge amount of time. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: PySNMP Thread unsafe?
pysnmp has been designed to be MT-safe. Although, I've never used it in a MT app, so there may be a bug showing up when you do threading... At its simplest, I'd advise snooping on the wire to make sure you are querying different devices at the same time and also to see where the [I assume] bottleneck really is -- is it in a sending or receiving phase of the query. If you could show me the code that causes the trouble? [EMAIL PROTECTED] писал(а): I'm trying to monitor about 250 devices with SNMP, using PySNMP version 4. I use the threading.Thread to create a threadpool of 10 threads, so devices not responding won't slow down the monitoring process too much. Here comes my problem. When using PySNMP single threaded, every this goes well; but if I create 10 threads, it all goes awry... It seems PySNMP is not thread safe? Can anyone elaborate on this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Q: Class Privacy (or lack of)
Steve Jobless wrote: Hi, I just started learning Python. I went through most of the tutorial at python.org. But I noticed something weird. I'm not talking about the __private hack. Actually this is __ultra_private. For normal privacy, _private is enough !-) Let's say the class is defined as: class MyClass: def __init__(self): pass def func(self): return 123 But from the outside of the class my interpreter let me do: x = MyClass() x.instance_var_not_defined_in_the_class = 456 or even: x.func = 789 After x.func = 789, the function is totally shot. Obviously. But why would you do such a stupid thing ? OTOH, this let you customize func() for a given object or class. Which can be very helpful sometimes. Are these bugs or features? Features, definitively. If they are features, don't they create problems as the project gets larger? My experience is that with medium/large projects, this feature can actually help to solve a lot of problems in a much more simpler and straightforward way than with most mainstream languages. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: building an index for large text files for fast access
Erik Max Francis wrote: alex23 wrote: The standard library module 'libcache' does exactly what you're considering implementing. I believe the module you're referring to is `linecache`. and whatever its name is, it's not a goer: it reads the whole of each file into memory. It was designed for stack traces. See docs. See source code. See discussion when somebody with a name within a typo or 0 of the OP's asked an almost identical question very recently. Here's a thought: sqlite3 database, one table (line_number, file_offset, line_length), make line_number the primary key, Bob's yer uncle. Oh yeah, that battery's not included yet -- you'll need to download the pysqlite2 module, and mutter strange oaths: import sys PY_VERSION = sys.version_info[:2] if PY_VERSION = (2, 5): import sqlite3 else: from pysqlite2 import dbapi2 as sqlite3 It would be a very good idea for the OP to give us a clue as to (min/max/average) number of (bytes per line, lines per file, bytes per file) *and* the desired response time on what hardware OS ... *and* how long if takes to do this: for line in file_handle: pass Alternatively, if you have the disk space, you could have just two columns in the DB table: (line_number, line). Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
doctest with variable return value
Hi all, I am wondering what is the standard doctest (test) practice for functions who's returned value change all the time e.g. forex rate: import urllib def get_rate(symbol): get_rate(symbol) connects to yahoo finance to return the rate of symbol. get_rate('AUDEUR') url= http://finance.yahoo.com/d/quotes.csv?s=%s=Xf=sl1d1t1c1ohgve=.csv; % \ symbol f=urllib.urlopen(url) return float(f.readline().split(',')[1]) As you can guess I am very new to unittest and doctest in general ... Thanks for your help, EuGeNe -- http://mail.python.org/mailman/listinfo/python-list
Re: micro authoritative dns server
In message [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I just want to know if anyone could help me in writing a code for minimal authoritative dns server. You'll probably need to start by reading and understanding RFC1034 and RFC1035. -- http://mail.python.org/mailman/listinfo/python-list
Re: function v. method
(Apollogies to fuzzylollipop for replying to them rather than the list!)Python does have ALREADY have an OFFICAL mechanism for private members, prefix your names with _ or __. Both are ommited from autogenerateddocuementation and both are OFFICALLY not supposed to be used.Could you elaborate on that a little or point me in the right direction to read up on it? I'm currently re-writing a large lump of my coding and trying to use best practice. I thought it was considered good practice to make stuff private (in this case using __ ) that wasn't intened to be accessed from outside the function/class? Cheers for your help.Wesley Brooks. -- http://mail.python.org/mailman/listinfo/python-list
Any tips/comments on my code sample
Just wondering if anyone could give me advice on handling potential error conditions in python, it seems that exceptions are used alot more for this stuff than in other languages. I have provided a code sample giving an example of a first attempt at using them (in python anyway) and also I have given an example of using the logging module I intend to use to replace all the print statements... it seems hassle to set up, but I think logging can provide good flexibility. - just wondering if you could give comments on my use of exceptions and the logging module (and my code in general as i'm a relative newbie), and whether the logging module can handle the case where you have threaded code (handling file locking on the log files etc.) Cheers def Configure_Logging(): print configuring logging logger = logging.getLogger(CT_Deploy) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter(%(asctime)s - %(levelname)-8s - %(name)s - %(message)s) ch.setFormatter(formatter) logger.addHandler(ch) logger.debug(Logging configured) def Do_DB_Stuff(deplo_num): logger = logging.getLogger(CT_Deploy_logger.Do_DB_Stuff) sql_list = [alter table deplo_%s move tablespace MAP % deplo_num, create index deplo_%s_esz on deplo_%s(esz) tablespace cadidx % (deplo_num, deplo_num), analyze table deplo_%s estimate statistics for all columns % deplo_num] db_list = [db1, db2, db3, db4] for db in db_list: try: #connect_string = usr/[EMAIL PROTECTED] % db #conn = cx_Oracle.connect(connect_string) #cur = conn.cursor() print \n\nConnected to %s... % db except cx_Oracle.DatabaseError: print \n\nUnable to connect to %s % db continue try: try: for sql in sql_list: #cur.execute(sql % CT_deplo_num) print \tSuccess: executing '%s' against %s % (sql, db) except cx_Oracle.DatabaseError: print \tFailure: executing '%s' against %s % (sql, db) print \tROLLING BACK... conn.rollback() else: conn.commit() finally: cur.close() conn.close() def main(): Configure_Logging() deplo_num = raw_input(please enter deplo num...) Do_DB_Stuff(deplo_num) if __name__ == __main__: main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Grail not downloading
Dustan wrote: Does anybody know anything about Grail? I've been unable to get at it, and I've tried on both Windows and Macintosh machines. http://grail.sourceforge.net/ http://prdownloads.sourceforge.net/grail/grail-0.6.tgz?download -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest with variable return value
On Tuesday 25 July 2006 09:53, 3KWA wrote: Hi all, I am wondering what is the standard doctest (test) practice for functions who's returned value change all the time e.g. forex rate: import urllib def get_rate(symbol): get_rate(symbol) connects to yahoo finance to return the rate of symbol. get_rate('AUDEUR') url= http://finance.yahoo.com/d/quotes.csv?s=%s=Xf=sl1d1t1c1ohgve=.csv; % \ symbol f=urllib.urlopen(url) return float(f.readline().split(',')[1]) As you can guess I am very new to unittest and doctest in general ... Thanks for your help, EuGeNe Hi EuGeNe, Pass it through a variable before returning a value. Here's how I would do it: import urllib2 def get_rate(symbol): URL='http://finance.yahoo.com/d/quotes.csv?s=AUDEUR=Xf=sl1d1t1c1ohgve=.csv' request_headers = { 'User-Agent': 'Linuxinclar/0.1' } request = urllib2.Request(URL, None, request_headers) response = urllib2.urlopen(request) STR = response.read() return STR.split(',')[1].strip() SYMB='AUDEUR' print SYMB,'=',get_rate(SYMB) Python rocks. That's be nice to indicate hour though (4th array element)... Best Regards, Rob Sinclar -- http://mail.python.org/mailman/listinfo/python-list
dicts vs classes
Hi all, I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? regards, Guyon Morée http://gumuz.looze.net -- http://mail.python.org/mailman/listinfo/python-list
csv file or sqlite ?
hi, I am programming a filter for websites. to check if an url is in the blacklist, i have used a csv file. i have try to use sqlite but it looks as fast as csv files. Can you tell me if sqlite is faster than csv files ? or not ? thanks ___ Découvrez un nouveau moyen de poser toutes vos questions quelque soit le sujet ! Yahoo! Questions/Réponses pour partager vos connaissances, vos opinions et vos expériences. http://fr.answers.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
In [EMAIL PROTECTED], Guyon Morée wrote: I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? If you really have a memory problem read the documentation about `__slots__`. But I would only consider this if `a lot of` is several 100k or millions of objects and the memory consumption really is a problem. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
Guyon Morée [EMAIL PROTECTED] writes: I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? I recommend you to measure the time and memory usage for the two alternatives. That could give you the answer you want. HTH -- Marco Wahl http://visenso.com -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
dict is already a classwhy another? Guyon Morée wrote: Hi all, I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? regards, Guyon Morée http://gumuz.looze.net -- http://mail.python.org/mailman/listinfo/python-list
When is Django going to...
support Oracle and MS SQL Server? I just realized that's gonna be a big blow for my case against RoR because we use both databases almost exclusively, we don't use any of Django supported database actually. I did a search and found that there was an Oracle support committed--but is it going to make it into any release any time soon? Thanks Ray -- http://mail.python.org/mailman/listinfo/python-list
Re: When is Django going to...
Ray wrote: support Oracle and MS SQL Server? I just realized that's gonna be a big blow for my case against RoR because we use both databases almost exclusively, we don't use any of Django supported database actually. I did a search and found that there was an Oracle support committed--but is it going to make it into any release any time soon? You'd probably get better answers on Django's mailing-list ? -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
upload a file
Dear all, could you give me an help ? I would to upload a file from web using Python. Is there a simple way to do this? I'm using the cgi module and python 2.3. The file to be uploaded is a text file. Thank you for all your suggestions, Ernesto - This mail sent through IMP: http://horde.org/imp/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I optimise this? [intended in good humour]
John Machin wrote: Markus wrote: You know you're guilty of early/over optimisation, when it's almost two in the morning and the file open in front of you reads as follows. The code you are about to read is real... Some of the variable names have been changed to protect the families of those involved. [-snip-] from timeit import Timer if __name__=='__main__': t = Timer('len(argv)==1','from sys import argv') print %f usec/pass % (100 * t.timeit(number=10)/10) t = Timer('argv[0]==argv[-1]','from sys import argv') print %f usec/pass % (100 * t.timeit(number=10)/10) Do you realise that the two expressions that you are comparing are not even equivalent, and moreover you ignored an expression that will be faster and equivalent (unless/until somebody decides on an optimisation like interning/sharing strings between/among sys.argv elements). Let me point out that len(argv) == 1 is the only one that will work if argv is []. ;) (took me a few seconds to realize I must put a smiley there) Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: csv file or sqlite ?
In [EMAIL PROTECTED], frevol nicolas wrote: I am programming a filter for websites. to check if an url is in the blacklist, i have used a csv file. i have try to use sqlite but it looks as fast as csv files. Can you tell me if sqlite is faster than csv files ? or not ? Depends on the number of records/lines and how you access them. If you have some kind of server and read the csv file into a set or dictionary and query this thousands of times, it's faster than querying a database the same amount of times. If you have really many items in that blacklist and just query a few of them per program run, say in a CGI script, then a database will become faster than linear searching through a csv file. Just try both and measure to know for sure. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: When is Django going to...
Bruno Desthuilliers wrote: Ray wrote: support Oracle and MS SQL Server? I just realized that's gonna be a big blow for my case against RoR because we use both databases almost exclusively, we don't use any of Django supported database actually. I did a search and found that there was an Oracle support committed--but is it going to make it into any release any time soon? You'd probably get better answers on Django's mailing-list ? Er, yes. That was silly of me. Thanks Bruno! Sorry everyone, Ray -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
I'm wondering about whether to use objects in this way or dictionaries for a program I'm writing at the moment. It seems to me that unless you need some of the functionality supplied with dictionaries (len(a), has_key, etc) then simple objects are a syntacticaly cleaner and more natural way to express yourself. Any objctions to this, or pitfalls? Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Baseball Stats
Hi, Below your solution ready to run. Put get_statistics () in a loop that feeds it the names from your file, makes an ouput file name from it and passes both 'statistics' and the ouput file name to file_statistics (). Cheers, Frederic - Original Message - From: [EMAIL PROTECTED] Newsgroups: comp.lang.python To: python-list@python.org Sent: Monday, July 24, 2006 5:48 PM Subject: Parsing Baseball Stats I would like to parse a couple of tables within an individual player's SHTML page. For example, I would like to get the Actual Pitching Statistics and the Translated Pitching Statistics portions of Babe Ruth page (http://www.baseballprospectus.com/dt/ruthba01.shtml) and store that info in a CSV file. Also, I would like to do this for numerous players whose IDs I have stored in a text file (e.g.: cobbty01, ruthba01, speaktr01, etc.). These IDs should change the URL to get the corresponding player's stats. Is this doable and if yes, how? I have only recently finished learning Python (used the book: How to Think Like a Computer Scientist: Learning with Python). Thanks for your help... -- http://mail.python.org/mailman/listinfo/python-list import SE, urllib Tag_Stripper = SE.SE ('~.*?~= ~[^]*~= ~[^]*~= ') CSV_Maker= SE.SE (' ~\s+~=(9) ') # SE is the hacker's Swiss army knife. You find it in the Cheese Shop. # It strips your tags and puts in the CSV separator and if you needed other # translations, it would do those too on two lines of code. # If you don't want tabs, define the CSV_Maker accordingly, putting # your separator in the place of '(9)': # CSV_Maker = SE.SE ('~\s+~=,') # Now it's a comma def get_statistics (name_of_player): statistics = { # Uncomment those you want # 'Actual Batting Statistics' : [], 'Actual Pitching Statistics' : [], # 'Advanced Batting Statistics': [], 'Advanced Pitching Statistics' : [], # 'Fielding Statistics as Center Fielder' : [], # 'Fielding Statistics as First Baseman' : [], # 'Fielding Statistics as Left Fielder': [], # 'Fielding Statistics as Pitcher' : [], # 'Fielding Statistics as Right Fielder' : [], # 'Statistics as DH/PH/Other' : [], # 'Translated Batting Statistics' : [], # 'Translated Pitching Statistics' : [], } url = 'http://www.baseballprospectus.com/dt/%s.shtml' % name_of_player htm_page = urllib.urlopen (url) htm_lines = htm_page.readlines () htm_page.close () current_list = None for line in htm_lines: text_line = Tag_Stripper (line).strip () if line.startswith ('h3'): if statistics.has_key (text_line): current_list = statistics [text_line] current_list.append (text_line) else: current_list = None else: if current_list != None: if text_line: current_list.append (CSV_Maker (text_line)) return statistics def show_statistics (statistics): for category in statistics: for record in statistics [category]: print record print def file_statistics (file_name, statistics): f = file (file_name, 'wa') for category in statistics: f.write ('%s\n' % category) for line in statistics [category][1:]: f.write ('%s\n' % line) f.close () -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Have you considered IronPython? This is of course only an option if you're prepared to code in VB.NET or C# instead of VB6 or Delphi, but it would provide seamless integratioon between your Python code and the rest of your app and would not require an external graphics library - although you would need to distribute the .NET and IronPython runtimes. Multiple-language and library integration is after all what .NET is all about. Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Steve: Thanx for reminding me. I have that book around here *someplace*. Never finished it, but will dig it out pronto. As you so aptly point out, I want to develop more than experiment and who better to learn from than the author of PyWin itself Steve Holden wrote: You almost certainly would regard a copy of Hammind and Robinson's Python Programming on Win32 as remarkable value for money. It's an axcellent book, and even has examples fo how you can make a VBA application scriptable in Python. If you are more interested in developing functionality that experimenting, buying that book would save to a huge amount of time. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Grail not downloading
SuperHik wrote: Dustan wrote: Does anybody know anything about Grail? I've been unable to get at it, and I've tried on both Windows and Macintosh machines. http://grail.sourceforge.net/ http://prdownloads.sourceforge.net/grail/grail-0.6.tgz?download Thanks. I'll try that as soon as I get on a Mac. -- http://mail.python.org/mailman/listinfo/python-list
Re: Grail not downloading
Martin v. Löwis wrote: Dustan wrote: Does anybody know anything about Grail? I've been unable to get at it, and I've tried on both Windows and Macintosh machines. http://grail.sourceforge.net/ The files just don't exist, physically, on the server (if you have an SF account, you can check this yourself). However, it appears that the source code is still available through CVS: http://grail.cvs.sourceforge.net/grail/grail/ Regards, Martin I appreciate the info. I couldn't exactly attempt to download the files manually, though. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Simon: Good idea, but I'm not yet .NET-compatible and can't handle that learning curve in addition to everything else. IronPython is an option I hadn't considered, but yours is a good idea for the next project Simon Hibbs wrote: Have you considered IronPython? This is of course only an option if you're prepared to code in VB.NET or C# instead of VB6 or Delphi, but it would provide seamless integratioon between your Python code and the rest of your app and would not require an external graphics library - although you would need to distribute the .NET and IronPython runtimes. -- http://mail.python.org/mailman/listinfo/python-list
Stack trace in C
Bear with me - I am new to Python. (And redirect me to a more suitable newsgroup in case this one is not appropriate.) I am trying to embed Python into a C++ application and want to get back a backtrace in case of errors in the python code. This works well with e.g. import sys def u3(): xx() # raise an error def u2(): u3() def u1(): u2() def f(): try: u1() except NameError: type, value, tb = sys.exc_info() #f = tb.tb_frame #while f: # print f.f_lineno, f.f_code.co_name # f = f.f_back #print === while tb: f = tb.tb_frame print f.f_lineno, f.f_code.co_name tb = tb.tb_next def d1(): f() def d2(): d1() d2() on the python side. However, I want to do that on the C side. So far I have code similar to std::ostringstream msg; [...] #if 1 // Branch 1 PyObject * exc_type = 0; PyObject * exc_value = 0; PyObject * exc_traceback = 0; PyErr_Fetch(exc_type, exc_value, exc_traceback); PyObject * tb_frame = PyObject_GetAttrString(exc_traceback, tb_frame); #else // Branch 2 PyObject * pName = PyString_FromString(sys); PyObject * pModule = PyImport_Import(pName); PyObject * pFunc = PyObject_GetAttrString(pModule, exc_info); PyObject * pResult = PyObject_CallObject(pFunc, NULL); PyObject * tb_frame = PySequence_GetItem(pResult, 2); #endif while (tb_frame != Py_None) { PyObject * f_code = PyObject_GetAttrString(tb_frame, f_code); PyObject * f_lineno = PyObject_GetAttrString(tb_frame, f_lineno); int lineno = PyInt_AsLong(f_lineno); msg in line lineno \n; PyObject * tmp1 = PyObject_GetAttrString(tb_frame, f_back); PyObject * tmp2 = PyObject_GetAttrString(tb_frame, tb_next); // Now, neither tmp1 nor tmp2 is usable // tb_frame = tmpX; } } [Plus some reference counting/error checking code I left out] The 'Branch 1' version works for a sinmgle frame, but then tmp1 will be None and tmp2 0 at the end of the iteration and so no further frames are found. The 'Branch 2' version creates immediatly tb_frame as None and does not even enter the loop body once. So what am I doing wrong? How do I get the equivalent of the python code in C? Andre' -- http://mail.python.org/mailman/listinfo/python-list
Re: Stack trace in C
On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz [EMAIL PROTECTED] wrote: Bear with me - I am new to Python. (And redirect me to a more suitable newsgroup in case this one is not appropriate.) I am trying to embed Python into a C++ application and want to get back a backtrace in case of errors in the python code. I think you'd have more luck with the traceback module, which has such methods as format_exception and print_tb. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Missing rotor module
I'm in the midle of porting a python 1.5 application to 2.4 I just discovered that the rotor encryption module isn't part anymore of the 2.4 distribution. Is there a way to add this module to 2.4, or what would be the simplest way to replace this. The existing application makes use of the rotor module everywhere, which means in a lot of modules. Thanks for any ideas Rony -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
Carl J. Van Arsdall wrote: [...] My problem with the fact that python doesn't have some type of thread killer is that again, the only solution involves some type of polling loop. A polliing loop is neither required nor helpful here. [...] #Just pretend for the sake of arguement that 'op' actually means something and is a lengthy operation def func_to_thread(): os.system('op 1') os.system('op 2') os.system('op 3') What good do you think killing that thread would do? The process running 'op n' has no particular binding to the thread that called os.system(). If 'op n' hangs, it stays hung. The problem here is that os.system doesn't give you enough control. It doesn't have a timeout and doesn't give you a process ID or handle to the spawned process. Running os.system() in multiple threads strikes me as kind of whacked. Won't they all compete to read and write stdin/stdout simultaneously? #In order to make this killable with reasonable response time we have to organize each of our ops into a function or something equally annoying op_1(): os.system('op 1') op_2(): os.system('op 2') op_3(): os.system('op 3') opList(op_1, op_2, op_3) def to_thread(): for op in opList: checkMessageQueue() op() Nonsense. If op() hangs, you never get to checkMessageQueue(). Now suppose op has a timeout. We could write def opcheck(thing): result = op(thing) if result == there_was_a_timeout: raise some_timeout_exception How is: def func_to_thread(): opcheck('op 1') opcheck('op 2') opcheck('op 3') any less managable than your version of func_to_thread? So with this whole hey mr. nice thread, please die for me concept gets ugly quickly in complex situations and doesn't scale well at all. Furthermore, say you have a complex systems where users can write pluggable modules. IF a module gets stuck inside of some screwed up loop and is unable to poll for messages there's no way to kill the module without killing the whole system. Any of you guys thought of a way around this scenario? Threadicide would not solve the problems you actually have, and it tends to create other problems. What is the condition that makes you want to kill the thread? Make the victim thread respond to that condition itself. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing rotor module
rony steelandt [EMAIL PROTECTED] writes: Is there a way to add this module to 2.4, or what would be the simplest way to replace this. The existing application makes use of the rotor module everywhere, which means in a lot of modules. Thanks for any ideas It's still in the 1.5 distro and later ones up to maybe 2.2. You can probably just drop it into 2.4 and compile it. But you should migrate away from it if you were using it for anything serious. Its security sucks. -- http://mail.python.org/mailman/listinfo/python-list
How do I pass a list to a __init__ value/definition?
Let me start with my disclaimer by saying I'm new to computer programming and have doing it for the past three weeks. I may not be completely correct with all the jargon, so please bear with me. Anyways, I'm writing a function which has a class called MultipleRegression. I want one of the variables under the __init__ method to be a list. I've got: class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors and I want to be able to enter regressors as a list like MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1 gets passed to regressors and thus to self.regressors. Is there any simple way to fix this? Keep in mind that the length of the list may vary, so I can't just create a set number of variables and then mash them together into a list. Thanks so much! I really am getting into this whole programming thing. Its real challenging and very useful for my work. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
[EMAIL PROTECTED] writes: Threadicide would not solve the problems you actually have, and it tends to create other problems. What is the condition that makes you want to kill the thread? Make the victim thread respond to that condition itself. If the condition is a timeout, one way to notice it is with sigalarm, which raises an exception in the main thread. But then you need a way to make something happen in the remote thread. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors and I want to be able to enter regressors as a list like MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1 gets passed to regressors and thus to self.regressors. Really? class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors foo = MultipleRegression(42, [1,2,3,4], 5) print foo.regressors prints [1,2,3,4] Try it and see. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
On 25 Jul 2006 05:46:55 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Let me start with my disclaimer by saying I'm new to computer programming and have doing it for the past three weeks. I may not be completely correct with all the jargon, so please bear with me. Anyways, I'm writing a function which has a class called MultipleRegression. I want one of the variables under the __init__ method to be a list. I've got: class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors and I want to be able to enter regressors as a list like MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1 gets passed to regressors and thus to self.regressors. Is there any simple way to fix this? Keep in mind that the length of the list may vary, so I can't just create a set number of variables and then mash them together into a list. What you have works fine for me: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type help, copyright, credits or license for more information. class MultipleRegression: ...def __init__(self, dbh, regressors, fund): ...self.dbh = dbh ...self.regressors = regressors ... spam = MultipleRegression('dbh', [1,2,3,4], 5) spam.regressors [1, 2, 3, 4] What makes you think you only have the first member of the list? Can you show us the code that's not working? -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote: I've got: class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors and I want to be able to enter regressors as a list like MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1 gets passed to regressors and thus to self.regressors. Your problem lies elsewhere, as when I do exactly that, I get the correct results: mr = MultipleRegression(10, [1,2,3,4], 5) print mr.regressors [1, 2, 3, 4] So I think the way you are passing your list to MultipleRegression is perhaps wrong. I expect your problem is in creating that list in the first place from an unknown number of items. Basically you need to create the list, repeatedly add the necessary items to it until you're done, and then pass that to MultipleRegression. How to create and populate that list will depend on where you're getting the data from. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Stack trace in C
In article [EMAIL PROTECTED], Jean-Paul Calderone [EMAIL PROTECTED] wrote: On Tue, 25 Jul 2006 14:20:41 +0200, Andre Poenitz [EMAIL PROTECTED] wrote: Bear with me - I am new to Python. (And redirect me to a more suitable newsgroup in case this one is not appropriate.) I am trying to embed Python into a C++ application and want to get back a backtrace in case of errors in the python code. I think you'd have more luck with the traceback module, which has such methods as format_exception and print_tb. From C, PyErr_Print() is often handy (if only for debugging). Just -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
You guys are right it is getting passed initially. I checked in by printing the self.regressors in the class and it gives the list. But I get the error: TypeError: iteration over non-sequence for def Regress(self): print self.regressors for reg in self.regressors: index = HedgeFund(self.dbh, reg) indexTS[reg] = FundReturnSeries(dbh,index, sd, ed) indexNames[reg] = index.Name() header.append(index.Name()) header.append(t-statistic) header.append(r-squared) fh_csv.writerow(header) and when I print self.regressors here it only gives me the first number in the list. This bit of code is directly below the __init__ method. Any ideas what I'm doing wrong? Thanks for the quick response so far. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
On 25 Jul 2006 05:51:47 -0700, Paul Rubin http://phr.cx@nospam.invalid wrote: [EMAIL PROTECTED] writes: Threadicide would not solve the problems you actually have, and it tends to create other problems. What is the condition that makes you want to kill the thread? Make the victim thread respond to that condition itself. If the condition is a timeout, one way to notice it is with sigalarm, which raises an exception in the main thread. But then you need a way to make something happen in the remote thread. Raising an exception in your own thread is pretty trivial. SIGALRM does no good whatsoever here. :) Besides, CPython will only raise exceptions between opcodes. If a misbehaving thread hangs inside an opcode, you'll never see the exception from SIGALRM. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote: Let me start with my disclaimer by saying I'm new to computer programming and have doing it for the past three weeks. I may not be completely correct with all the jargon, so please bear with me. Anyways, I'm writing a function which has a class ot While legal (in Python) and sometimes handy, it's somewhat uncommon to define classes in functions. Perhaps a problem with jargon ?-) /ot called MultipleRegression. I want one of the variables under the __init__ method to be a list. Then pass in a list. I've got: class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors and I want to be able to enter regressors as a list like MultipleRegression(dbh, [1,2,3,4], 5). But when I do this only the 1 gets passed to regressors and thus to self.regressors. Using your code (copy-pasted for the class definition), I get this result: m = MultipleRegression('dbh', [1,2,3,4], 5) m.regressors [1, 2, 3, 4] Looks like you didn't send the real minimal code sample exposing the problem. FWIW, one possible cause would be misunderstanding of the concept of 'reference', ie : regressors = [1, 2, 3, 4] m1 = MultipleRegression('dbh', regressors, 5) m1.regressors [1, 2, 3, 4] regressors.append(42) m1.regressors [1, 2, 3, 4, 42] If this happens to be your real problem, you can solve it by storing a *copy* of the regressors list. Depending on what you really store in 'regressors', you'll need a simple copy or a deep copy: 1/ simple copy, suitable if regressors list items are immutable (numerics, strings, tuples, ...) or if it's ok to have references to (not copies of) these items: class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = regressors[:] # makes a copy of the list 2/ deep copy, in case you need it (but read the Fine Manual before...): import copy class MultipleRegression: def __init__(self, dbh, regressors, fund): self.dbh = dbh self.regressors = copy.deepcopy(regressors) I really am getting into this whole programming thing. Its real challenging and very useful for my work. Welcome onboard !-) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
Dennis Lee Bieber wrote: On Mon, 24 Jul 2006 10:27:08 -0700, Carl J. Van Arsdall My problem with the fact that python doesn't have some type of thread killer is that again, the only solution involves some type of polling loop. I.e. if your thread of execution can be written so that it And that is because the control of a thread, once started, is dependent upon the underlying OS... No; it's because killing a thread from another thread fundamentally sloppy. The process of creating a thread can be translated into something supplied by pretty much all operating systems: an Amiga task, posix thread, etc. But ending a thread is then also dependent upon the OS -- and not all OSs have a way to do that that doesn't run the risk of leaking memory, leaving things locked, etc. until the next reboot. No operating system has a good way to do it, at least not for the kind of threads Python offers. The procedure for M$ Windows to end a task basically comes down to send the task a 'close window' event; if that doesn't work, escalate... until in the end it throw its hands up and says -- go ahead and leave memory in a mess, just stop running that thread. The right procedure in MS Windows is the same as under POSIX: let the thread terminate on its own. module without killing the whole system. Any of you guys thought of a way around this scenario? Ask Bill Gates... The problem is part of the OS. Or learn how to use threads properly. Linux is starting to get good threading. Win32 has had it for quite a while. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote: You guys are right it is getting passed initially. I checked in by printing the self.regressors in the class and it gives the list. But I get the error: TypeError: iteration over non-sequence for def Regress(self): ot the usual Python coding style is to use either all_lowercase (preferably) or mixedCase names for functions/methods names /ot print self.regressors for reg in self.regressors: index = HedgeFund(self.dbh, reg) indexTS[reg] = FundReturnSeries(dbh,index, sd, ed) Names 'sd' and 'ed' are undefined. indexNames[reg] = index.Name() header.append(index.Name()) header.append(t-statistic) header.append(r-squared) fh_csv.writerow(header) and when I print self.regressors here it only gives me the first number in the list. This bit of code is directly below the __init__ method. Any ideas what I'm doing wrong? Sorry, I lack the needed psychic powers to find a bug in a code I can't see !-) Some wild guesses: * you overwrite self.regressors somewhere else * there's at least one case where you instanciate MultipleRegression with someting that is not iterable. FWIW, always try to reduce code to the minimal runnable snippet exhibiting the problem, so others have a chance to help you. As a side-effect, one very often finds the problem while doing so !-) HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
Bruno may be right. At some point I've got del self.regressors[fundNumber] which eliminates one of the variables in the list. I guess I figured it would be alright because I thought the program would run in a linear fashion (aside from loops, etc). I use the list in the code above where I delete the variable. Its weird because the deletion is under an if that only occurs if the Regress method runs correctly. Somehow it seems to anticipate the deletion of the variable before it occurs. Its a bit like quantum mechanics? -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem
On 2006-07-25 04:06:24, Steve Holden wrote: Dennis Lee Bieber wrote: On Mon, 24 Jul 2006 17:35:50 -0300, Gerhard Fiedler [EMAIL PROTECTED] declaimed the following in comp.lang.python: It is surprising in the sense that binding seems not to be necessary for read access. It does, I would agree, seem a little counter-intuitive that assignment (or binding) forces the name to be considered local. That's just one of Python's features. Ok... I can live with that, and thanks for the confirmation that it's not only me to feel that this is somewhat surprising :) Surprising for me are actually two things: 1- the fact itself, and 2- that term binding, and that whatever it means (I'll have to read more on that, now that I know the term) is different for read-only and read/write access. Neither the Post-It note metaphor nor the pointer explanation address that. Using the Post-It note metaphor, I'm asking myself why the label doesn't get attached to a different box when reading, but only when writing. (Just one of Python's features, I know :) Same thing with the pointer explanation: AFAIK, no language that uses pointers explicitly does something similar (that is, the storage the pointer points to is different depending on whether the pointer gets used for writing and reading, or only for reading). Thanks, Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: function v. method
On 2006-07-25 05:16:04, Wesley Brooks wrote: prefix your names with _ or __. Both are ommited from autogenerated docuementation and both are OFFICALLY not supposed to be used. Could you elaborate on that a little or point me in the right direction to read up on it? I'm currently re-writing a large lump of my coding and trying to use best practice. I thought it was considered good practice to make stuff private (in this case using __ ) that wasn't intened to be accessed from outside the function/class? I think fuzzylollipop meant that such members should not be used from the outside of the class; that is, they should be considered implementation, not API. (Which is why apparently autogenerated docs leave them out.) Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
FWIW, always try to reduce code to the minimal runnable snippet exhibiting the problem, so others have a chance to help you. As a side-effect, one very often finds the problem while doing so !-) Sorry I can't post to much of the code. Some of what I'm using is grabbing infromation off of our internal database, and for compliance reasons I can't print enough code so that it would actually run. Thanks for you help anyways, I'll try and figure out what I can. If necessary I'll retool the whole thing -- http://mail.python.org/mailman/listinfo/python-list
local moduile acess from cgi-bin
hello all. I do some coding in python but this is my first attampt to write somthing for hte web. I need to write a cgi-bin script for a web-server, and i've got the access for it from our SYSTEM. the problem is that this script uses some modules (pg, pyLab) that i've installed localy in my home dir. Python knows how to find them due to an enviorment variable inthe shell (please corrent me if i'm wrong). now, i am by no means big expert about web servers, but if i got it right, the web server run under some user (www-data or such). so howi can i make this user (and the web) be able to run my python code without having to install the modules as shared. (which i dont think they will allow me). thanks very much amit -- http://mail.python.org/mailman/listinfo/python-list
Paste text across multiple text boxes
I've written a python program that analyzes some data. However, I would like to make it easier to input data from the user. Currently, I have nine text boxes arranged vertically, and the user types a number into each of the boxes. This can be a little tedious, so I've envisioned a way speed up the process. I would like the user to be able to copy a vertical list of data (from excel or notepad) and paste it into the first textbox on my program. When they do this, I want each number to go into its respective box (the first number into the first box, and so on). I'm using wx.TextCtrl boxes, but haven't been able to find a way to do this. Is there a way to intercept the pasted data so I can control how it goes into my text boxes? Or is there another way to make this work? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote: FWIW, always try to reduce code to the minimal runnable snippet exhibiting the problem, so others have a chance to help you. As a side-effect, one very often finds the problem while doing so !-) Sorry I can't post to much of the code. Some of what I'm using is grabbing infromation off of our internal database, and for compliance reasons I can't print enough code so that it would actually run. Reducing to the minimal runnable snippet exhibiting the problem actually implies not depending on any DB or whatever. Nothing prevents you from replacing these parts with mock objects returning dummy data. And this is exactly why this process very often reveals the problem... Thanks for you help anyways, I'll try and figure out what I can. If necessary I'll retool the whole thing -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I pass a list to a __init__ value/definition?
[EMAIL PROTECTED] wrote: Bruno may be right. At some point I've got del self.regressors[fundNumber] oops... You're probably in for troubles with this: l = [1, 2, 3, 4] del l[1] l [1, 3, 4] del l[1] l [1, 4] del l[1] l [1] del l[1] Traceback (most recent call last): File stdin, line 1, in ? IndexError: list assignment index out of range You perhaps want a dict instead: l = [1, 2, 3, 4] d = dict(zip(l, l)) d {1: 1, 2: 2, 3: 3, 4: 4} del l[1] l [1, 3, 4] d {1: 1, 2: 2, 3: 3, 4: 4} del d[1] d {2: 2, 3: 3, 4: 4} del d[1] Traceback (most recent call last): File stdin, line 1, in ? KeyError: 1 del d[4] d {2: 2, 3: 3} which eliminates one of the variables in the list. This *won't* turn the list into an integer: l = [1, 2, 3, 4] while l: ... del l[0] ... l [] for item in l: print item ... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: local moduile acess from cgi-bin
noro wrote: hello all. I do some coding in python but this is my first attampt to write somthing for hte web. I need to write a cgi-bin script for a web-server, and i've got the access for it from our SYSTEM. the problem is that this script uses some modules (pg, pyLab) that i've installed localy in my home dir. Python knows how to find them due to an enviorment variable inthe shell (please corrent me if i'm wrong). now, i am by no means big expert about web servers, but if i got it right, the web server run under some user (www-data or such). so howi can i make this user (and the web) be able to run my python code without having to install the modules as shared. (which i dont think they will allow me). import sys sys.path.append('/home/amir/wherever-your-modules-are') should do the trick. HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: prob with struct and byte order
ok. here is how i got a message in the first place. The data server developers released this one windows app that simulates a real app. In that it logs into the server and sends and receives commands. instead of putting in the data servers ip though, i put in the ip address of the linux box i am building this on. when a command got sent, i had a listening socket open that would receive the command from the simulation program and dump it into a mysql table. So far its worked becuase the same command works with the real server. But now, i have to learn how to contruct messages for real because of the control we want to have over the field units. i put this in def split_message(message): if not (message.startswith('STX') or message.endswith('ENX')): raise ValueError('missing start or end sequence') length, message_type = struct.unpack('II', message[3:11]) return length, message_type, message[11:-3] print 'length: %d\ntype: %d\n%r' % split_message(data) and this is what was in the txt file. ( i am using a text file for sys.stdout becuase my terminal app does not do copy and paste.) length: 52 type: 200 'stateman\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00stat1manet\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' i used the same snippit for a query message length: 44 type: 234 '1758466855\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd6\t\rT\x00\x00\x00\x00' now, the message type 234 is correct according to the docs. Here is what it has to say. query_ANSI: used to request information about a particular data system in the field unsigned long int messageType = 234; unsigned char primaryMIN(32); # this is the serial number of the unit unsigned long int ESN # serial number of the communicator unsigned long int userID thanks again guys.. i think we're getting closer. -sk John Machin wrote: Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], nephish wrote: tohex gave me '53 54 58 S T X 00 00 00 34 Length!? Decimal 57. 3 * 16 + 4 - 52 where I come from -- assuming hex means hexadecimal and not witchcraft :-) 00 00 00 c8 Type!? Decimal 200. 70 69 76 6f 74 72 61 63 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74 72 61 63 31 70 69 76 6f 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Payload!? 45 4e 58' E N X this is the login message (message type 200) The problem I see is the length. The payload without STX, ENX and the two numbers in front is 47 bytes so there's a 5 byte difference. I don't think so. You have to look at some more messages to get an idea how the length corresponds to the actual payloads length. Yes, but not because of the 5-difference problem. The OP has favoured us with 3 messages (in 3 different formats), 2 x login and 1 of some sort of data. See below. 8--- script start import struct def unhex(s, spaced): return ''.join([chr(int(s[x:x+2], 16)) for x in xrange(0, len(s), 2 + spaced)]) # gasp hex1 = 535458002c00ea31373538343636383535d6090d54454e58 txt1 = unhex(hex1, 0) txt2 = 'STX\x00\x00\x004\x00\x00\x00\xc8stateman\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00state1man\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ENX' hex3 = '53 54 58 00 00 00 34 00 00 00 c8 70 69 76 6f 74 72 61 63 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 74 72 61 63 31 70 69 76 6f 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 4e 58' txt3 = unhex(hex3, 1) for msgno, msg in enumerate((txt1, txt2, txt3)): print \nMessage %d: length of actual string is %d % (msgno + 1, len(msg)) print Has STX/ENX:, msg.startswith(STX) and msg.endswith(ENX) print repr:, repr(msg) print hex :, ' '.join([%02x % ord(x) for x in msg]) msg_len, msg_type = struct.unpack('II', msg[3:11]) print Internal len: %d; type: %d % (msg_len, msg_type) 8--- end script, start output Message 1: length of actual string is 54 Has STX/ENX: True repr: 'STX\x00\x00\x00,\x00\x00\x00\xea1758466855\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd6\t\rT\x00\x00\x00\x00ENX' hex : 53 54 58 00 00 00 2c 00 00 00 ea 31 37 35 38 34 36 36 38 35 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 d6 09 0d 54 00 00 00 00 45 4e 58 Internal len: 44; type: 234 Message 2: length of actual string is 61 Has STX/ENX: True repr: 'STX\x00\x00\x004\x00\x00\x00\xc8stateman\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00state1man\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ENX' hex : 53 54 58 00 00 00 34 00 00 00 c8 73 74 61 74 65 6d 61 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 73 74 61 74 65 31 6d 61 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 4e 58 Internal len: 52; type: 200 Message 3: length of actual
Re: json implementation
jon cashman [EMAIL PROTECTED] writes: Hi everyone, Is there a doc comparing different json implementation (example: python-json, simplejson)? Does anyone have a strong recommendation to make? Any problem/issue for a particular implementation? Thanks. - jon _ Is your PC infected? Get a FREE online computer virus scan from McAfee® Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 I don't know personally, but TurboGears uses json-py. https://sourceforge.net/projects/json-py/ -- Harry George PLM Engineering Architecture -- http://mail.python.org/mailman/listinfo/python-list
Re: Exercises for dive into python
On Mon, 2006-07-24 at 23:16 +0200, Tal Einat wrote: snip... I recently gave a Python crash-course in my company, and ran into the same problem. There are many good Python tutorials, manuals, references etc., most are accompannied by various code examples, but there are very few exercises. I had a hard time collecting and inventing a few good exercises, about 12 in all. There are probably some good exercises out there, but they seem to be relatviely hard to find. Maybe they should be collected and organized at Python.org? That sounds like an exelent idea. Maybe the way to structure it is my book/chapter. You probably meant by book/chapter. Well, that would be fine, but it's up to whoever wrote dive into Python to update it. I was actually suggesting a central repository for Python exercises, all in the public domain, so that they could be used by anyone learning or teaching Python (or programming in general). I don't think this is necessarily the case. I am fairly sure the problem is not the people writing books do not have a way of publishing the excesses, its just they have hot the time or inclination to do so. what I was suggesting was a wiki type site where exercises could be worked on collaboratively. The authors should not have a problem with this as it would add value to there work and make it more desirable. Ben I think building a large collection of good Python exercises could help both those teaching Python and those learning it. Also, gathering a set of Python exercises for those learning general programming concepts (variables, functions, object-oriented, etc.) could help spread the use of Python for teaching programming. snip... -- http://mail.python.org/mailman/listinfo/python-list
M2Crypto and general HTTPS help needed
Hi all. I'm trying to connect to an HTTPS server and fetch a page, and I can get that working fine by doing the following: from M2Crypto import Rand, SSL, m2urllib url = m2urllib.FancyURLopener() u = url.open('https://127.0.0.1') data = u.read() print data u.close() However, I'm trying to verify that the certificate on the server has the right CN on it, to validate that the site really is who it's supposed to be. However, for the life of me I can't figure this out. I've read through the documentation on M2Crypto (which is cryptic itself), and I know I'm still really stupid when it comes to Python, but I figured this would be a more obvious thing to do. Does anyone know how to do this, or suggest another package to use? Thanks! --Brian -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* Brian McCann K12USA.com, Cool Tools for Schools 1-877-225-0100 [EMAIL PROTECTED] blocked::mailto:[EMAIL PROTECTED] http://www.k12usa.com http://www.k12usa.com/ -- http://mail.python.org/mailman/listinfo/python-list
question: Python or Lua for rejuvenation of old PCs?
John, Saw your post athttp://mail.python.org/pipermail/python-list/2004-January/201290.html when I was googling to see if anyonemight have ported Python to Tandem. Wonder what the business case is for a project of porting Python to Tandem? We really could use a good scripting language on the beast. Anyway, "Hi" from a former ACI University-type instructor (I did the ACIU Prep class you founded). Regards, Chris Cowden West Direct, Inc 402-965-7093 -- http://mail.python.org/mailman/listinfo/python-list
Re: Paste text across multiple text boxes
This link seems to have some relevent code. http://lists.wxwidgets.org/archive/wxPython-users/msg07340.html Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Python and Boost.
Hi, I'm trying to call a C++ class from python. I've looked around and the solution would appear to be boost. I'm not sure but maybe I've downloaded and installed the entire boost library, when there is probably a separate tar ball for python / C++ integration. Can someone please point me to a tar ball for mac os x so that I can call my C++ class from Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Mr. Roboto wrote: Folks: I want to embark on a project to add Python (actually, wxPython or PythonWin) to a new Windows app I want to start writing soon. Essentially, I want to take VB6 (or pos Delphi) and construct the app framework/core functionality using one of those languages, then extend the app w/ Python, the same way one can extend the MS Office apps using VBA. The core Python docs provide the fundamental info one needs to get started. But, I've been looking for some pointers to articles/web pages that will bootstrap the effort, so I won't have to completely reinvent the wheel. So far, the c.l.p ngroup traffic (and the web in general) that speaks to this subject is apparently pretty sparse. Since I'm a one-man show, it would be helpful if anyone could offer pointers to sites/pages/books that address some of these issues: 1) To COM or not ? From an implementation standpoint, it seems worthwhile to build the host app as a series of COM objects, which could then be ref'd/manipulated via external Python code. Not sure if this makes sense from a performance-perspective, but I doubt the apps I'm thinking about (mostly desk accessory utils kinda, sorta) are going to be compute-intensive at all. 2) SWIG or not ? Have never used it, but know that SWIG has been ref'd many times in the ngroup as an tool for facilitating the use of Python as an embedded language. Is SWIG worth the effort for a relatively small (10 KLOC) app ? 3) Handling exceptions. I want to start from Day One with a sensible approach to debugging and testing both host objects and external scripts. 4) Deployment. Size (30 - 50MB for wxPython or PyWin alone) and a silent install of either pkg prior to installing the host app. Regardless of the conversation in this group, I plan to get started in the next few days. This is how I'm currently looking at the above issues: 1) COM: Yes, since COM seems like an easy fit w/o writing lotsa glue code because of built-in support via PyWin 2) SWIG: Not for a 1st cut, at least not to get one's feet wet, so to speak 3) Exceptions: No clue. Need to closely read Extending/Embedding Python for more guidance 4) Deployment: Bite the disk space bullet and use PyWin or wxPython as is Anyway, that's the beginning of the conversation. If you have any observations or suggestions, please feel free. Later...MR Do you have major performances issues ? why not write everything in Python/WxPython ? I used to write my applications in VB6 with python com objects ... and decided there was no gain there. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Stripped CSS Background Image Calls
Thanks Marc, Yes, there is a web framework, basically the CSS is used as the layout wrapper of the Python script. It is a include call within the Python script. -- http://mail.python.org/mailman/listinfo/python-list
Don't use __slots__! (was Re: dicts vs classes)
In article [EMAIL PROTECTED], Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: In [EMAIL PROTECTED], Guyon Morée wrote: I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a performance/memory usage point of view? If you really have a memory problem read the documentation about `__slots__`. But I would only consider this if `a lot of` is several 100k or millions of objects and the memory consumption really is a problem. Guido sez: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved popularity amongst the novices and apprentices, who should know better than to use this magic incantation casually. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Stripped CSS Background Image Calls
JenAsh wrote: Thanks Marc, Yes, there is a web framework, basically the CSS is used as the layout wrapper of the Python script. It is a include call within the Python script. Then first post to this framework's mailing list, or to the author. FWIW, there are few chances you get any useful answer on a unspecified web framework here. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
2 timers, doesnt work?
I am creating 2 timers inside a GUI, but it seems that only the one declared last (the second timer), gets triggered, but the first one doesnt. Here is the code for the timers: # main timer, which governs when the register watcher get updated self.mainTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.UpdateAll, self.mainTimer) self.mainTimer.Start(5, False) # graph timer, which governs when the graph gets updated self.grphTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.upGrphDisplay, self.grphTimer) self.grphTimer.Start(101, False) So in this case, only the upGrphDisplay method gets called, the UpdateAll function doesnt get called. Any clues as to why this is happening? thanks a lot! -- kiran -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
Simon Hibbs: It seems to me that unless you need some of the functionality supplied with dictionaries (len(a), has_key, etc) then simple objects are a syntacticaly cleaner and more natural way to express yourself. I'd say the opposite. Classes contain a dict of their attributes, etc. So if you don't need the functionality supplied by objects, then using simpler dictionaries is better. (But in the end the choice has to be made according to the specific situations). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
smtplib timeout
I am doing SMTP callbacks in a Python milter (http://pymilter.sourceforge.net) using the smtplib module. For some spammer MXes, it takes days (!) before smtplib.sendmail will return. Since the spammer connects to us every few seconds, this quickly leads to a problem :-) I need to set a timelimit for the operation of smtplib.sendmail. It has to be thread based, because pymilter uses libmilter which is thread based. There are some cookbook recipies which run a function in a new thread and call Thread.join(timeout). This doesn't help, because although the calling thread gets a nice timeout exception, the thread running the function continues to run. In fact, the problem is worse, because even more threads are created. -- Stuart D. Gathman [EMAIL PROTECTED] Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 Confutatis maledictis, flamis acribus addictis - background song for a Microsoft sponsored Where do you want to go from here? commercial. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't use __slots__! (was Re: dicts vs classes)
Aahz, citing Guido: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved I think I have used __slots__ just one time. Can you tell me some of of such bad side effects? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Python audio output switch
Guys: Hi there. Recently I'll have to write a quite interesting program in Python on a Linux box. What I need is a function which allows the user to 'switch' the audio output from an audio file/microphone/line in. I'm not quite familiar with Linux programming. I've checked some python media frameworks but still need some light. Does anybody have experience on this? Thanks in advance! Regards, Pan Xingzhi -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Phillipe: Actually, it's not performance of the core app that concerns me. I'm thinking more about UI/form *design* productivity. I've done a lot of Access work over the years and while the stand-alone VB form designer isn't quite as thorough, it's still one of the slickest out there. Unfortunately, there's no designer for PyWin and wxPython's XRC is nice but not in the same league as what can be done w/ Delphi or VB. Yes, I'm aware that wxWidgets has a real form designer, but that's yet another story, for another day. Making XRC into a more fully-featured tool (more on par w/ the aforementioned) is a way nice project unto itself, but not right now. However, the desk accessory I've mentioned is an excellent 1st step towards *possibly* doing something much bigger Philippe Martin wrote: Do you have major performances issues ? why not write everything in Python/WxPython ? I used to write my applications in VB6 with python com objects ... and decided there was no gain there. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: Paste text across multiple text boxes
Thanks! This will get me started. Simon Hibbs wrote: This link seems to have some relevent code. http://lists.wxwidgets.org/archive/wxPython-users/msg07340.html Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: dicts vs classes
Simon Hibbs wrote: I'm wondering about whether to use objects in this way or dictionaries for a program I'm writing at the moment. It seems to me that unless you need some of the functionality supplied with dictionaries (len(a), has_key, etc) then simple objects are a syntacticaly cleaner and more natural way to express yourself. Any objctions to this, or pitfalls? Simon Hibbs I'm not sure, but I think this should be the other way round: unless you need special behavior that dicts don't supply (methods) or you really want/need obj.attr notation, you're better off just using dicts, but Marco Wahl is right, if it really matters measure it. Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: micro authoritative dns server
Lawrence D'Oliveiro wrote: In message [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: I just want to know if anyone could help me in writing a code for minimal authoritative dns server. You'll probably need to start by reading and understanding RFC1034 and RFC1035. Yes. But these documents are low-level documents and implementation of that is terrible (I admire people who write code for low-level projects like http://www.dnspython.org/). I would like more high-level code: in principle, the programmer who writes his/her own dns should don't matter if the dns server has to pass certain RR or another, else he/she should matter in other high-level things For that, probably using dnspython, I wanted if anyone could show me the simplest high-level code for a authoritative dns server. DNS server that only answers to the request of hosts that programmer add to one list. Thanks, Xan. -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't use __slots__! (was Re: dicts vs classes)
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: Aahz, citing Guido: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved I think I have used __slots__ just one time. Can you tell me some of of such bad side effects? The main one is that inheritance becomes difficult to nearly-impossible. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem
Gerhard Fiedler wrote: On 2006-07-25 04:06:24, Steve Holden wrote: Dennis Lee Bieber wrote: On Mon, 24 Jul 2006 17:35:50 -0300, Gerhard Fiedler [EMAIL PROTECTED] declaimed the following in comp.lang.python: It is surprising in the sense that binding seems not to be necessary for read access. It does, I would agree, seem a little counter-intuitive that assignment (or binding) forces the name to be considered local. That's just one of Python's features. Ok... I can live with that, and thanks for the confirmation that it's not only me to feel that this is somewhat surprising :) Since Python has no local variable declaration, there must be a rule to distinguish local names from names living in the enclosing namespaces. The rule is: unless previously declared 'global' (ie module-level) with the appropriate statement, any name bound in the local namespace is local. If declared 'global', it has to exist in the global namespace. This was much more simple to understand when we didn't have nested functions - we mostly had global and local scope. Fact is that we now have nested functions, but still no statement equivalent to 'global' for parent namespaces - with the result that we cannot actually rebind parent's namespace names from within a nested function. But we are still free to modify any mutable object we can access, so the usual workaround for immutable objects is to wrap them in a mutable container (list, dict, etc): def outer(): def _inner(): outer_var[0] = 'dead' outer_var = ['parrot'] print before, outer_var = %s % outer_var _inner() print after, outer_var = %s % outer_var and before you say it: yes, it's a dirty hack. Surprising for me are actually two things: 1- the fact itself, and 2- that term binding, and that whatever it means (I'll have to read more on that, now that I know the term) a binding is the association of a name and a reference to an object in a given namespace. It's different from the common notion of variable, which is usually a symbolic name for a memory address storing a value (like a pointer to an object's address). is different for read-only and read/write access. What makes the difference is that binding a name to an object in a namespace creates the name in this namespace (unless the name as been declared global, cf above). With the result that, the name existing in the local namespace, it won't be looked up in enclosing namespaces. Neither the Post-It note metaphor nor the pointer explanation address that. Using the Post-It note metaphor, I'm asking myself why the label doesn't get attached to a different box when reading, The normal lookup rule for names is local namespace then enclosing namespaces until top-level (module, aka 'global'), then builtins. Else, you would have to declare as global any module / function / whatever name in each and every function. but only when writing. cf above and below. (Just one of Python's features, I know :) Same thing with the pointer explanation: AFAIK, no language that uses pointers explicitly does something similar (that is, the storage the pointer points to is different depending on whether the pointer gets used for writing and reading, or only for reading). In most languages, you have to explicitly declare local names one way or another. Python takes the opposite route : you have to explicitly declare global names. Since you don't declare local names, binding creates the name if it doesn't already exists in the local namespace. HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib timeout
[Stuart D. Gathman] I need to set a timelimit for the operation of smtplib.sendmail. It has to be thread based, because pymilter uses libmilter which is thread based. There are some cookbook recipies which run a function in a new thread and call Thread.join(timeout). This doesn't help, because although the calling thread gets a nice timeout exception, the thread running the function continues to run. In fact, the problem is worse, because even more threads are created. Have you tried setting a default socket timeout, which applies to all socket operations? Here is a code snippet which times out for server connections. Timeouts should also work for sending and receiving on sockets that are already open, i.e. should work for the smtplib.sendmail call. == import socket import smtplib dud_server = '192.168.1.1' timeout_value = 1.0 # seconds socket.setdefaulttimeout(timeout_value) print connecting to server: %s % dud_server try: connection = smtplib.SMTP(dud_server) except socket.timeout: print server timed out == HTH, -- alan kennedy -- email alan: http://xhaus.com/contact/alan -- http://mail.python.org/mailman/listinfo/python-list
Re: About Embedding PyWin or wxPython
Mr. Roboto wrote: Phillipe: Actually, it's not performance of the core app that concerns me. I'm thinking more about UI/form *design* productivity. I've done a lot of Access work over the years and while the stand-alone VB form designer isn't quite as thorough, it's still one of the slickest out there. Unfortunately, there's no designer for PyWin and wxPython's XRC is nice but not in the same league as what can be done w/ Delphi or VB. Yes, I'm aware that wxWidgets has a real form designer, but that's yet another story, for another day. Making XRC into a more fully-featured tool (more on par w/ the aforementioned) is a way nice project unto itself, but not right now. However, the desk accessory I've mentioned is an excellent 1st step towards *possibly* doing something much bigger Philippe Martin wrote: Do you have major performances issues ? why not write everything in Python/WxPython ? I used to write my applications in VB6 with python com objects ... and decided there was no gain there. Regards, Philippe I personally _really_ like wxDesigner (http://www.roebling.de/) and as under VB6, I always avoided having the tables filled for me (bound forms if I recall) I have not found my productivity go down ... but then again, I never was a VB expert. 1) As others have said, it is very easy to make a Python com object (thank you Mark!) - and as long as Windows keeps supporting COM 2) I chose the COM option 3) If your script does not handle exceptions, you'll have a fairly cryptic VB dialog box telling you about your python com object unhapiness - I find it more easy to handle the expections in the script 4) Yes it takes space - I have an application that uses Python, wxPython, Gadfly, pyserial, HTMLGen . and the whole thing takes 120M I used visual studio to buld a single install for everything- works well. The one open issue I have about wxPython in a com object is how the main event loop (in your core application) will react if a com object with GUI pops-up ... never tried it. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
[EMAIL PROTECTED] wrote: Carl J. Van Arsdall wrote: [...] My problem with the fact that python doesn't have some type of thread killer is that again, the only solution involves some type of polling loop. A polliing loop is neither required nor helpful here. [...] #Just pretend for the sake of arguement that 'op' actually means something and is a lengthy operation def func_to_thread(): os.system('op 1') os.system('op 2') os.system('op 3') What good do you think killing that thread would do? The process running 'op n' has no particular binding to the thread that called os.system(). If 'op n' hangs, it stays hung. The problem here is that os.system doesn't give you enough control. It doesn't have a timeout and doesn't give you a process ID or handle to the spawned process. Running os.system() in multiple threads strikes me as kind of whacked. Won't they all compete to read and write stdin/stdout simultaneously? Unfortunately this is due to the nature of the problem I am tasked with solving. I have a large computing farm, these os.system calls are often things like ssh that do work on locations remote from the initial python task. I suppose eventually I'll end up using a framework like twisted but, as with many projects, I got thrown into this thing and threading is where we ended up. So now there's the rush to make things work before we can really look at a proper solution. #In order to make this killable with reasonable response time we have to organize each of our ops into a function or something equally annoying op_1(): os.system('op 1') op_2(): os.system('op 2') op_3(): os.system('op 3') opList(op_1, op_2, op_3) def to_thread(): for op in opList: checkMessageQueue() op() Nonsense. If op() hangs, you never get to checkMessageQueue(). Yea, understood. At the same time, I can't use a timeout either, I don't know how long op_1 or op_2 will be. This is why I want something that is triggered on an event. Now suppose op has a timeout. We could write def opcheck(thing): result = op(thing) if result == there_was_a_timeout: raise some_timeout_exception How is: def func_to_thread(): opcheck('op 1') opcheck('op 2') opcheck('op 3') any less managable than your version of func_to_thread? Again, the problem I'm trying to solve doesn't work like this. I've been working on a framework to be run across a large number of distributed nodes (here's where you throw out the duh, use a distributed technology in my face). The thing is, I'm only writing the framework, the framework will work with modules, lots of them, which will be written by other people. Its going to be impossible to get people to write hundreds of modules that constantly check for status messages. So, if I want my thread to give itself up I have to tell it to give up. In order to tell it to give up I need some mechanism to check messages that is not going to piss off a large team of programmers. At the same time, do I really want to rely on other people to make things work? Not really, I'd much rather let my framework handle all control and not leave that up to programmers. So the problem is, I have something linearly executed a large list of python functions of various sizes ranging from short to long. Its not about killing the thread so much as how do I make the thread listen to control messages without polling. So with this whole hey mr. nice thread, please die for me concept gets ugly quickly in complex situations and doesn't scale well at all. Furthermore, say you have a complex systems where users can write pluggable modules. IF a module gets stuck inside of some screwed up loop and is unable to poll for messages there's no way to kill the module without killing the whole system. Any of you guys thought of a way around this scenario? Threadicide would not solve the problems you actually have, and it tends to create other problems. What is the condition that makes you want to kill the thread? Make the victim thread respond to that condition itself. I feel like this is something we've established multiple times. Yes, we want the thread to kill itself. Alright, now that we agree on that, what is the best way to do that. Right now people keep saying we must send the thread a message. That's fine and I completely understand that, but right now the only mechanism I see is some type of polling loop (or diving into the C API to force exceptions). So far I've not seen any other method though. If you want to send a thread a control message you must wait until that thread is able to check for a control message. If something hangs in your thread you are totally screwed, similarly, if your thread ends up in some excessively lengthy IO (IO that could be interrupted or whatever) you have to wait for that IO to
Re: How to force a thread to stop
On 2006-07-25 13:30:22, Carl J. Van Arsdall wrote: Running os.system() in multiple threads strikes me as kind of whacked. Won't they all compete to read and write stdin/stdout simultaneously? Unfortunately this is due to the nature of the problem I am tasked with solving. I have a large computing farm, these os.system calls are often things like ssh that do work on locations remote from the initial python task. [...] Again, the problem I'm trying to solve doesn't work like this. I've been working on a framework to be run across a large number of distributed nodes (here's where you throw out the duh, use a distributed technology in my face). The thing is, I'm only writing the framework, the framework will work with modules, lots of them, which will be written by other people. Its going to be impossible to get people to write hundreds of modules that constantly check for status messages. Doesn't this sound like a case for using processes instead of threads? Where you don't have control over the thread, you can use a process and get the separation you need to be able to kill this task. Alternatively you could possibly provide a base class for the threads that handles the things you need every thread to handle. They'd not have to write it then; they'd not even have to know too much about it. Gerhard -- http://mail.python.org/mailman/listinfo/python-list
simple question
I need to install Python Imaging Library (PIL) - imaging-1.1.5.tar.gz (source ) onto Suse Linux 10.1 system in order for (latest) Scribus 1.3.3.2 to install and work. Plesae indicate how I perform PIL install (exact commands/procedures) in manner where files are automatically placed in proper directories, etc. Your urgent assistance is appreciated. Thanks, Wendell Anderson [EMAIL PROTECTED] or [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
Gerhard Fiedler wrote: On 2006-07-25 13:30:22, Carl J. Van Arsdall wrote: Running os.system() in multiple threads strikes me as kind of whacked. Won't they all compete to read and write stdin/stdout simultaneously? Unfortunately this is due to the nature of the problem I am tasked with solving. I have a large computing farm, these os.system calls are often things like ssh that do work on locations remote from the initial python task. [...] Again, the problem I'm trying to solve doesn't work like this. I've been working on a framework to be run across a large number of distributed nodes (here's where you throw out the duh, use a distributed technology in my face). The thing is, I'm only writing the framework, the framework will work with modules, lots of them, which will be written by other people. Its going to be impossible to get people to write hundreds of modules that constantly check for status messages. Doesn't this sound like a case for using processes instead of threads? Where you don't have control over the thread, you can use a process and get the separation you need to be able to kill this task. Alternatively you could possibly provide a base class for the threads that handles the things you need every thread to handle. They'd not have to write it then; they'd not even have to know too much about it. Gerhard I'd be all for using processes but setting up communication between processes would be difficult wouldn't it? I mean, threads have shared memory so making sure all threads know the current system state is an easy thing. With processes wouldn't I have to setup some type of server/client design, where one process has the system state and then the other processes constantly probe the host when they need the current system state? -- Carl J. Van Arsdall [EMAIL PROTECTED] Build and Release MontaVista Software -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem
Dennis Lee Bieber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The names in the parameter list of the def statement are bound to the objects associated with the actual call. After that, they behave very much as locals... Now -- with defaults it gets a touch trickier... A function's parameters are not just 'very much as locals', they *are* locals. def f(x): print locals() f(3) {'x': 3} In particular, parameters are just those locals that are initialized in the call process; it is an error for a parameter name to not become bound to some object. The default objects fill in the slack when there are not enough argument objects. From the calling side, the arguments are objects to be used in that initial binding process, either directly or as part of a new collective object. It is an error for an argument to not be used. The calling code does not care about the parameter names, but just their number and nature. So one can think of calling as cross-namespace name binding followed by control transfer. Returning is similar except that return objects may ignored or bound to slots rather than names. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question
Maxine Weill wrote: I need to install Python Imaging Library (PIL) - imaging-1.1.5.tar.gz (source ) onto Suse Linux 10.1 system in order for (latest) Scribus 1.3.3.2 to install and work. Plesae indicate how I perform PIL install (exact commands/procedures) in manner where files are automatically placed in proper directories, etc. I though that PIL now used the standard setup system. If the package's top level directory includes a file called setup.py then just run python setup.py install and you should be good to go. please note, however, that you should really read the README about how to ensure you have support for JPEG and zlib. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Help in string.digits functions
John McMonagle wrote: On Mon, 2006-07-24 at 22:19 -0700, Anoop wrote: Hi All I am getting two different outputs when i do an operation using string.digits and test.isdigit(). Is there any difference between the two. I have given the sample program and the output Thanks for ur inputs Anoop #1: ~~ import string test='121206' if test not in string.digits: print I am Not Digit else: print I am Digit #2: ~~ import string test='121206' if not test.isdigit(): print I am Not Digit else: print I am Digit Output ~ #1:I am Not Digit #2:I am Digit Thnks and Rgds Anoop string.digits is the string constant '0123456789' So your test, if test not in string.digits: will evaluate True because '121206' is not in '0123456789'. Whereas test.isdigit() returns true if all the characters in test are digits. So yes, there is a big difference between the two. Regards, John Your first test could be rewritten to do what I think you're thinking it should do like so: import string test='121206' for ch in test: if ch not in string.digits: print I am not all Digits break else: print I am all Digits But isdigit() would be the better way. Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't use __slots__! (was Re: dicts vs classes)
Guido sez: __slots__ is a terrible hack with nasty, hard-to-fathom side effects that should only be used by programmers at grandmaster and wizard levels. Unfortunately it has gained an enormous undeserved popularity amongst the novices and apprentices, who should know better than to use this magic incantation casually. But, if they are novices, why should they be expected to know better? I just re-read http://docs.python.org/ref/slots.html#l2h-217 and don't see anyplace where it says, Warning: for use by wizards only. -- http://mail.python.org/mailman/listinfo/python-list
Re: print function question
Bertrand-Xavier M. wrote: On Tuesday 25 July 2006 05:52, Eric Bishop wrote: Why does this work: # start a = 5 print a, 'is the number' #end, prints out 5 is the number But not this: # start a = 5 print a 'is the number' #end, errors out The difference here is the comma seperating the variable and the string literal. Is the comma some sort of concatenation operator or is the comma necessary in some form of a requirement in the print function, i.e is the variable a an argument to print as well as 'is th number' another argument to print? Yes. It allows to concat several variables, and also adds a space. These do work as well: a = 5 print value is, a print value %s %(a) print value is, a, '...' Regards, Rob Also, a comma at the end of a print statement surpresses the usual trailing newline (it will cause a space to appear instead if you print something else, but NOT if you write directly to stdout.) print Hello, print world! # prints Hello world! on one line with a space between them, but import sys print Hello, sys.stdout.write(world!) # prints Helloworld! Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib timeout
On Tue, 25 Jul 2006 09:21:40 -0700, Alan Kennedy wrote: [Stuart D. Gathman] I need to set a timelimit for the operation of smtplib.sendmail. It has to be thread based, because pymilter uses libmilter which is thread based. Have you tried setting a default socket timeout, which applies to all socket operations? Does this apply to all threads, is it inherited when creating threads, or does each thread need to specify it separately? -- Stuart D. Gathman [EMAIL PROTECTED] Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 Confutatis maledictis, flamis acribus addictis - background song for a Microsoft sponsored Where do you want to go from here? commercial. -- http://mail.python.org/mailman/listinfo/python-list
Re: an urgent answer to a simple question
I need to install Python Imaging Library (PIL) - imaging-1.1.5.tar.gz (source ) onto Suse Linux 10.1 system in order for (latest) Scribus 1.3.3.2 to install and work. Not being a Suse user, I'm flying by the seat of my pants. My recommendation: Install debian, and use apt-get install python-imaging. One might even just do apt-get install scribus and it would find the PIL dependancy. You can poke in the .deb file and it will show you where everything goes. If, IIUC, Suse is an RPM-based distro, you can use http://rpmfind.net/linux/rpm2html/search.php?query=pil to find PIL, the way most folks would find RPM packages that don't come automatically with their distro. RPMs may be glorified tarballs as well, so you may be able to poke in them too. Or maybe Suse has some dependancy-tracker (I've hear the name of the program yum...might do dependancy checking?) where you can just point it at scribus, and it automatically finds PIL and installs it too. Plesae indicate how I perform PIL install (exact commands/procedures) in manner where files are automatically placed in proper directories, etc. Your urgent assistance is appreciated. Thanks, thanks for your post. Hopefully this helped. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: How to force a thread to stop
Carl J. Van Arsdall [EMAIL PROTECTED] writes: I'd be all for using processes but setting up communication between processes would be difficult wouldn't it? I mean, threads have shared memory so making sure all threads know the current system state is an easy thing. With processes wouldn't I have to setup some type of server/client design, where one process has the system state and then the other processes constantly probe the host when they need the current system state? -- http://poshmodule.sf.net might be of interest. -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question
Steve Holden schrieb: Maxine Weill wrote: I need to install Python Imaging Library (PIL) - imaging-1.1.5.tar.gz (source ) onto Suse Linux 10.1 system in order for (latest) Scribus 1.3.3.2 to install and work. Plesae indicate how I perform PIL install (exact commands/procedures) in manner where files are automatically placed in proper directories, etc. I though that PIL now used the standard setup system. If the package's top level directory includes a file called setup.py then just run python setup.py install if there are more versions of python installed and one wants to install for specific version then /pool/pathToMyInstalledSoftware/bin/python2.4 setup.py install /pool/pathToPetersInstalledSoftware/bin/python2.2 setup.py install this is what I figured out my 2 cents -- Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest with variable return value
3KWA wrote: I am wondering what is the standard doctest (test) practice for functions who's returned value change all the time e.g. forex rate: import urllib def get_rate(symbol): get_rate(symbol) connects to yahoo finance to return the rate of symbol. get_rate('AUDEUR') url= http://finance.yahoo.com/d/quotes.csv?s=%s=Xf=sl1d1t1c1ohgve=.csv; % \ symbol f=urllib.urlopen(url) return float(f.readline().split(',')[1]) You cannot test for an unknown value, but you can do some sanity checks: rate = get_rate('AUDEUR') rate 0 True isinstance(rate, float) True This will at least make sure that get_rate() does not throw an exception. You can also spoonfeed it with handcrafted data... def mock_urlopen(url): ... from cStringIO import StringIO ... return StringIO(yadda,0.1234) ... urllib.urlopen = mock_urlopen get_rate(AUDEUR) 0.1234 but this has the disadvantage that the test has to know about the actual implementation of the function about to be tested. Peter -- http://mail.python.org/mailman/listinfo/python-list