Re: reading from a txt file
you should have that file i/o in some try: except: pairs for starters. and you should close data_file when you are done. isn't it just data_file.read() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - threading
Thanks MyHaz, Now its oke :) thanks for that example -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best GUI toolkit in Python,Tkinter,wxPython,QT,GTK?
Undoubtably Wax :-) Easier to learn than TKinter, with none of the limitations (it's built on top of wxPython). See http://zephyfalcon.org I've just started using it and I'm really impressed. Best Regards, Fuzzy http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
Re: Secure scripts variables
Florian Lindner [EMAIL PROTECTED] writes: I have a script which is readable and executable by a user, but not writable. The users executes the scripts, it reads in a value and based on this value it computes a result and stores it in a variable. Can the user read out the value of this variable? If yes, can he be prevented to do so? I don't really understand the question. The user could, for example, run the Python interpreter under a debugger, and examine its internal state step by step during execution. What you really want is a setuid script. That can do what you want, but you have to write them very carefully. -- http://mail.python.org/mailman/listinfo/python-list
Re: IMAP4.search by message-id ?
Max M wrote: Sean Dodsworth wrote: Can anyone tell me how to get a message's number from the message-id using IMAP4.search? I've tried this: resp, items = server.search(None, 'HEADER', 'Message-id', msgID) but it gives me a 'bogus search criteria' error Why do you need the 'HEADER' Wouldn't this be enough? resp, items = server.search(None, 'Message-id', msgID) I am note shure if the msgId should be quoted. I assume not, as it will allways be an integer. Max, Thanks, but it didnt work. I still get the same error: error: SEARCH command error: BAD ['Bogus criteria list in SEARCH'] args = (SEARCH command error: BAD ['Bogus criteria list in SEARCH'],) I had originally included the HEADER field as per the RFC3501 documentation: HEADER field-name string also, the message-id is not an integer its a string like: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Doug Helm [EMAIL PROTECTED] wrote: Hey, Folks: I'm trying to write a very simple file upload CGI. I'm on a Windows server. I *am* using the -u switch to start Python for CGIs, as follows: c:\python\python.exe -u %s %s I *do* have write permissions on the directory I'm trying to write to. But, when I click submit, it just hangs. Any help would be greatly appreciated. Thanks. Here's the code... Upload.py import cgi print content-type: text/html\n\n I see you got your problem solved, but you should know there is a problem with this line. The print statement automatically adds an end-of-line, so this will actually end up producing TWO blank lines after the header. You should use this: print Content-type: text/html\n -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimisation Hints (dict processing and strings)
I posted a question about string concatination just last week. There is plenty of discussion on it, if you just search the group. -- http://mail.python.org/mailman/listinfo/python-list
Re: Things you shouldn't do
On Wed, 30 Mar 2005 07:02:57 GMT, Andrew Dalke [EMAIL PROTECTED] wrote: Steve wrote: [an anecdote on distinguishing l1 and 11] What are some of other people's favourite tips for avoiding bugs in the first place, as opposed to finding them once you know they are there? There's a good book on this topic - Writing Solid Code. And there's an excellent website showing what *not* to do: http://mindprod.com/unmain.html The OP's point is paragraph 11 in the Camouflage section. -- python -c 'print .join([chr(154 - ord(c)) for c in U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-])' -- http://mail.python.org/mailman/listinfo/python-list
Re: convert user input to Decimal objects using eval()?
[Julian Hernandez Gomez] is there a easy way to make eval() convert all floating numbers to Decimal objects and return a Decimal? [Raymond Hettinger] from decimal import Decimal import re number = re.compile(r((\b|(?=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d{1,3})?)) deciexpr = lambda s: number.sub(rDecimal('\1'), s) [Terry Reedy] This is less obvious and more useful, to me, than some of the recipies in the new Cookbook. Okay, we can fix that. I've cleaned it up a bit and posted it on ASPN with references, docs, and a doctest: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393265 Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Little Q: how to print a variable's name, not its value?
Ron_Adam wrote: I've been playing around with a way to explore name spaces, but once you drop into class's, and functions, the references can lead you into an endless loops. Here is a rough attempt at printing the names of a variable. It will pick up several names where appropriate, but deliberately doesn't attempt to get all possible names (as you say, that could result in endless loops). In particular, for the Fred=5/John=8/Winner=8 example it will only find one of John or Winner since it only picks at most one match from each dict or list. It doesn't yet manage to correctly lookup attributes (e.g. slots) when they aren't stored in a __dict__, nor does the output distinguish between dictionary keys and values (so encodings.cp437.encoding_map[8] below actually refers to the key not the value). If you want to track down a memory leak with this code save a weak reference to the variable you expect to be saved and then you may be able to work out why it hasn't been freed later on. I originally wrote a version of this code because I was having problems with xml.dom.ext.reader.HtmlLib (its parser holds onto the DOM from a C extension object which doesn't support garbage collection). In that situation you get variable 'names' beginning with '...' since there is no named variable to start from, but the attributes make it easier to track down which objects are involved and where the circular loops are. Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. Fred = 5 John = 8 Winner = John import varname for s in varname.object_info(Winner, False): ...print s ... sre_parse.ESCAPES['\\b'][1] tokenize.tok_name[8] token.tok_name[8] sre_parse.OPCODES['call'] sre_parse.FLAGS['m'] sre_parse.CHCODES['category_loc_word'] sre_parse.ATCODES['at_loc_boundary'] sre_constants.OPCODES['call'] sre_constants.CHCODES['category_loc_word'] sre_constants.ATCODES['at_loc_boundary'] sre_compile.OPCODES['call'] sre_compile.CHCODES['category_loc_word'] sre_compile.ATCODES['at_loc_boundary'] encodings.cp437.encoding_map[8] encodings.cp437.decoding_map[8] encodings.cp1252.encoding_map[8] encodings.cp1252.decoding_map[8] string.expandtabs[0] tokenize.RPAR token.RPAR stat.ST_MTIME sre_parse.SRE_FLAG_MULTILINE sre_constants.SRE_FLAG_MULTILINE sre_compile.SRE_FLAG_MULTILINE sre.M signal.SIGFPE re.M os.O_APPEND nt.O_APPEND inspect.CO_VARKEYWORDS imp.PY_CODERESOURCE gc.DEBUG_INSTANCES __main__.Winner class C: ... def foo(self): ...x = 'Hello '+'world' ...for s in varname.object_info(x): ...print s ... C().foo() __main__.C.foo()x -- varname.py import gc, inspect, types, operator def locate_keyorvalue(obj, container): if isinstance(container, dict): for k, v in container.iteritems(): if v is obj: return 'value', k if k is obj: return 'key', k else: for i, x in enumerate(container): if x is obj: return 'index', i return '???', '' def object_info(obj, anonymous=True): gc.collect() tree = {} ignored = {} def ignore(obj): ignored[id(obj)] = 1 def unignore(obj): del ignored[id(obj)] def safeshow(o): if isinstance(o, (list, dict)): return type(o) return o def buildTree(obj): '''Build a tree of referrers to obj such that tree[id(obj)] - list of referrers ''' ignore(inspect.currentframe()) objects = [obj] while objects: current = objects.pop() #print current, type(current), hex(id(current)) if isinstance(current, (types.ModuleType, )): refs = [] # Don't extend references to modules else: refs = [ o for o in gc.get_referrers(current) if not id(o) in ignored ] ignore(refs) tree[id(current)] = refs modules = [ r for r in refs if isinstance(r, (types.ModuleType,)) ] if modules: objects.extend(modules) tree[id(current)] = modules else: # Not yet found a path from a module for r in refs: if not id(r) in tree: objects.append(r) ignore(inspect.currentframe()) ignore(tree) buildTree(obj) def findPath(obj, ignore): '''Find a path from 'obj' back as far as it will go in the tree''' ignore[id(obj)] = 1 referrers = tree[id(obj)] if referrers: for t in referrers: if id(t) in ignore: yield ['...', t, obj] else: for path in findPath(t, ignore): yield path + [obj] else: yield [obj] del ignore[id(obj)] ignores = {}
Re: Queue.Queue-like class without the busy-wait
Op 2005-03-30, Paul Rubin schreef http: I think the best bet for the short term is handling it at the C level, with sigalarm. Another way is to have chained sigalarm handlers in the main thread. Possible, but I don't have the time to investigate that possibility now. Actually there's a simple and obvious approach: Linux and Windows both already implement semaphore objects with timeouts (see man semop under Linux). Other modern Unixes probably also have them. So I'd think it would be straightforward to just make a C module that wraps these semaphores with the C API. I'm not sure that this would be an acceptable approach. I did the man semop and it indicates this is part of system V IPC. This makes me fear that semaphores will use file descriptors or other resources that are only available in a limited amount. Not usefull if you are talking about thousands of threads. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem in designing a global directory in python
Tian wrote: I have tried using sysctx=None instead of global sysctx, but it doesn't work either. It seems my initialization work in the previous calling of init() has no persistent effect when utils is imported using from myproj.utils import getContext. What's weird, when a module is in the same directory as utils.py, where I can simply use utils for importing, there is no such problem. Any other suggestions? put the following print statement next to every global sysctx replacing ... with the function name where the statement is located. print ... globals are in %s % __name__ Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Queue.Queue-like class without the busy-wait
Antoon Pardon [EMAIL PROTECTED] writes: I'm not sure that this would be an acceptable approach. I did the man semop and it indicates this is part of system V IPC. This makes me fear that semaphores will use file descriptors or other resources that are only available in a limited amount. Not usefull if you are talking about thousands of threads. That would be terrible, if semaphores are as heavy as file descriptors. I'd like to hope the OS's are better designed than that. So, if we have to do this at user level, the two best choices seem to be either your pipe method, or an asynchronous sigalarm handler that goes and releases any timed out locks. The sigalarm method is conceptually cleaner, but it involves hacking C code, so it's not so easy. Plus I think using sigalarm results in more total system calls if there's lots of timeouts. I do believe that the current scheme with the slow-motion spinlocks is pretty revolting and that any of the alternatives we've discussed are better. I wonder what the Pypy folks are doing. It would be great if they have some general treatment of asynchronous exceptions. -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)
Ville Vainio wrote: The issue that really bothers me here is bloating the builtin space. We already have an uncomfortable amount of builtin functions. Of course the additions that have been suggested would not pollute the builtin namespace, but they would still be there, taking space. I'd rather see a more modular and 'slimmer' Python, what with the advent of Python for S60 and other embedded uses. Certainly a valid point. How would you feel about adding just a select few itertools functions, perhaps just islice, chain and tee? These functions provide the operations that exist for lists but don't, by default, exist for iterators: slicing, concatenation and copying. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakrefs to classes that derive from str
Ron Garret wrote: Note that you don't need the class redirection: py ref('') Traceback (most recent call last): File interactive input, line 1, in ? TypeError: cannot create weak reference to 'str' object But I don't know why strings aren't valid arguments to ref... None of the native types (int, float, list, tuple, etc.) can have weak references, but wrapping them in a class is supposed to get around that. And it does -- for all classes except str. Interesting. Is the wrapping thing documented somewhere? I didn't see it in the documentation for weakref.ref (though I have been known to be blind occasionally) ;) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils: package data
Qiangning Hong wrote: ehh.. I did a little more reading and found that this function can be easily done by the new distutils parameter package_data in 2.4. However, I am using python2.3 :( So, my question becomes: how to emulate the package_data function in python 2.3? There is distutils.sysconfig.get_python_lib() that works at least since 2.2: from distutils import sysconfig sysconfig.get_python_lib() '/usr/lib/python2.2/site-packages' from distutils import sysconfig sysconfig.get_python_lib() '/usr/lib64/python2.3/site-packages' from distutils import sysconfig sysconfig.get_python_lib() 'c:\\python24\\Lib\\site-packages' Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with tkinter
Pierre Quentel wrote: Instead of indexing self.lab by strings, you can index them by the attributes themselves : self.lab[self.i], and change line 23 into for var in (self.s, self,i) For your example, I wouldn't have used the text option in the definition of the labels, then textvariable in the callback method (procedi) ; I would have used only text and no IntVar or StringVar, just an integer and a string : class MiaApp: def __init__(self, genitore): self.mioGenitore = genitore self.i = 42 self.s = Baobab self.lab = {} self.lab[self.i] = Label(self.mioGenitore) self.lab[self.i].configure(width = 30, relief = RIDGE, text = [vuota]) self.lab[self.i].pack() self.lab[self.s] = Label(self.mioGenitore) self.lab[self.s].configure(width = 30, relief = RIDGE, text = [vuota]) self.lab[self.s].pack() self.but = Button(self.mioGenitore) self.but.configure(text = Vai!, command = self.procedi) self.but.pack() def procedi(self): for var in (self.i, self.s): self.lab[var].configure(text = var) Regards, Pierre hi pierre. i don't think this would not have worked as expected (by me). in my intentions, the text of the label must be slaved to a variable, so that it would change dynamically during the mainloop execution if another part of the code had chenged the content of the variable. maybe here is a more convincing example (the previous one was contrived too hastily i guess): 1 from Tkinter import * 2 3 class MiaApp: 4 def __init__(self, genitore): 5self.mioGenitore = genitore 6self.var = {0: 42, 1: Baobab} 7self.lab = {} 8self.lab[0] = Label(self.mioGenitore) 9self.lab[0].configure(width = 30, relief = RIDGE, 10 text = [vuota]) 11self.lab[0].pack() 12self.lab[1] = Label(self.mioGenitore) 13self.lab[1].configure(width = 30, relief = RIDGE, 14 text = [vuota]) 15self.lab[1].pack() 16self.but = Button(self.mioGenitore) 17self.but.configure(text = Vai!, command = self.procedi) 18self.but.pack() 19self.but2 = Button(self.mioGenitore) 20self.but2.configure(text = Torna!, command = self.procedi2) 21self.but2.pack() 22 def procedi(self): 23for var in self.lab.keys(): 24 self.lab[var].configure(text = self.var[var]) 25 def procedi2(self): 26self.var[0] = 24 27self.var[1] = Cactus 28 29 radice = Tk() 30 miaApp = MiaApp(radice) 31 radice.mainloop() in this example, when user presses Torna!, the labels are not updated as i expect; they only will be when user presses Vai! again (not what i want). thanks again macs -- http://mail.python.org/mailman/listinfo/python-list
RELEASED Python 2.4.1 (final)
On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.1 (final). Python 2.4.1 is a bug-fix release. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the bugs squished in this release. Python 2.4.1 should be a completely painless upgrade from Python 2.4 - no new features have been added. For more information on Python 2.4.1, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.1/ Highlights of this new release include: - Bug fixes. According to the release notes, several dozen bugs have been fixed, including a fix for the SimpleXMLRPCServer security issue (PSF-2005-001). Highlights of the previous major Python release (2.4) are available from the Python 2.4 page, at http://www.python.org/2.4/highlights.html Enjoy the new release, Anthony Anthony Baxter [EMAIL PROTECTED] Python Release Manager (on behalf of the entire python-dev team) pgpFIWVzNjUPQ.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with tkinter
Eric Brunel wrote: On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel [EMAIL PROTECTED] wrote: [...] mr brunel, i thank you for prompt reply. i will take my time to read it carefully. meanwhile, i inform you and the ng that someone else gave me a quick and dirty answer to my problem, namely subststuting line #24 like this: 24 self.lab[var].configure(textvariable = eval(var)) which seems to work as desired. thanks again bye macs -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimisation Hints (dict processing and strings)
OPQ wrote: - Try if it isn't faster to iterate using items instead of iterating over keys items are huge lists of numbers. keys are simple small strings. And even if it is faster, how can I find the key back, in order to delete it ? for v in hashh.items(): if len(v)2: del ??? To elaborate on the memory requirements of .keys () vs. items (): .keys () creates a new list of n objects. The objects are additional references to the existing keys. .items () creates also a new list of n objects. These objects are tuples of references, one to the key and one to the value. Only references are used so it doesn't matter how large the value actually is. Whether the tuples are created for the items () call or already exist depends on the implementation of the dictionary. Trying to infer this by using sys.getrefcount got me inconclusive results. I gonna try, but think that would be overkill: a whole list has to be computed ! Maybe whith genexps .. for key in (k for (k,v) in hash.iteritems() if len(v)2) Using only iterators has problems: for k,v in hash.iteritems (): if len (v) 2: del hash [k] You are changing hash while you iterate over it, this very often breaks the iterator. If you are memory bound, maybe a dabase like SQLite is really the way to go. Or you could write the keys to a remporary file in the loop and then write a second loop that reads the keys and deletes them from hash. Daniel -- http://mail.python.org/mailman/listinfo/python-list
twistedSnmp and hexadecimal values ...
Hi all ml. I'm tryng to use TwistedSnmp to make query and walk directly inside my python code. The problem i'm facing is that any time there is an hexadecimal value to be returned by the snmpwalk it is returened in a weird and useless way... does anyone had any (successfull) experience with twistedsnmp and hexadecimal values (as Mac Addresses)? thanks P -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best GUI toolkit in Python,Tkinter,wxPython,QT,GTK?
Fuzzyman wrote: Undoubtably Wax :-) Easier to learn than TKinter, with none of the limitations (it's built on top of wxPython). See http://zephyfalcon.org http://zephyrfalcon.org/labs/wax.html works better. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: oddness in string.find(sub,somestring)
MyHaz wrote: import string searched_string=abcdefg substring=123 print string.find(substring,searched_string) -1 searched_string= print string.find(substring,searched_string) 0 why would this be? And when is someone going to fix it :P I don't know. When are you going to fix it? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: oddness in string.find(sub,somestring)
thanks all that clears things up nicely - Haz -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best GUI toolkit in Python,Tkinter,wxPython,QT,GTK?
True enough :-) Thanks Fuzzy http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimisation Hints (dict processing and strings)
OPQ wrote: for (2): for k in hash.keys()[:]: # Note : Their may be a lot of keys here if len(hash[k])2: del hash[k] - use the dict.iter* methods to prevent building a list in memory. You shouldn't use these values directly to delete the entry as this could break the iterator: for key in [k for (k, v) in hash.iteritems () if len (v) 2]: del hash (key) I gonna try, but think that would be overkill: a whole list has to be computed ! Yes, but it is smaller than the list returned by hash.keys(), so it should be a win over what you were doing originally. Plus it avoids a lookup (hash[k]) which may improve the speed also. BTW I have long assumed that iterating key, value pairs of a dict using iteritems() is faster than iterating with keys() followed by a lookup, since the former method should be able to avoid actually hashing the key and looking it up. I finally wrote a test, and my assumption seems to be correct; using iteritems() is about 1/3 faster for simple keys. Here is a simple test: ## d = dict((i, i) for i in range(1)) def withItems(d): for k,v in d.iteritems(): pass def withKeys(d): for k in d: d[k] from timeit import Timer for fn in [withItems, withKeys]: name = fn.__name__ timer = Timer('%s(d)' % name, 'from __main__ import d, %s' % name) print name, timer.timeit(1000) ## I get withItems 0.980311184801 withKeys 1.37672944466 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: author index for Python Cookbook 2?
Premshree Pillai wrote: There's an index here: http://harvestman.freezope.org/cookbook/creds.html But dunno if all the recipes were finally included. Maybe somebody (Alex?) can confirm? [snip..] Well - my copy just arrived :-) Three of my recipes are in - but one has been merged with someone elses and improved beyond all recognition :-) Regards, Fuzzy http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
redundant imports
hi everybody. suppose that code-1.py imports code-2.py and code-3.py (because it uses names from both), and that code-2.py imports code-3.py. if python were c, code-1.c should only *include* code-2.c, because the latter in turns includes code-3.c. inclusion of modules in c is a purely preprocessing textual matter (compilation is deferred to after the fact), i guess, so that such things are possible. import of modules in python is a different beast, so the redundancy is (i think) necessary. any comment/suggestion/idea? bye macs -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with tkinter
Eric Brunel wrote: On Tue, 29 Mar 2005 22:32:59 +0200, Pierre Quentel [EMAIL PROTECTED] wrote: Instead of indexing self.lab by strings, you can index them by the attributes themselves : self.lab[self.i], and change line 23 into for var in (self.s, self,i) I really think this is asking for trouble: I suppose that the i and s attributes are meant to change at some point in the future, and you're mapping their *values* to the corresponding labels. So if the value changes, you won't be able to get the label again. For your example, I wouldn't have used the text option in the definition of the labels, then textvariable in the callback method (procedi) ; I would have used only text and no IntVar or StringVar, just an integer and a string : I would have done exactly the contrary, as it is far more easier to use. Using the textvariable option in Label's does not require you to remember the labels, but only the variables used to hold their contents. I'd also use two mappings: the first mapping a name to a Tkinter variable for the label variables, and the second for the values to give to these variables later. Here is my version of the class code: class MiaApp: def __init__(self, genitore): self.mioGenitore = genitore ## Mapping for variables self.variables = { i : StringVar(), s : StringVar() } ## Mapping for future variable values self.values = { i : 42, s : Baobab } ## Now, create the labels for var in self.variables.values(): ## Default text var.set([vuota]) ## Create label lb = Label(self.mioGenitore, width=30, relief=RIDGE, textvariable=var) lb.pack() ## The button is no more remembered in an attribute, as it does not seem to be needed but = Button(self.mioGenitore, text = Vai!, command = self.procedi) but.pack() def procedi(self): ## Just change the variable values for varName in self.variables.keys(): self.variables[varName].set(self.values[varName]) your technique is most interirting and clean, i must say. nevertheless, i cannot find a natural way to modularize it, in such a way that the machinery of the method might be isolated from the code that uses it. consider for example the following two programs: $ cat Miodialogo.py from Tkinter import * class MioDialogo(Toplevel): def __init__(self, genitore, chiamante): Toplevel.__init__(self, genitore) self.wm_title(Valori delle variabili) self.mioGenitore = genitore self.mioChiamante = chiamante self.fonteVar = (Helvetica, 14) self.quadro_grande = Frame(self) self.quadro_grande.pack(expand = YES, fill = BOTH) self.titolo = Label(self.quadro_grande) self.titolo.configure( text = Valori delle variabili:, width = 20, font = self.fonteVar ) self.titolo.pack(side = TOP, fill = X) def mostraVariabili(self, *argomenti): lung = 1 for i in argomenti: if len(i) lung: lung = len(i) self.dq = {} self.dn = {} self.dv = {} for i in argomenti: self.dq[i] = Frame(self.quadro_grande) self.dq[i].pack( side = TOP, anchor = W, fill = X ) self.dn[i] = Label(self.dq[i]) self.dn[i].configure( text = i + : , width = lung + 2, anchor = W ) self.dn[i].pack( side = LEFT ) self.dv[i] = Label(self.dq[i]) self.dv[i].configure( textvariable = eval(self.mioChiamante. + i), anchor = W ) self.dv[i].pack( side = LEFT, expand = YES, fill = X ) self.vaBene = Button(self.quadro_grande) self.vaBene.configure( text = Va Bene, command = self.pulsanteVaBenePremuto, default = ACTIVE ) self.vaBene.bind( Return, self.pulsanteVaBenePremuto_a ) self.vaBene.focus_force() self.vaBene.pack( side = BOTTOM, pady = 2 ) def pulsanteVaBenePremuto(self): self.destroy() self.mioChiamante.var.configure(state = NORMAL) def pulsanteVaBenePremuto_a(self, evento): self.pulsanteVaBenePremuto() $ cat spunta-4.py from Tkinter import * from Miodialogo import * class MiaApp: def __init__(self, genitore): self.mioGenitore = genitore self.fonte = (Helvetica, 12) self.quadro_grande = Frame(genitore) self.quadro_grande.pack(expand = YES, fill = BOTH) self.msg = Label(self.quadro_grande) self.msg.configure( font = self.fonte, wraplength = 10c, justify = LEFT, text = uSono qui sotto presentati tre pulsanti a spunta. \ Premendo un pulsante, se ne varia lo stato di selezione e si \ imposta una variabile a un valore che indica lo stato del \ pulsante stesso. Premendo il pulsante \u00ABMostra \ Variabili\u00BB si possono vedere i valori correnti delle \
ANN: pyMinGW support for Python 2.4.1 (final) is available
This is to inform those interested in compiling Python in MinGW that an updated version of pyMinGW is now available. Get it from here: http://jove.prohosting.com/iwave/ipython/pyMinGW.html Regards Khalid -- http://mail.python.org/mailman/listinfo/python-list
RE: Need Help: Server to pass py objects-THANKS
Thanks to all who responded. Although overwhelmed by the hits from a Google search initially, it looks like pyro is a good choice for my needs. -Original Message- From: Ken Godee [mailto:[EMAIL PROTECTED] Sent: Tuesday, March 29, 2005 3:45 PM To: python-list@python.org Subject: Re: Need Help: Server to pass py objects I have a legacy system with data stored in binary files on a remote server. I need to access and modify the content of those files from a webserver running on a different host. (All Linux) I would like to install a server on the legacy host that would use my python code to translate between the legacy files and Python Objects that represent the subset of data I care about, then pass those Python objects back and forth to my webserver, which would then manage the http I/F to various clients. My organization prefers to use open source software. Can anyone suggest some products to research further? Take a look here http://pyro.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakrefs to classes that derive from str
Steven Bethard wrote: Ron Garret wrote: None of the native types (int, float, list, tuple, etc.) can have weak references, but wrapping them in a class is supposed to get around that. And it does -- for all classes except str. Interesting. Is the wrapping thing documented somewhere? I didn't see it in the documentation for weakref.ref (though I have been known to be blind occasionally) ;) I believe it's here: http://docs.python.org/lib/module-weakref.html if you search for the string Not all and read the next two paragraphs. On the other hand, it says (there) only that several builtin types such as list and dict ... can add support through subclassing, and does not say anything about int, str, etc... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Suggesting methods with similar names
I have a class Surface with many methods. Working in the interactive window I receive an error like this when I write the wrong method name: table.addGlas() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'Surface' object has no attribute 'addGlas' Is it possibile to make the object give a better answer: a short list of few method names similar to the one I've misspelled? I've found some modules with phonetic algorithms like soundex, metaphone, etc, for example here: http://sourceforge.net/projects/advas/ I can produce the list of method names with this: toRemove = __delattr__ __dict__ __getattribute__ __module__ __new__ __reduce__ __copy__ __reduce_ex__ __setattr__ __slot__ __weakref__ __str__ __class__ __doc__.split() methods = sorted( set(dir(Surface)).difference(toRemove) ) The problem is calling the phonetic algorithm to show a ranked list of the 2-4 method names most similar to the wrong one called. I don't know if this problem requires a change in the python shell, or in the metaclass of that Surface class, etc. And in the end maybe this functionality (inspired by a similar Mathematica one) is already inside IPython :-] Bye, Bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: redundant imports
max(01)* wrote: hi everybody. suppose that code-1.py imports code-2.py and code-3.py (because it uses names from both), and that code-2.py imports code-3.py. if python were c, code-1.c should only *include* code-2.c, because the latter in turns includes code-3.c. inclusion of modules in c is a purely preprocessing textual matter (compilation is deferred to after the fact), i guess, so that such things are possible. import of modules in python is a different beast, so the redundancy is (i think) necessary. any comment/suggestion/idea? bye macs It's not as redundant as it looks. Once a module has been imported it goes into sys.modules and any subsequent imports refer to that original import, so the overhead of reading and parsing the file is only incurred once. As you're probably aware, Python also caches compilation results in *.pyc files; it will only compile the imported module if it changed since the last compilation. Check out the docs for the full skinny, in particular http://www.python.org/doc/2.4/ref/import.html HTH, Tim J -- Website: www DOT jarmania FULLSTOP com -- http://mail.python.org/mailman/listinfo/python-list
Re: redundant imports
max(01)* wrote: hi everybody. suppose that code-1.py imports code-2.py and code-3.py (because it uses names from both), and that code-2.py imports code-3.py. if python were c, code-1.c should only *include* code-2.c, because the latter in turns includes code-3.c. inclusion of modules in c is a purely preprocessing textual matter (compilation is deferred to after the fact), i guess, so that such things are possible. import of modules in python is a different beast, so the redundancy is (i think) necessary. any comment/suggestion/idea? You're mixed up about this whole idea. You say first that [code-1] uses names from both, which by definition means that it needs to import both. (I say by definition because import is *how* a module gets names from another module.) Then you say that code-1 can choose not to include code-3 because some other module is including it... but so what? That doesn't change the fact that code-1 needs names from code-3, and just because code-3 is imported elsewhere is no reason to think that code-1 magically gets its names too. Should all modules magically see all names in all modules which are imported, even by other modules? That would pretty much defeat most of the value of namespaces. Anyway, why this concern over so-called redundant imports? The source code itself is not parsed and compiled all over again, and even the .pyc file is not re-read... once any module has imported a module any other import just retrieves a reference to that module from the sys.modules dictionary, which is practically a free operation. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: global name Result is not defined
Elmar Haneke wrote: I do have an problem with Python and Capisuite. what's Capisuite? have you check the Capisuite site for support options? (mailing lists, etc). On calling one of the Capisuite functions I get an Exception global name 'Result' is not defined. Where to search for the problem? Including the *entire* traceback might help. /F -- http://mail.python.org/mailman/listinfo/python-list
Py2exe and dotNet Python
I downloaded PythonDotNet from the Zope site to my laptop. According to the docs I can use this with my regular Python installation. I copied CLR.dll and Python.Runtime.dll to my root folder (c:\\Python24). Doing this I was able to run the dotNet examples with no problems. When I tried to run py2exe on the scripts I received the following errors: --- The following modules appear to be missing: ['CLR.System.Drawing', 'CLR.System.Windows.Forms'] --- My setup.py script for py2exe looks like this: --- # setup.py from distutils.core import setup import py2exe setup(console=[helloform.py]) --- I run the setup like this: python setup.py py2exe. Is there anything else I need to do to get this converted into a *.exe file successfully? Thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: twistedSnmp and hexadecimal values ...
You really should give an example so that we will know what you mean by weird and useless. Otherwise you are asking us to implement TwistedSnmp to see what you are referring to. Larry Bates Francesco Ciocchetti wrote: Hi all ml. I'm tryng to use TwistedSnmp to make query and walk directly inside my python code. The problem i'm facing is that any time there is an hexadecimal value to be returned by the snmpwalk it is returened in a weird and useless way... does anyone had any (successfull) experience with twistedsnmp and hexadecimal values (as Mac Addresses)? thanks P -- http://mail.python.org/mailman/listinfo/python-list
Using something other than ';' to separate statements
I know I've seen this somewhere, but can't seem to google it. Is there a way to use an alternate statement separator, other than the default ';'? jw -- http://mail.python.org/mailman/listinfo/python-list
Impacket sequence numbers
Hello, I have been using Impacket to produce some packets, but unfortunatelly it does not provide functionality for changing the sequence number of a packet and leaves it to 0. Is it possible to cjange the sequense number in some way? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Things you shouldn't do
Steve [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] snip What are some of other people's favourite tips for avoiding bugs in the first place, as opposed to finding them once you know they are there? Fonts with slashed zeros and serifs. -Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: Secure scripts variables
Paul Rubin wrote: Florian Lindner [EMAIL PROTECTED] writes: I have a script which is readable and executable by a user, but not writable. The users executes the scripts, it reads in a value and based on this value it computes a result and stores it in a variable. Can the user read out the value of this variable? If yes, can he be prevented to do so? I don't really understand the question. The user could, for example, run the Python interpreter under a debugger, and examine its internal state step by step during execution. What you really want is a setuid script. That can do what you want, but you have to write them very carefully. AFAIK scripts can't be setuid? Can you tell me what you mean and how to do it? Florian -- http://mail.python.org/mailman/listinfo/python-list
(no subject)
#! rnews 1551 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George [EMAIL PROTECTED] Subject: Re: why and when we should do it? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: [EMAIL PROTECTED] User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 Lines: 43 Sender: [EMAIL PROTECTED] Organization: The Boeing Company References: [EMAIL PROTECTED] Mime-Version: 1.0 Date: Wed, 30 Mar 2005 14:16:34 GMT Xref: news.xs4all.nl comp.lang.python:369917 Su Wei [EMAIL PROTECTED] writes: hi,everybody,Sorry to bother you. i hvae seen some code like this before: class BusinessBO : dev __init__(slef): #write you own code here dev businessMethod : #write you own code here pass why and when we should add the keyword pass ? and some time i have seen class SomeObject(Object) : #some code why and when we should inherit Object? thanks in advanced. There are enough typos in your example that I'm guessing you actually saw: class BusinessBO : def __init__(self): #write you own code here pass def businessMethod(self): #write you own code here pass pass is the Python way to say Yes, I know there should be code here, but I don't want any. It is required in this context because a def cannot be totally empty. -- [EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
What I wanted it to know how to. Take a function like. Note replace ... with spaces. def makeAddr(tAdd): def add(tNum): return tNum + tAdd return add In a class so I make several functions that do the same thing but on diffrent objects. I ended up writing a base function and just wrapping it for all the cases. If there is a way to use this type of function to create class functions I would like to know how. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python interpreter error: unsupported operand type(s) for -: 'tuple' and 'int'
George Yoshida wrote: Rakesh wrote: To quote a much smaller trimmed-down example, here is how it looks like: ## --- # Entry Point to the whole program ## --- def main(): mylist = GenerateList() minnumber = min(mylist) for num in mylist: print num - minnumber ## TODO: Interpreter errors above. Try printing mylist. Then you'll know why - operand doesn't work. You're creating a nested tuple. I'd recommend changing the original script to something like:: seconds = [] [snip] # Convert the date format to the seconds since epoch for i in xrange( len(dates) ): thissecond = parseDate(dates[i][1]) seconds.append(thissecond) or if you want to stick with tuple:: seconds = () [snip] # Convert the date format to the seconds since epoch for i in xrange( len(dates) ): thissecond = parseDate(dates[i][1]) seconds += (thissecond, ) -- george Thanks. That fixed the problem. ## ## Generate a list ## def GenerateList(): array = [] for i in xrange(10): array.append(i) return array ## --- # Entry Point to the whole program ## --- def main(): mylist = GenerateList() minnumber = min(mylist) for num in mylist: print num - minnumber ## # Entry-point to the whole program ## main() This is how my revised code looks like -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
Also note I can't read or type is seems. what I want to know is how to take a function like. I realley need to fininsh my coke before I try to think. -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
See the following. -- Paul class X(object): pass def makeAddr(tAdd): def add(self, tNum): return tNum + tAdd return add # add methods to class X X.add1 = makeAddr(1) X.add100 = makeAddr(100) # create an X object x = X() # invoke new methods print x.add1( 50 ) print x.add100( 50 ) Prints: 51 150 -- http://mail.python.org/mailman/listinfo/python-list
Re: Things you shouldn't do
Here's another real world example, although it was in C: char* ptr; assert( ptr = malloc( memsize ); ) Of course, this worked when built in debug, but it took a while to track down why it wasn't working in the release build (the assert()'s were stripped out in the release builds, so ptr didn't allocate any memory). Unfortunately, the runtime failure happened in an entirely different part of the code, since ptr wasn't initialized to null, so this particular routine just merrily stomped on whatever memory address happened to initialize in ptr. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
Thanks I will try that. -- http://mail.python.org/mailman/listinfo/python-list
Re: twistedSnmp and hexadecimal values ...
Francesco Ciocchetti wrote: I'm tryng to use TwistedSnmp to make query and walk directly inside my python code. The problem i'm facing is that any time there is an hexadecimal value to be returned by the snmpwalk it is returened in a weird and useless way... does anyone had any (successfull) experience with twistedsnmp and hexadecimal values (as Mac Addresses)? TwistedSNMP returns the raw (binary) values as strings. Hexadecimal values are just human readable presentation logic for a binary value (stored as a string). For instance, for a MAC address, we currently display it to our users using: :.join([ '%02x'%(ord(v)) for v in mac ]) where mac is the weird and useful ;) value you got back. That will give you a colon-separated hexadecimal display value, which may or may not be exactly what you want. Feel free to play with the display logic to get what you feel to be a good display format. We (Cinemon) often use string sub-classes that provide extra formatting logic and apply those to the values when we get the data-values in, but that's just an artefact of how we store and process the results of the TwistedSNMP queries, not TwistedSNMP itself. BTW, more detail in a question (what result you got, what result you expected, what you did to get the result) is generally a good idea. HTH, Mike Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Want to meet any of these people? They are registered for PyCon
Steve Holden [EMAIL PROTECTED] wrote: Sorry you can't make it to Python. My even-naiver way of approaching the problem was to use the sort utility built into Cygwin, thereby avoiding writing any code at all. an easier way is to publish it unsorted, but claim it is sorted. someone is sure to correct it with the proper sorted list. Garry Hodgson, Technology Consultant, ATT Labs Be happy for this moment. This moment is your life. -- http://mail.python.org/mailman/listinfo/python-list
urllib problem (maybe bugs?)
Hi, I'm trying to fill the form on page http://www.cbs.dtu.dk/services/TMHMM/ using urllib. There are two peculiarities. First of all, I am filling in incorrect key/value pairs in the parameters on purpose because that's the only way I can get it to work.. For version I am suppose to leave it unchecked, having value of empty string. And for name outform I am suppose to assign it a value of -short. Instead, I left out outform all together and fill in -short for version. I discovered the method my accident. After I've done that it works fine for small SEQ values. Then, when I try to send large amount of data (1.4MB), it fails miserably with AttributeError exception. I highly suspect the two problems I have are the result of some bugs in the urllib module. Any suggestions? This is my code: fd = open('secretory0_1.txt', 'r') txt = fd.read() fd.close() params = urllib.urlencode({'SEQ': txt, 'configfile': '/usr/opt/www/pub/CBS/services/TMHMM-2.0/TMHMM2.cf', 'version': '-short'}) f = urllib.urlopen(http://www.cbs.dtu.dk/cgi-bin/nph-webface;, params) data = f.read() start = data.find('follow a href=h') + 16 end = data.find('This link/a') secondurl = data[start:end] f = urllib.urlopen(secondurl) print f.read() The value pairs I am suppose to fill in are: SEQ = some sequence here configfile = '/usr/opt/www/pub/CBS/services/TMHMM-2.0/TMHMM2.cf' version = '' outform = '-short' The exception I get when sending secretory0_1.txt is: C:\Documents and Settings\thw\python testhttp.py Traceback (most recent call last): File testhttp.py, line 11, in ? f = urllib.urlopen(http://www.cbs.dtu.dk/cgi-bin/nph-webface;, params) File C:\Python24\lib\urllib.py, line 79, in urlopen return opener.open(url, data) File C:\Python24\lib\urllib.py, line 182, in open return getattr(self, name)(url, data) File C:\Python24\lib\urllib.py, line 307, in open_http return self.http_error(url, fp, errcode, errmsg, headers, data) File C:\Python24\lib\urllib.py, line 322, in http_error return self.http_error_default(url, fp, errcode, errmsg, headers) File C:\Python24\lib\urllib.py, line 550, in http_error_default return addinfourl(fp, headers, http: + url) File C:\Python24\lib\urllib.py, line 836, in __init__ addbase.__init__(self, fp) File C:\Python24\lib\urllib.py, line 786, in __init__ self.read = self.fp.read AttributeError: 'NoneType' object has no attribute 'read' Timothy -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
Thanks that made it work. If I did it that way I think the other programmers on my team would kill me so I will stick with wrapping the function over and over again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting methods with similar names
[EMAIL PROTECTED] wrote: I have a class Surface with many methods. Working in the interactive window I receive an error like this when I write the wrong method name: table.addGlas() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'Surface' object has no attribute 'addGlas' Is it possibile to make the object give a better answer: a short list of few method names similar to the one I've misspelled? I've found some modules with phonetic algorithms like soundex, metaphone, etc, for example here: http://sourceforge.net/projects/advas/ I can produce the list of method names with this: toRemove = __delattr__ __dict__ __getattribute__ __module__ __new__ __reduce__ __copy__ __reduce_ex__ __setattr__ __slot__ __weakref__ __str__ __class__ __doc__.split() methods = sorted( set(dir(Surface)).difference(toRemove) ) The problem is calling the phonetic algorithm to show a ranked list of the 2-4 method names most similar to the wrong one called. I don't know if this problem requires a change in the python shell, or in the metaclass of that Surface class, etc. And in the end maybe this functionality (inspired by a similar Mathematica one) is already inside IPython :-] You could achieve this by overriding __getattribute__ (untested): def __getattribute__(self, name): try: object.__getattribute__(self, name) # or whatever is your superclass # or use super(), but I would have to lookup the syntax and # breakfast is waiting ;) except AttributeError: # find similar attributes suggestions = raise AttributeError('Surface' object has no attribute '%s'. Did you mean %s? % (name, suggestions)) I leave it to the experts to wrap this into a generic metaclass, decorator etc. ;) -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Want to meet any of these people? They are registered for PyCon
On Wed, 30 Mar 2005 14:42:52 GMT, rumours say that Garry Hodgson [EMAIL PROTECTED] might have written: Steve Holden [EMAIL PROTECTED] wrote: Sorry you can't make it to Python. My even-naiver way of approaching the problem was to use the sort utility built into Cygwin, thereby avoiding writing any code at all. an easier way is to publish it unsorted, but claim it is sorted. someone is sure to correct it with the proper sorted list. For parents, the other way is to forbid their children sorting the list. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils: package data
Qiangning Hong wrote: I am writing a setup.py for my package. I have a pre-compiled myextmod.pyd file in my package and I want the distutils to automatically copy it to C:\Python23\Lib\site-packages\mypackage\myextmod.pyd. I try to add the following parameter to setup(): data_file = [('mypackage', ['mypackage/myextmod.pyd'])], but it installs the pyd file to C:\Python23\mypackage\myextmod.pyd, this is not what I want. And I don't want to specify the path in data_file to the absolution path 'C:\Python23\Lib\site-packages\mypackage', for portability, of course. Any hints? Actually you probably want to look at describing the .pyd as an Extension. Then you can even give distutils the instructions to build it, and as a side effect you can install it to the right location This may not be what you want though David -- http://mail.python.org/mailman/listinfo/python-list
Re: PyParsing module or HTMLParser
Paul, Thank you for your reply. Here is a test page that I woul like to test with PyParsing http://www.ourglobalmarket.com/Test.htm From that I would like to extract the tittle ( it is below Lanjin Electronics Co., Ltd. ) (Sell 2.4GHz Wireless Mini Color Camera With Audio Function ) description - below the tittle next to the picture Contact person Company name Address fax phone Website Address Do you think that the PyParsing will work for that? Best regards, Lad. -- http://mail.python.org/mailman/listinfo/python-list
Re: author index for Python Cookbook 2?
Premshree Pillai wrote: There's an index here: http://harvestman.freezope.org/cookbook/creds.html That lists the authors. Where is a list of the recipes? -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)
Ville Vainio wrote: A minimal set would not be that offensive, yes. But then we would have two places to look for itertools functionality, which may not be desirable. True, though this is currently necessary with str objects if you want to use, say string.maketrans, so it's not without some precedent. If it's necessary to leave anything in itertools, my suggestion would be that the documentation for the iter type have a clear see also link to the itertools module. One thing that might be worth keeping in mind is that some of itertools functionality is going to become obsolete come py3k (izip-zip), and some is already (imap). At least such operations should not be dumped into the builtin iter. Yeah, maps and filters are basically obsolete as of generator expressions. The list of itertools functions that don't seem obsolete (and won't be made obsolete by Python 3.0): chain count cycle dropwhile groupby islice repeat takewhile tee As I suggested, I think that chain, islice and tee are tightly coupled with iterator objects, providing concatenation, slicing and copying operations. This leaves: count cycle dropwhile groupby repeat takewhile None of these really have analogs in sequence objects, so I consider them less tightly tied to iter. I'd probahbly say that these are more along the lines of alternate constructors, ala dict.fromkeys. While they're certainly useful at times, I'd be happy enough to leave them in itertools if that was the general feeling. Of course I guess I'd be happy enough to leave everything in itertools if that was the general feeling (or the BDFL pronouncement). ;) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakrefs to classes that derive from str
Peter Hansen wrote: I believe it's here: http://docs.python.org/lib/module-weakref.html if you search for the string Not all and read the next two paragraphs. On the other hand, it says (there) only that several builtin types such as list and dict ... can add support through subclassing, and does not say anything about int, str, etc... Ahh, thanks for the help. I guess there are at least two solutions to the OP's problem then: (1) Document that str and subclasses of str can't be weakreffed (easy) (2) Change str so that it (or at least its subclasses) can be weakreffed (hard) Probably either way a feature request should be filed. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib problem (maybe bugs?)
Timothy Wu wrote: After I've done that it works fine for small SEQ values. Then, when I try to send large amount of data (1.4MB), it fails miserably with AttributeError exception. the page states that you should send no more than 4000 proteins. how many proteins do you have in your 1.4 megabyte file? I highly suspect the two problems I have are the result of some bugs in the urllib module. Any suggestions? if the urllib module couldn't handle forms, don't you think anyone else would have noticed that by now? File C:\Python24\lib\urllib.py, line 786, in __init__ self.read = self.fp.read AttributeError: 'NoneType' object has no attribute 'read' my guess is that the server shuts the connection down when you're send too much data to it. have you contacted the server administrators? (see the bottom of that page). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting methods with similar names
You could achieve this by overriding __getattribute__ (untested): I believe OP would do better to use __getattr__, which is only called when the attribute is not found by the normal lookup, which is the only time he needs/wants customized control. TJR -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
Jaime Wyant [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I know I've seen this somewhere, but can't seem to google it. Is there a way to use an alternate statement separator, other than the default ';'? Other than \n, no. Both are builtin to the language definition and interpreter. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you use a closure in a class
Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] See the following. -- Paul class X(object): pass def makeAddr(tAdd): def add(self, tNum): return tNum + tAdd return add # add methods to class X X.add1 = makeAddr(1) X.add100 = makeAddr(100) You or others might find this rearrangement stylistically preferable: define makeAddr first, then class X(object): add1 = makeAddr(1) add100 = makeAddr(100) ... Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
Jaime Wyant wrote: I know I've seen this somewhere, but can't seem to google it. Is there a way to use an alternate statement separator, other than the default ';'? The validity of Terry's answer (which is true for the general case) aside, it might be possible to do what you are trying to do if you could explain what it is you are really trying to accomplish, rather than just asking about how you think you should accomplish it... (Ideas involving string.replace and exec come to mind, but it's impossible to say whether that might work in your context until you provide more background.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakrefs to classes that derive from str
Ron Garret wrote: foo(int) foo(float) foo(dict) foo(list) foo(str) TypeError: cannot create weak reference to 'C' object foo(tuple) TypeError: cannot create weak reference to 'C' object foo(long) TypeError: cannot create weak reference to 'C' object Ah, it appears that non-immediate immutable types don't support weakrefs. Hm... I see the same results you do, and yet I don't understand the comment. Can you please explain what immediate means in this context? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Write an hexadecimal file
Hi I'm trying to write an hexadecimal file... I mean not a text plain... I have to convert a float decimal number in float hexadecimal one, and that's done. That number is the one I'm gonna write in the hex file... can anybody help me 'cause i don't know how python write an hex file! Thanks! -- Atentamente, Cesar Andres Roldan Garcia Presidente Comunidad Académica Microsoft Javeriana Cali - Colombia -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
Well, I'm embedding python in an old C console app. This app uses a lot of ; delimited records. I want to allow the execution of arbitrary python statements inside some of these records. I was hoping there was an easy way to set the statement terminator. I will simply make up a new terminator and do some string substitution to turn my new terminator into python's ';'. Thanks ya'll, jw On Wed, 30 Mar 2005 11:58:42 -0500, Peter Hansen [EMAIL PROTECTED] wrote: Jaime Wyant wrote: I know I've seen this somewhere, but can't seem to google it. Is there a way to use an alternate statement separator, other than the default ';'? The validity of Terry's answer (which is true for the general case) aside, it might be possible to do what you are trying to do if you could explain what it is you are really trying to accomplish, rather than just asking about how you think you should accomplish it... (Ideas involving string.replace and exec come to mind, but it's impossible to say whether that might work in your context until you provide more background.) -Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Good use for Jython
Mike Wimpe [EMAIL PROTECTED] wrote or quoted: Other than being used to wrap Java classes, what other real use is there for Jython being that Python has many other GUI toolkits available? Also, these toolkits like Tkinter are so much better for client usage (and faster) than Swing, so what would be the advantage for using Jython? or Is Jython really just so that Java developers can write Java code faster? Jython allows Python programmers to access to the large volume of existing Java code and libraries - and provides access to a ubiquitous and widely distributed runtime environment. -- __ |im |yler http://timtyler.org/ [EMAIL PROTECTED] Remove lock to reply. -- http://mail.python.org/mailman/listinfo/python-list
Re: Weakrefs to classes that derive from str
[Ron Garret] Why doesn't this work? from weakref import ref class C(str): pass ... ref(C()) Traceback (most recent call last): File stdin, line 1, in ? TypeError: cannot create weak reference to 'C' object . . . Everything but strs. Also subclasses of tuple are not weak referencable. The issue is in the design of the C structure as a variable-sized immutable object. Both strings and tuples allocate as a single unit of memory that holds both the header information and the content information (the characters in a string or the array of object pointers for a tuple). Since the size varies from one string or tuple to the next, there is no straight-forward way for a subclass to add an additional header field pointing to a list of weak references. For lists and dicts, this is not a problem because the object is allocated in two sections, a fixed size header component and a pointer to another area of memory to hold the contents of the collection. This makes it possible for a subclass to graft-on a weak reference pointer at a known, fixed offset from the beginning of the header. There are two ways to fix this. One is to add a weak reference pointer to every string object -- that way you wouldn't even have to subclass it. Another way is to break the object into two pieces as is done for mutable containers like dicts and lists. Both approaches consume time and space. In general, that is not a big deal, but fast, memory efficient strings and tuples are at the center of all things Python. The need to weak reference this objects is somewhat rare in comparison to the frequency of their other uses. It did not make sense to always pay a time/space penalty just to create the possibility of weak referencing. While the design decision is unlikely to change, the docs could certainly be improved. A doc patch would be welcome. FWIW, the work-arounds are to weak-reference instances of UserString or to create a custom class with a has-a relationship instead of an is-a relationship. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Weekly Python Patch/Bug Summary
Over 2 days, this link consistently gives 500 Internal Server Error (from python.org, says IE): Decimal interaction with __rop__ (2005-03-19) http://python.org/sf/1166602 opened by Facundo Batista while this one works fine: Fix _tryorder in webbrowser.py (2005-03-20) http://python.org/sf/1166780 opened by Rodrigo Dias Arruda Senra Ditto for remainer (about half and half for the 10 or so I tried so far). I have occasionally had intermittent errors, but nothing like this before. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Mar 30)
QOTW: This is a Python newsgroup. Assume that we all have been brainwashed. -- Peter Otten [M]y experience porting Java to Jython is that it mostly involves deleting stuff :-) -- Kent Johnson [K]eep in mind, however, that not all problems in life can be solved with software. -- Roy Smith The Second Edition (of the *Cookbook*) hits the shelves! http://www.oreilly.com/catalog/pythoncook2/ Most of the week's news had to do with PyCon2005: http://python.org/moin/PyConDC2005 http://programming.newsforge.com/programming/05/03/29/0747230.shtml?tid=108tid=18 http://oreillynet.com/pub/wlg/6767 http://planetpython.org/ Notice that plenty of other PyEvents, including PyConDayBrasil in particular, are imminent: http://python.org/moin/PythonEvents#preview A Microsoft magazine publishes two favorable profiles of Python: http://www.devsource.com/article2/0,1759,1778141,00.asp http://www.devsource.com/article2/0,1759,1778250,00.asp How does a Linux-hosted Tkinter set its window icon? Jeff Epler knows: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/95a5c57c829699d2/ Roy Smith and Larry Bates, among others, cogently counsel would-be language autodidacts: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/359d8bc917d8dd0a/ Ivan Van Laningham addresses the off-topic matter of /bin/ls's performance with such precision as to illuminate Python use, particularly in its evocation of earlier threads: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9a8586f0ac49c8ca/ http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d6524ee021fc946f/ Raymond Hettinger, so wise in the ways of iteration, also knows his way around the syntax of decimal numerals: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a7b8b5de4c355d56 Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum further[s] the interests of companies that base their business on ... Python. http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a
Re: Write an hexadecimal file
[Cesar Andres Roldan Garcia] I'm trying to write an hexadecimal file... I mean not a text plain... I have to convert a float decimal number in float hexadecimal one, and that's done. The struct module provides a portable way to convert a float to and from a sequence of bytes. The binascii modules provides tools for converting a sequence of bytes to and from a representation as a hex string. import struct, binascii binascii.hexlify(struct.pack('f', 3.1415926535)) '40490fdb' struct.unpack('f', binascii.unhexlify(_))[0] 3.1415927410125732 Writing to a file is accomplished with the open() function and the file.write() method: f = open('mydata.hex', 'w') f.write('40490fdb') f.close() Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
return the last item in a list
I've googled for the above and get way too many hits.. I'm looking for an 'easy' way to have the last item in a list returned. I've thought about list[len(list)-1] but thought there would be a more gracefull way. -- http://mail.python.org/mailman/listinfo/python-list
Re: return the last item in a list
On 30 Mar 2005 10:48:17 -0700, rumours say that David Bear [EMAIL PROTECTED] might have written: I've googled for the above and get way too many hits.. I'm looking for an 'easy' way to have the last item in a list returned. I've thought about list[len(list)-1] but thought there would be a more gracefull way. There is. alist[-1] Did you read the tutorial? This is referenced in 3. An Informal Introduction to Python. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting methods with similar names
[Bearophile] Working in the interactive window I receive an error like this when I write the wrong method name: table.addGlas() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'Surface' object has no attribute 'addGlas' Is it possibile to make the object give a better answer: a short list of few method names similar to the one I've misspelled? [Bearophile] Thank you, __getattr__ does what I need :-) A smart help can be designed easely... The idea is a winner. When you're done, consider posting the result as an ASPN cookbook recipe. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: [DB-SIG] Looking for Stephen Turner, maintainer of informixdb
Read the license. If he's released it under GPL or BSD, then you could, in all good faith, release a fork of the code until he surfaces. Carsten Haese wrote: Hello everybody: I have discovered that the functionality for connecting Python to an Informix database is currently in a frustrating state of neglect. The link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I couldn't find any usable workarounds to the build problem, so I worked out successfully how to build informixdb using distutils. Now I'd like to share the result with the community, but the maintainer appears to have gone missing. My emails to [EMAIL PROTECTED] and [EMAIL PROTECTED] have bounced back undeliverable, so now I'm posting to the lists trying to locate Stephen. If anybody has any pointers for locating Stephen Turner, please let me know. If Stephen can't be located, I'd be willing to take over the project, but I'd prefer the torch be given to me rather than me just taking it. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: return the last item in a list
[David Bear] I'm looking for an 'easy' way to have the last item in a list returned. Try mylist.pop() or mylist[-1]. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Write an hexadecimal file
Larry Bates wrote: There is not such thing as a hexadecimal file. Right, 300 is 300 whether you choose to represent it in decimal, binary, hex, etc... it's still only 300 of something ;) -- http://mail.python.org/mailman/listinfo/python-list
checking if program is installing using python
i want to check to see if a certain program is installed on my windows box using python. how can i do that...(ie, i want to see if word is installed) please help -- http://mail.python.org/mailman/listinfo/python-list
CGI, FieldStorage and Filename
Hello, I'm writing a simple cgi script and want to be able to access the filename in a FieldStorage file instance. I have successfully manmaged to access the file as a 'file-like object' by using the simple code of : objInFile = objForm['DataFile'].file I can easily read through this data and get all the information out as I need - sorted!! However, when I attempt to access the filename attribute of this using : print 'Content-Disposition: attachment; filename=' + os.path.split(objForm['DataFile'].filename)[0] + '_reformatted.txt' I get None back for the filename. So I dumped the content of the objForm['DataFile'] to stdout to see what it contains : print objForm['DataFile'] I got back this : FieldStorage('DataFile', 'MOAF_10-12_fin_2.txt', 'Project\tJob\tBarcode\tPlate set blaahh, blaaahh, blahh) As you can see, when __str__ is called, the FieldStorage is displaying the name of the client side file - so it knows what it is, however when I call .filename on it, I get None. I don;t get what is happening here - has anyone else seen this and/or knows what I'm doing wrong? If so then all and any help would be much appreciated. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
AttributeError: ClassA instance has no attribute '__len__'
I'm new to Python. In general I manage to understand what is happening when things go wrong. However, the small program I am writing now fails with the following message: AttributeError: ClassA instance has no attribute '__len__' Following the traceback,I see that the offending line is self.x = arg1 + len(self.y) + 1 Why should this call to the built-in len() fail? In a small test program it works with no problems: class foo: def __init__(self): self.x = 0 self.y = 'y' def fun(self, arg1): self.x = arg1 + len(self.y) + 1 a = foo() a.fun(2) No problems; can you help me make some sense of what is happening? Thanks in advance Mack -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI, FieldStorage and Filename
Neil Benn wrote: Hello, I'm writing a simple cgi script and want to be able to access the filename in a FieldStorage file instance. I have successfully manmaged to access the file as a 'file-like object' by using the simple code of : snip Sorry, split the filename on path not pathext.. have a nice day if you are in a different time zone than me! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: PyParsing module or HTMLParser
Lad - Well, here's what I've got so far. I'll leave the extraction of the description to you as an exercise, but as a clue, it looks like it is delimited by bView Detail/b/a/td/tr/tbody/table br at the beginning, and Quantity: 500br at the end, where 500 could be any number. This program will print out: ['Title:', 'Sell 2.4GHz Wireless Mini Color Camera With Audio Function Manufacturers Hong Kong - Exporters, Suppliers, Factories, Seller'] ['Contact:', 'Mr. Simon Cheung'] ['Company:', 'Lanjin Electronics Co., Ltd.'] ['Address:', 'Rm 602, 6/F., Tung Ning Bldg., 2 Hillier Street, Sheung Wan , Hong Kong\n, HK\n( Hong Kong )'] ['Phone:', '85235763877'] ['Fax:', '85231056238'] ['Mobile:', '852-96439737'] So I think pyparsing will get you pretty far along the way. Code attached below (unfortunately, I am posting thru Google Groups, which strips leading whitespace, so I have inserted '.'s to preserve code indentation; just strip the leading '.' characters). -- Paul === from pyparsing import * import urllib # get input data url = http://www.ourglobalmarket.com/Test.htm; page = urllib.urlopen( url ) pageHTML = page.read() page.close() #~ I would like to extract the tittle ( it is below Lanjin Electronics #~ Co., Ltd. ) #~ (Sell 2.4GHz Wireless Mini Color Camera With Audio Function ) #~ description - below the tittle next to the picture #~ Contact person #~ Company name #~ Address #~ fax #~ phone #~ Website Address LANGBRK = Literal() RANGBRK = Literal() SLASH = Literal(/) tagAttr = Word(alphanums) + = + dblQuotedString # helpers for defining HTML tag expressions def startTag( tagname ): return ( LANGBRK + CaselessLiteral(tagname) + \ ...ZeroOrMore(tagAttr) + RANGBRK ).suppress() def endTag( tagname ): return ( LANGBRK + SLASH + CaselessLiteral(tagname) + RANGBRK ).suppress() def makeHTMLtags( tagname ): return startTag(tagname), endTag(tagname) def strong( expr ): return strongStartTag + expr + strongEndTag strongStartTag, strongEndTag = makeHTMLtags(strong) titleStart, titleEnd = makeHTMLtags(title) tdStart, tdEnd = makeHTMLtags(td) h1Start, h1End = makeHTMLtags(h1) title = titleStart + SkipTo( titleEnd ).setResultsName(title) + titleEnd contactPerson = tdStart + h1Start + \ ...SkipTo( h1End ).setResultsName(contact) company = ( tdStart + strong(Company:) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(company) address = ( tdStart + strong(Address:) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(address) phoneNum = ( tdStart + strong(Phone:) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(phoneNum) faxNum= ( tdStart + strong(Fax:;) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(faxNum) mobileNum = ( tdStart + strong(Mobile:) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(mobileNum) webSite = ( tdStart + strong(Website Address:) + tdEnd + tdStart ) + \ ...SkipTo( tdEnd ).setResultsName(webSite) scrapes = title | contactPerson | company | address | phoneNum | faxNum | mobileNum | webSite # use parse actions to remove hyperlinks linkStart, linkEnd = makeHTMLtags(a) linkExpr = linkStart + SkipTo( linkEnd ) + linkEnd def stripHyperLink(s,l,t): return [ t[0], linkExpr.transformString( t[1] ) ] company.setParseAction( stripHyperLink ) # use parse actions to add labels for data elements that don't # have labels in the HTML def prependLabel(pre): def prependAction(s,l,t): return [pre] + t[:] return prependAction title.setParseAction( prependLabel(Title:) ) contactPerson.setParseAction( prependLabel(Contact:) ) for tokens,start,end in scrapes.scanString( pageHTML ): print tokens -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
In article [EMAIL PROTECTED], runsun pan [EMAIL PROTECTED] wrote: . . . Secondly, [x+y for x,y in itertools.izip(xs, ys)] did go much faster than map(lambda x,y: x+y, xs, ys). The latter is not only the slowest one, but with an amazingly slow speed of 15 times slowdown. If I understand the story correctly, this reflects Raymond Hettinger's extraordinary achievement in making all things iter* really, really quick. -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: ClassA instance has no attribute '__len__'
MackS wrote: I'm new to Python. In general I manage to understand what is happening when things go wrong. However, the small program I am writing now fails with the following message: In general you are more likely to get helpful responses from this group if you post the actual code that has the problem and include the actual traceback. However... AttributeError: ClassA instance has no attribute '__len__' Following the traceback,I see that the offending line is self.x = arg1 + len(self.y) + 1 len calls the object's __len__ method. self.y is bound to something (an instance of ClassA) that apparently has no __len__ method Why should this call to the built-in len() fail? In a small test program it works with no problems: class foo: def __init__(self): self.x = 0 self.y = 'y' def fun(self, arg1): self.x = arg1 + len(self.y) + 1 a = foo() a.fun(2) In this case self.y is bound to something different i.e., 'y' :an object of type str, which has a __len__ method: 'y'.__len__() 1 Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if program is installing using python
does this help? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggesting methods with similar names
Raymond HettingerWhen you're done, consider posting the result as an ASPN cookbook recipe. I still cannot write in the cookbook... I think I have problems with the registration. So you can put it there... I've found that difflib is good enough for the string matching. This idea isn't fully mine, it's modified from the Mathematica textual interface. Here is the code with long lines: | def __getattr__(self, name): | If a wrong method is called, suggest methods with similar names. | def match(str1, str2): | Return approximate string comparator measure (between 0.0 and 1.0) using difflib. | if str1 == str2: | return 1.0 | m1 = SequenceMatcher(None, str1, str2) | m2 = SequenceMatcher(None, str2, str1) | return (m1.ratio()+m2.ratio()) / 2.0 # average | | toRemove = __delattr__ __dict__ __getattribute__ __module__ __new__ __reduce__ __copy__ |__reduce_ex__ __setattr__ __slot__ __weakref__ __str__ __class__ __doc__.split() | methods = set(dir(self.__class__)).difference(toRemove) | name = name.lower() | matchList = [ (match(name, m.lower()),m) for m in methods ] | suggestions = sorted(matchList, reverse=True)[:5] # A heap isn't necessary here | suggestions = , .join( pair[1] for pair in suggestions ) | raise AttributeError, (method '%s' not found. \nMost similar named ones: %s % (name, suggestions)) Note: the general idea of a smart help can be improved a *lot*, this is the basic version :-] Bear hugs, Bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
Jaime Wyant wrote: Well, I'm embedding python in an old C console app. This app uses a lot of ; delimited records. I want to allow the execution of arbitrary python statements inside some of these records. I was hoping there was an easy way to set the statement terminator. I will simply make up a new terminator and do some string substitution to turn my new terminator into python's ';'. You refer to it here as a statement terminator, but in the first posting you called it a statement separator. I believe it is just a separator, not a terminator, and as such is not even required unless you need/want to have two statements on the same line. In all the tens of thousands of lines of Python code I've written, I don't believe I've ever used a single semicolon to separate two statements. Perhaps you don't need them either... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if program is installing using python
[EMAIL PROTECTED] wrote] does this help? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 There is the which module that I wrote that does this a little more robustly: http://starship.python.net/~tmick/#which However, I didn't see the original posting for this thread so I'm not sure if this is what is being looked for. Cheers, Trent -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlretireve problem
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Larry Bates wrote: I noticed you hadn't gotten a reply. When I execute this it put's the following in the retrieved file: !DOCTYPE HTML PUBLIC -//IETF//DTD HTML 2.0//EN HTMLHEAD TITLE404 Not Found/TITLE /HEADBODY H1Not Found/H1 The requested URL /pool/updates/main/p/perl/libparl5.6_5.6.1-8.9_i386.deb was no t found on this server.P /BODY/HTML You will probably need to use something else to first determine if the URL actually exists. I'm happy that at least someone responded as this was my first post to the python mailing list. I'm coding a program for offline package management. The link that I provided could be obsolete by newer packages. That is where my problem is. I wanted to know how to raise an exception here so that depending on the type of exception I could make my program function. For example, for Temporary Name Resolution Failure, python raises an exception which I've handled well. The problem lies with obsolete urls where no exception is raised and I end up having a 404 error page as my data. Can we have an exception for that ? Or can we have the exit status of urllib.urlretrieve to know if it downloaded the desired file. I think my problem is fixable in urllib.urlopen, I just find urllib.urlretrieve more convenient and want to know if it can be done with it. Thanks for responding. rrs - -- Ritesh Raj Sarraf RESEARCHUT -- http://www.researchut.com Gnupg Key ID: 04F130BC Stealing logic from one person is plagiarism, stealing from many is research. -BEGIN PGP SIGNATURE- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFCSuYS4Rhi6gTxMLwRAu0FAJ9R0s4TyB7zHcvDFTflOp2joVkErQCfU4vG 8U0Ah5WTdTQHKRkmPsZsHdE= =OMub -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: ClassA instance has no attribute '__len__'
MackS [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] | I'm new to Python. In general I manage to understand what is happening | when things go wrong. However, the small program I am writing now fails | with the following message: | | AttributeError: ClassA instance has no attribute '__len__' | | Following the traceback,I see that the offending line is | | self.x = arg1 + len(self.y) + 1 | | Why should this call to the built-in len() fail? In a small test | program it works with no problems: | | class foo: | def __init__(self): |self.x = 0 |self.y = 'y' | | def fun(self, arg1): | self.x = arg1 + len(self.y) + 1 | | a = foo() | a.fun(2) | | | No problems; can you help me make some sense of what is happening? In your program, self.y is an instance of ClassA. The traceback tells you that ClassA has no __len__ attribute (i.e. it is an object that has no no special method called __len__, which is what gets called when you do len(obj). In your test program, self.y is y, a string, which has a __len__ method by design: (see dir(y), which gives you: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] If you want len(self.y) to work, self.y must be an object that implements a __len__ method. In other words, your ClassA needs a __len__ method. A trivial example: class ClassA: def __init__(self, text): self.text = text def __len__(self): #return something useful return len(self.text) y = ClassA(Hello) print len(y) # prints 5 Regards, -- Vincent Wehren | | Thanks in advance | | Mack | -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.4.1 (final)
The page http://www.python.org/download/ needs to be added to the list of things updated with a new release. It would, for instance, have me download python-2.4.msi rather than the new python-2.4.1 msi, which is a couple of clicks farther away. A naive visitor would be much less likely to find the new file. (I also notified [EMAIL PROTECTED]). And yes, thanks for the new edition. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
TOC of Python Cookbook now online (was Re: author index for Python Cookbook 2?)
[EMAIL PROTECTED] wrote: Premshree Pillai wrote: There's an index here: http://harvestman.freezope.org/cookbook/creds.html That lists the authors. Where is a list of the recipes? I emailed the O'Reilly webmaster, and the table of contents are now online at http://www.oreilly.com/catalog/pythoncook2/toc.html and also listed below. Table of Contents Preface 1. Text 1.1 Processing a String One Character at a Time 1.2 Converting Between Characters and Numeric Codes 1.3 Testing Whether an Object Is String-like 1.4 Aligning Strings 1.5 Trimming Space from the Ends of a String 1.6 Combining Strings 1.7 Reversing a String by Words or Characters 1.8 Checking Whether a String Contains a Set of Characters 1.9 Simplifying Usage of Strings' translate Method 1.10 Filtering a String for a Set of Characters 1.11 Checking Whether a String Is Text or Binary 1.12 Controlling Case 1.13 Accessing Substrings 1.14 Changing the Indentation of a Multiline String 1.15 Expanding and Compressing Tabs 1.16 Interpolating Variables in a String 1.17 Interpolating Variables in a String in Python 2.4 1.18 Replacing Multiple Patterns in a Single Pass 1.19 Checking a String for Any of Multiple Endings 1.20 Handling International Text with Unicode 1.21 Converting Between Unicode and Plain Strings 1.22 Printing Unicode Characters to Standard Output 1.23 Encoding Unicode Data for XML and HTML 1.24 Making Some Strings Case-Insensitive 1.25 Converting HTML Documents to Text on a Unix Terminal 2. Files 2.1 Reading from a File 2.2 Writing to a File 2.3 Searching and Replacing Text in a File 2.4 Reading a Specific Line from a File 2.5 Counting Lines in a File 2.6 Processing Every Word in a File 2.7 Using Random-Access Input/Output 2.8 Updating a Random-Access File 2.9 Reading Data from zip Files 2.10 Handling a zip File Inside a String 2.11 Archiving a Tree of Files into a Compressed tar File 2.12 Sending Binary Data to Standard Output Under Windows 2.13 Using a C++-like iostream Syntax 2.14 Rewinding an Input File to the Beginning 2.15 Adapting a File-like Object to a True File Object 2.16 Walking Directory Trees 2.17 Swapping One File Extension for AnotherThroughout a Directory Tree 2.18 Finding a File Given a Search Path 2.19 Finding Files Given a Search Path and a Pattern 2.20 Finding a File on the Python Search Path 2.21 Dynamically Changing the Python Search Path 2.22 Computing the Relative Path from One Directory to Another 2.23 Reading an Unbuffered Character in a Cross-Platform Way 2.24 Counting Pages of PDF Documents on Mac OS X 2.25 Changing File Attributes on Windows 2.26 Extracting Text from OpenOffice.org Documents 2.27 Extracting Text from Microsoft Word Documents 2.28 File Locking Using a Cross-Platform API 2.29 Versioning Filenames 2.30 Calculating CRC-64 Cyclic Redundancy Checks 3. Time and Money 3.1 Calculating Yesterday and Tomorrow 3.2 Finding Last Friday 3.3 Calculating Time Periods in a Date Range 3.4 Summing Durations of Songs 3.5 Calculating the Number of Weekdays Between Two Dates 3.6 Looking up Holidays Automatically 3.7 Fuzzy Parsing of Dates 3.8 Checking Whether Daylight Saving Time Is Currently in Effect 3.9 Converting Time Zones 3.10 Running a Command Repeatedly 3.11 Scheduling Commands 3.12 Doing Decimal Arithmetic 3.13 Formatting Decimals as Currency 3.14 Using Python as a Simple Adding Machine 3.15 Checking a Credit Card Checksum 3.16 Watching Foreign Exchange Rates 4. Python Shortcuts 4.1 Copying an Object 4.2 Constructing Lists with List Comprehensions 4.3 Returning an Element of a List If It Exists 4.4 Looping over Items and Their Indices in a Sequence 4.5 Creating Lists of Lists Without Sharing References 4.6 Flattening a Nested Sequence 4.7 Removing or Reordering Columns in a List of Rows 4.8 Transposing Two-Dimensional Arrays 4.9 Getting a Value from a Dictionary 4.10 Adding an Entry to a Dictionary 4.11 Building a Dictionary Without Excessive Quoting 4.12 Building a Dict from a List of Alternating Keys and Values 4.13 Extracting a Subset of a Dictionary 4.14 Inverting a Dictionary 4.15 Associating Multiple Values with Each Key in a Dictionary 4.16 Using a Dictionary to Dispatch Methods or Functions 4.17 Finding Unions and Intersections of Dictionaries 4.18 Collecting a Bunch of Named Items 4.19 Assigning and Testing with One Statement 4.20 Using printf in Python
Re: Using something other than ';' to separate statements
Jaime Wyant wrote: [snip] After goofing around with this idea, I've realized you can't be very expressive with a bunch of python statements strung together. My biggest problem is that I can't figure out (i don't think you can), how to do conditionals that are strung together: # This won't work if a 5: print a 5;else print Doh I've decided to just call a function from the semicolon delimited record, using the return value in my `C' app... The following might work based on the context: code = '''if a 5: \nprint a 5\nelse:\nprint Doh\n''' or, formatted differently code = ''' if a 5: print a 5 else: print Doh ''' Then, you could do exec(code) Yeah, I tried to make it work, but it just won't. At least not in a satisfactory way. Thanks! jw André -- http://mail.python.org/mailman/listinfo/python-list
Python and USB
Rogger, I am trying to use wrapper for libusb. I downloaded the Usb.py but I am not sure that I have the libusb installed on my Pc. Can you help me in getting libusb.py or libusb.c . Thank you, Ravi -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
On Wed, 30 Mar 2005 14:26:20 -0500, Peter Hansen [EMAIL PROTECTED] wrote: Jaime Wyant wrote: Well, I'm embedding python in an old C console app. This app uses a lot of ; delimited records. I want to allow the execution of arbitrary python statements inside some of these records. I was hoping there was an easy way to set the statement terminator. I will simply make up a new terminator and do some string substitution to turn my new terminator into python's ';'. You refer to it here as a statement terminator, but in the first posting you called it a statement separator. I believe it is just a separator, not a terminator, and as such is not even required unless you need/want to have two statements on the same line. Yeah, my thinking was that a separator implied terminator, because to separate something has to have a beginning / ending. Sorry for the inconsistency. Anyway, I did want to be able to string a handful of statements together in one string. The python statements were one of the semicolon delimited fields I'm working with -- which is where my problem lied. After goofing around with this idea, I've realized you can't be very expressive with a bunch of python statements strung together. My biggest problem is that I can't figure out (i don't think you can), how to do conditionals that are strung together: # This won't work if a 5: print a 5;else print Doh I've decided to just call a function from the semicolon delimited record, using the return value in my `C' app... In all the tens of thousands of lines of Python code I've written, I don't believe I've ever used a single semicolon to separate two statements. Perhaps you don't need them either... Yeah, I tried to make it work, but it just won't. At least not in a satisfactory way. Thanks! jw -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem in designing a global directory in python
'@'.join([..join(['fred','dixon']),..join(['gmail','com'])]) a écrit : noob warning: what is so wonderful about the NEW class over the old ? A whole lot of things. But the main thing to know is that old-style classes are deprecated, and will disappear in the future. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using something other than ';' to separate statements
Jaime Wyant wrote: # This won't work if a 5: print a 5;else print Doh This will: [Doh, a 5][a 5] I highly discourage using it though--it's somewhat obtuse. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
[ANN]: Last Chance 2005 IORCC Entries
FOR IMMEDIATE RELEASE: Wed Mar 30 11:58:39 CST 2005 LOCATION: http://iorcc.dyndns.org/2005/press/033005.html ANNOUNCEMENT: 2005 IORCC Deadline Approaches Entry Deadline March 31st, 2005 Less than 36 Hours Left, Great Prizes and Fun! Dear Rubyists, Perlists, Shellists, Cists and Hackers, Well, it has boiled down to this, a great finish for the International Obfuscated Ruby Code Contest, 2005 Edition. There is still 30 hours left to get your obscure and wacky Ruby code entered. Surf on over to the Official IORCC rules and website: http://iorcc.dyndns.org With over $2000 USD in prizes from notable industry leaders like Stone Design, OmniGroup, Luscious Monster, OpenBase, Bare Bones Software, O'Reilly Press, Syngress, Purgatory Design, Running With Scissors, BasaSoft, Ecto, Puzzles Forever, Pragmatic Programmer, Bartas Tech, Macro Mates, Ambrosia Software, Sol Robots, Code Tek, dbSuite and more! You just won't believe the list of prizes these generous people have committed to giving away! Dust off your Ruby compiler, take your Perl, Shell, Python and Tcl skills to the test, making a really obscure and obfuscated entry for this years contest. Entry window closes at 23:59:59 Universal Time March 31st, 2005. Official Sponsors, Rules and Entry Guidelines are available online at the IORCC Website. Enter Today! We'd like to also say thanks to the following people and companies in chronological order of sponsorship: - Dave Thomas, Signed copies of PickAxe and Ruby on Rails books! - Syngress Press, Ruby the Developers Guide (700+ pages of real world Ruby) - Purgatory Design's Intaglio, graphics application for charting obscure entries. - O'Reilly and Associates, The Ruby Nutshell book, need we say more? - Andrew Stone's, Stone Design Suite, Create, Graphics, WebApps, Applets and more! - Puzzles Forever, the folks that invented Solitaire Forever. - OpenBase SQL, OpenStep and now OSX Database solutions for Linux, Windows and MacOSX. - Postal2: Share the Pain from the sick puppies at Running With Scissors/Infamous Gary Coleman. - Sol Robot's CrosswordForge, word finder and crossword puzzle generator. Fun for all. - Bartas Technologies' CopyWrite, got a book or documents to publish? Use CopyWrite. - MacroMates' TextMate. Lightweight and POWERFUL code project management tool, really slick! - CodeTek's Virtual Desktop. The definitive way to expand and maximize your desktop workspace. - OmniGroup's OmniGraffle and OmniOutline, the way to go in professional presentations. - InterServices New Media's, dbSuite WebBuilder and SQL4X Manager J for OS X. - Ecto for OS X, the power of the blog! - BasaSoft's, BasaOne, the Integrated Web Application Development Environment. - Bare Bones Software, with Mail Smith and BBEdit, the Professional HTML editing for OS X. - Pipe, simple, elegant, powerful. The utility editor for OS X. - Ambrosia Software, with SnapzProX 2 and WireTap Pro. Make moves from the desktop! - Delicious Monster, with of course Delicious Library. Catalog your videos, music and more! A big thank you to all the contestants, sponsors and support from the Ruby community. We have had a great time putting this together, and now we can (almost) begin the judging process. Winners will be announced after noon April 1st, 2005. A public voting forum for the 2005 IORCC People's Choice Award will be opened with voting continuing thru the 15th of April, 2005. Winners will be announced shortly after the web voting is closed and counted. Best of luck to you all! Todd Nathan IORCC Founder/Judge irc://irc.freenode.net/iorcc (SeaForth) http://iorcc.dyndns.org/ What you talkin about Willis? - GC 2005 IORCC Sponsor Home Page Links: http://www.pragprog.com/ http://www.syngress.com/ http://www.purgatorydesign.com/ http://www.oreilly.com/ http://www.stone.com/ http://www.solitaireforever.com/ http://www.openbase.com/ http://www.gopostal.com/ http://www.solrobots.com/ http://www.bartastechnologies.com/ http://www.macromates.com/ http://www.codetek.com/ http://www.omnigroup.com/ http://www.dbsuite.de/ http://ecto.kung-foo.tv/ http://www.basasoft.com/ http://www.barebones.com/index.shtml http://www.kcore.de/ http://www.ambrosiasw.com/news/ http://www.delicious-monster.com/ -- http://mail.python.org/mailman/listinfo/python-list