Re: What's the use of changing func_name?
could ildg wrote: def a(func): def _inner(*args, **kwds): print decorating... return func(*args, **kwds) _inner.func_name = func.func_name --when I delete this line, the rusult is the same. why? return _inner @a def g(*args): for x in args: print x print this is in function g g(1,2,3,4,5) func_name is writable in python 2.4. I wonder what's the use of writing it. Consider the code above, to change the func_name or not will get the completely same result. The result is as below: decorating... 1 2 3 4 5 this is in function g Please tell me how does this happen, thank you~ Well, the function you posted certainly doesn't change the literal string you have inside when you change its func_name. However, the function object *does* change. In [1]:def g(x): ...:pass ...: In [2]:g Out[2]:function g at 0x5aedf0 In [3]:g.func_name = 'f' In [4]:g Out[4]:function f at 0x5aedf0 -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: MMS download
Chu, Jeong Ho wrote: Is it possible to download MMS stream by using python? I don't know of a way with Python alone, but you could use mplayer's -dumpstream capabilities to dump to a file. It might even allow you to dump to a pipe, I forget. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the use of changing func_name?
Thank you for your help. I know the function g is changed after setting the func_name. But I still can't call funciton g by using f(), when I try to do this, error will occur: code g.func_name=f print g function f at 0x00B2CEB0 f() Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined /code Since the name of g is changed into f, why can't I call it by using f()? Should I call it using f through other ways? Please tell me. Thanks~ On 5/19/05, Robert Kern [EMAIL PROTECTED] wrote: could ildg wrote: def a(func): def _inner(*args, **kwds): print decorating... return func(*args, **kwds) _inner.func_name = func.func_name --when I delete this line, the rusult is the same. why? return _inner @a def g(*args): for x in args: print x print this is in function g g(1,2,3,4,5) func_name is writable in python 2.4. I wonder what's the use of writing it. Consider the code above, to change the func_name or not will get the completely same result. The result is as below: decorating... 1 2 3 4 5 this is in function g Please tell me how does this happen, thank you~ Well, the function you posted certainly doesn't change the literal string you have inside when you change its func_name. However, the function object *does* change. In [1]:def g(x): ...:pass ...: In [2]:g Out[2]:function g at 0x5aedf0 In [3]:g.func_name = 'f' In [4]:g Out[4]:function f at 0x5aedf0 -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
self-promotion of the decorator module (Was: How to learn OO of python?)
could ildg wrote: I think decorator is a function which return a function, is this right? e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ arg %r does not match %s % (a,t) return f(*args, **kwds) new_f.func_name = f.func_name return new_f return check_accepts After I saw all the examples, I concluded that every decorator must define an inner function which takes only one argument, the function to decorate. Is this right? Yes, but you may want to look at my decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip Your example would be written as follows: from decorator import decorator def accepts(*types): def check_accepts(f, *args, **kw): assert len(types) == f.func_code.co_argcount for a, t in zip(args, types): assert isinstance(a, t), arg %r does not match %s % (a,t) return f(*args, **kw) return decorator(check_accepts) with the following advantages: 1. one-level of nesting is saved (flat is better than nested) 2. name, docstring and dictionary of the original function are preserved; 3. the signature of the original function is preserved (this one is nontrivial). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the use of changing func_name?
could ildg wrote: Thank you for your help. I know the function g is changed after setting the func_name. But I still can't call funciton g by using f(), when I try to do this, error will occur: code g.func_name=f print g function f at 0x00B2CEB0 f() Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined /code Since the name of g is changed into f, why can't I call it by using f()? Should I call it using f through other ways? Please tell me. Thanks~ Merely changing func_name to 'f' will not register 'f' in the module's namespace. So calling f() will cause a NameError as there is no function object bound to the name 'f' in the namespace. Instead, if you say f = g then 'f' is bound in the namespace to the function object pointed to by 'g' and you can now make the call f(). -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the use of changing func_name?
could ildg wrote: Thank you for your help. I know the function g is changed after setting the func_name. But I still can't call funciton g by using f(), when I try to do this, error will occur: code g.func_name=f print g function f at 0x00B2CEB0 f() Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined /code Since the name of g is changed into f, why can't I call it by using f()? Should I call it using f through other ways? Please tell me. Thanks~ Others have answered this particular question, but you're probably still wondering what is the use of changing .func_name if it doesn't also change the name by which you call it. The answer is that there are tools that use the .func_name attribute for various purposes. For example, a documentation generating tool might look at the .func_name attribute to make the proper documentation. Actually, that's probably *the* biggest use case because I can't think of any more significant ones. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to learn OO of python?
could ildg wrote: I think decorator is a function which return a function, is this right? e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ arg %r does not match %s % (a,t) return f(*args, **kwds) new_f.func_name = f.func_name return new_f return check_accepts After I saw all the examples, I concluded that every decorator must define an inner function which takes only one argument, the function to decorate. Is this right? It's close, but not quite right. (I will use the word function for the moment, but see below for why this is inaccurate.) Every *decorator* must take only one argument, the function to decorate. It is not at all necessary that a decorator define an inner function. Consider (from [1]): def onexit(f): import atexit atexit.register(f) return f onexit is a decorator because it takes a function and returns a function. In this case, it happens to be that the same function is accepted and returned. Note that in the 'accepts' example above, *check_accepts* is the decorator, not accepts. The accepts function is actually a function that *returns* decorators. Now about that word function. Decorators are actually *callables* that accept a single *callable* and return a *callable*. Why does the terminology matter? Because I can construct decorators from classes too (from [2]): class memoized(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: return self.func(*args) Now the memoized decorator can be used just like any other decorator, e.g.: @memoized def fibonacci(n): if n in (0, 1): return n return fibonacci(n-1) + fibonacci(n-2) Note however that memoized is a *callable*, not a *function*. STeVe [1] http://www.python.org/peps/pep-0318.html [2] http://wiki.python.org/moin/PythonDecoratorLibrary -- http://mail.python.org/mailman/listinfo/python-list
Re: How to receive events (eg. user mouse clicks) from IE
The two you'll need to run makepy for are Microsoft Internet Controls and Microsoft HTML object Library. If you run them manually, you should be able to look at the generated code to get the guids. Here's a minimal example: import win32com.client ie_mod=win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-C05BAE0B}',0, 1, 1) class IE_Events(ie_mod.DWebBrowserEvents2): def OnNavigateComplete2(self, pDisp, URL): print 'OnNavigateComplete2:', URL ie=win32com.client.DispatchWithEvents('InternetExplorer.Application',IE_Events) ie.Visible=1 ie.Navigate('http://www.google.com') hth Roger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am trying to trap events from internet explorer eg. when user clicks on an html link - I need to get notified for that event. After looking through the newgroups / internet and reading through various sections in programming python on win32 - I understand that this can be done using DispatchWithEvents. I have also referred to discussions on comp.lang.python http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a3c502d06412a5f8/0ee3083e71316da7?q=dispatchwitheventsrnum=43#0ee3083e71316da7 and http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1da0668794851296/5bcec1fda216c598?q=dispatchwitheventsrnum=19#5bcec1fda216c598 So far - none of the newgroups postings report that IE events were trapped successfully (at least I could not find any). However, there is enough evidence that it can be done. My problems at the moment: a) The examples use early binding. However, I cannot get Python makepy to generate the code to force makepy process at run time - since COM makepy utility that I invoke from python win 32 does not have any entry for internet explorer. I tried to find the CLSID for IE 3050F613-98B5-11CF-BB82-00AA00BDCE0B but I get an exception b) Also one of the examples suggest that following code should work mod = EnsureModule(...) class MyEvents(mod.IDocumentEvents): # your methods here handler = MyEvents(ie.document) # handler should start recieving events. however, what CLSID is to be used in EnsureModule... . I tried with a few but I always get the error 'NoneType' object has no attribute 'IDocumentEvents' An example that 'works' will be very useful == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree and xsi to xmlns conversion?
Matthew Thorley wrote: Why does ElementTree.parse convert my xsi to an xmlns? because it is a namespace prefix, perhaps? When I do this from elementtree import ElementTree # Sample xml mgac = mgac xmlns=http://www.chpc.utah.edu/~baites/mgacML; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; xsi:schemaLocation=http://www.chpc.utah.edu/~baites/mgacML http://www.chpc.utah.edu/~baites/mgacML/mgac.xsd;cluster name=Si4H/cluster/mgac xml = ElementTree.fromstring(mgac) ElementTree.tostring(xml) I get this 'ns0:mgac ns1:schemaLocation=http://www.chpc.utah.edu/~baites/mgacML http://www.chpc.utah.edu/~baites/mgacML/mgac.xsd; xmlns:ns0=http://www.chpc.utah.edu/~baites/mgacML; xmlns:ns1=http://www.w3.org/2001/XMLSchema-instance;ns0:cluster name=Si4H //ns0:mgac' The xsi is gone and has been replaced by a new xmlns, which is also NOT inherited by the child elements. the xsi is a namespace prefix, which maps to a namespace URI. the child element doesn't use that namespace, so there's no need to add a namespace declaration. ElementTree.tostring(xml.getchildren()[0]) 'ns0:cluster name=Si4H xmlns:ns0=http://www.chpc.utah.edu/~baites/mgacML; /' If some one could please explain where I'm off I'd really appreciate it. I need to use xsi: to validate the document are you sure? the prefix shouldn't matter; it's the namespace URI that's important. if you're writing code that depends on the namespace prefix rather than the name- space URI, you're not using namespaces correctly. when it comes to namespaces, elementtree forces you to do things the right way: http://www.jclark.com/xml/xmlns.htm (unfortunately, the XML schema authors didn't understand namespaces so they messed things up: http://www.w3.org/2001/tag/doc/qnameids-2002-04-30 to work around this, see oren's message about how to control the namespace/prefix mapping. in worst case, you can manually insert xsi:-attributes in the tree, and rely on the fact that the default writer only modifies universal names) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing 2 similar strings?
Could hit a few snags. Quick out-of-the-library compression using standards like zlib will have headers that will dilute the difference on short strings, and on long strings block compression (zlib, bzip2) will not pick up similarities because the similarities will be in different blocks. With blocks of around 100k-1M in these algos by default (IIRC), this could work well for strings between oh say 1k-50k. But I need to underscore Aahz's posting above: ***Check out difflib, it's in the library.*** Perfect package for what the OP wants AFAICT. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
len [EMAIL PROTECTED] writes: I am in the process of learning python. I have bought Learning Python by Mark Lutz, printed a copy of Dive into Python and various other books and looked at several tutorials. I have started a stupid little project in python and things are proceeding well. I am an old time cobol programmer from the IBM 360/370 eria and this ingrained idea of file processing using file definition (FD's) I believe is causing me problems because I think python requires a different way of looking at datafiles and I haven't really gotten my brain around it yet. I would like to create a small sequential file, processing at first to store a group id, name, amount, and date which I can add to delete from and update. Could someone point me to some code that would show me how this is done in python. Eventually, I intend to expand my little program to process this file as a flat comma delimited file, move it to some type of indexed file and finally to some RDBMS system. My little program started out at about 9 lines of code and is now at about 100 with 5 or six functions which I will eventually change to classes (I need to learn OOP to but one step at a time). What you're looking for isn't so much the Python way of doing things; it's the Unix way of doing things. The OS doesn't present the file as a sequence of records; files are presented as a sequence of bytes. Any structure beyond that is provided by the application - possibly via a library. This is a sufficiently powerful way of looking at files that every modern OS I'm familiar with uses this view of files. You might want to look at URL: http://www.faqs.org/docs/artu/ . It's not really an answer to your question, but looks at Unix programming in general. It uses fetchmail as an example application, including examining the configuration editor written in Python. A classic Unix approach to small databases is to use text files. When you need to update the file, you just rewrite the whole thing. This works well on Unix, because it comes with a multitude of tools for processing text files. Such an approach is simple and easy to implement, but not very efficient for large files. A classic example is a simple phone book application: you have a simple tool for updating the phone book, and use the grep command for searching it. Works like a charm for small files, and allows for some amazingly sophisticated queries. To provide some (simple) code, assume your file is a list of lines, with id, name, amount, date on each line, separated by spaces. Loading this into a list in memory is trivial: datafile = open(file, r) datalist = [] for line in data: datalist.append(line.split()) datafile.close() At this point, datalist is a list of lists. datalist[0] is a list of [id, name, amount, date]. You could (for example) sum all the amounts like so: total = 0 for datum in datalist: total += datum[2] There are more concise ways to write this, but this is simple and obvious. Writing the list back out is also trivial: datafile = open(file, w) datafile.writelines( .join(x) + \n for x in datalist) datafile.close() Note that that uses a 2.4 feature. The more portable - and obvious - way to write this is: datafile = open(file, w) for datum in datalist: datafile.write( .join(datum) + \n) datafile.close() For comma delimited files, there's the CSV module. It loads files formmated as Comma Seperated Values (a common interchange format for spreadsheets) into memory, and writes them back out again. This is a slightly more structured version of the simple text file approach. It may be just what you're looking for. If you want to store string objects selectable by a single string key, the various Unix db libraries are just what the doctor ordered. The underlying C libraries allow arbitrary memory chunks as keys/objects, but the Python libraries use Python strings, and dbms look like dictionaries. The shelve module is built on top of these, allowing you to store arbitrary Python objects instead of just strings. Finally, for RDBMS, you almost always get SQL these days. The options run from small embedded databases built in python to network connections to full-blown SQL servers. I'd put that decision off until you really need a database. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
urllib2 EOF occurred in violation of protocol with proxy
I want to connect to a https server through an authenticating proxy like this: import urllib2 proxy_info = { 'user' : 'me', 'pass' : 'password', 'host' : 'mycompany.com.au', 'port' : 8008 } # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({https:https://%(user)s:% (pass)[EMAIL PROTECTED](host)s:%(port)d % proxy_info}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) # install it urllib2.install_opener(opener) # use it f = urllib2.urlopen('https://www.securewebsite.com.au') print f.headers print f.read() f.close() If I modify the 'https' to 'http' it works fine. But in https mode it returns: URLError: urlopen error (8, 'EOF occurred in violation of protocol') The site works fine if I do not go through the proxy, so it appears the proxy is not returning an EOF. I been searching for an answer, and found many other sites where people have had the same problem. Some have suggested m2crypto. Is there a work around using the standard 2.4.1 installation? -- http://mail.python.org/mailman/listinfo/python-list
Re: processing a Very Large file
Mike Meyer wrote: Unknown. Python relies on the C alloc/free routines for handling memory. del may immediately free() the memory (I don't know), but that doesn't mean it gets released to the OS. None of the implementations of alloc/free I'm aware of ever give the memory back to the OS. They store it in a data structure for internal reuse. ... and in any serious OS, if memory is not reused it will eventually page out anyway, so the total cost of not releasing the memory back to the OS is miniscule (an entry or two in a page table) and the benefit of releasing it basically nil[*], while the effort of working out whether memory can be released or not is possibly quite significant. [* Excepting possible swap-space exhaustion, I suppose.] -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 EOF occurred in violation of protocol with proxy
Bloke [EMAIL PROTECTED] writes: The site works fine if I do not go through the proxy, so it appears the proxy is not returning an EOF. I been searching for an answer, and found many other sites where people have had the same problem. Some have suggested m2crypto. Is there a work around using the standard 2.4.1 installation? I sort of remember some problem like that with Microsoft web servers. It's not clear that a workaround is really the right thing--it's a security hole, it lets attackers truncate web pages coming through the proxy without your client app being able to tell the difference. OpenSSL includes an interactive SSL client (sort of like telnet) that can be convenient for trying stuff out without having to write code. Just type for example at the openssl prompt: OpenSSL s_client -connect www.yourhost.com 443 GET / HTTP/1.0 newline newline substituting whatever your host and port are. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Steve M [EMAIL PROTECTED] wrote http://mail.python.org/pipermail/python-dev/2005-January/051255.html discusses the problem with memory allocation in CPython. Apparently CPython is not good at, or incapable of, releasing memory back to the operating system. and unless your operating system is totally braindead, and thus completely unfit to run huge enterprise size applications, that doesn't really matter much. leaks are problematic, large peak memory use isn't. (fwiw, I'm tempted to argue that people who don't understand how memory allocation works on modern systems are unfit to run enterprise applications as well, but that's another story). btw, very few memory allocators release memory back to the operating system for small allocations; most memory allocators, including Pythons, do that for large allocations. try running this, and check the memory use after each step: x = 1000 * x y = x[1:] z = x[2:] del z del y del z still claiming that CPython's incapable of releasing memory back to the system? (finding the smallest multiplier that gives the same effect is left as an exercise etc.) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Ivan Van Laningham wrote: (snip) What you're going to run into are two major stumbling blocks. One, Python's got no credibility with management types unless the credibility's already there. Python? Never heard of it. Tell me about it. ... Oh, it's interpreted, is it? Interesting. Nope, Sir, it's byte-compiled just like Java. But you don't have to invoke the compiler yourself... You can see Python going down the sewer pipes, right on their faces. Two, security. This python sounds pretty interesting. Tell me about the security. How can we prevent people from stealing our source code, which we just spent millions developing? ... Hmm, trust the developers out there not to peek? Oh, sure, let's use it. Just like Java, which is so easy to reverse-engineer... (True, there are ways around the second, but you're going to have to talk _very_ fast and have ALL the answers before the management type gets to his/her office and shuts the door in your face and on your idea.) +1 -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: EpyDoc problem
EpyDoc is hosted in Sourceforge. This alone may answer your question about a bug-tracker: http://sourceforge.net/tracker/?atid=405618group_id=32455func=browse Well, I wrote to the bug tracker some days ago but no answer so far. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging problems
I thought I did, but when I checked today it seems I've screwed up and edited logging/__init__.py in 2.4 and tested with 2.3 So after fixing it in the correct place, it works nicely.. -- http://mail.python.org/mailman/listinfo/python-list
Re: self-promotion of the decorator module
Michele Simionato wrote: with the following advantages: 1. one-level of nesting is saved (flat is better than nested) 2. name, docstring and dictionary of the original function are preserved; 3. the signature of the original function is preserved (this one is nontrivial). And at least the following bugs: from decorator import * @decorator def chatty(f, *args, **kw): print Calling %r % f.__name__ return f(*args, **kw) @chatty def f((x,y)): pass Traceback (most recent call last): File pyshell#11, line 1, in -toplevel- @chatty File C:\Work\decorator\decorator.py, line 119, in __call__ return _decorate(func, self.caller) File C:\Work\decorator\decorator.py, line 89, in _decorate dec_func = eval(lambda_src, evaldict) File string, line 1 lambda ['x', 'y']: call(func, ['x', 'y']) ^ SyntaxError: invalid syntax I would have thought the code would be simpler if it used inspect.formatargspec to produce an argument list which is correctly formatted for all the weird corner cases: class Default: def __init__(self, n): self.n = n def __repr__(self): return 'defarg[%d]' % self.n def f(x, y=1, z=2, *args, **kw): pass a,v,vk,d = inspect.getargspec(f) inspect.formatargspec(a,v,vk,map(Default, range(len(d '(x, y=defarg[0], z=defarg[1], *args, **kw)' def g(x, (y,z)=(1,2), *args, **kw): pass a,v,vk,d = inspect.getargspec(g) inspect.formatargspec(a,v,vk,map(Default, range(len(d '(x, (y, z)=defarg[0], *args, **kw)' d ((1, 2),) Even if we manage to decorate the function, the decorated object has the wrong name in tracebacks: @chatty def f(): pass f(3) Traceback (most recent call last): File pyshell#15, line 1, in -toplevel- f(3) TypeError: lambda() takes no arguments (1 given) Using a lambda function here seems needlessly perverse. You know the name of the function you want to define and you are going to eval a string, so why not exec the string instead def %(name)s %(fullsign)s: call(func, %(shortsign)s) % getinfo(func) and then just pick the function out of the namespace after the exec? e.g. def _decorate(func, caller): Takes a function and a caller and returns the function decorated with that caller. The decorated function is obtained by evaluating a lambda function with the correct signature. lambda_src = def %(name)s(%(fullsign)s): call(func, %(shortsign)s) % getinfo(func) # print lambda_src # for debugging execdict = dict(func=func, call=caller, defarg=func.func_defaults or ()) exec lambda_src in execdict dec_func = execdict.get(func.__name__) dec_func.__doc__ = func.__doc__ dec_func.__dict__ = func.__dict__ return dec_func There is still a problem with this one though. If the function has arguments named 'call', 'func', or 'defarg' (or for that matter my code above introduces a new problem if the function is called by one of those names) nasty things will happen. Fortunately you have a list of argument names readily available so it shouldn't be too hard to generate unique names to use in their place. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to learn OO of python?
Steven Bethard: Thank you so much! Your answer is very very helpful~ On 5/19/05, Steven Bethard [EMAIL PROTECTED] wrote: could ildg wrote: I think decorator is a function which return a function, is this right? e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ arg %r does not match %s % (a,t) return f(*args, **kwds) new_f.func_name = f.func_name return new_f return check_accepts After I saw all the examples, I concluded that every decorator must define an inner function which takes only one argument, the function to decorate. Is this right? It's close, but not quite right. (I will use the word function for the moment, but see below for why this is inaccurate.) Every *decorator* must take only one argument, the function to decorate. It is not at all necessary that a decorator define an inner function. Consider (from [1]): def onexit(f): import atexit atexit.register(f) return f onexit is a decorator because it takes a function and returns a function. In this case, it happens to be that the same function is accepted and returned. Note that in the 'accepts' example above, *check_accepts* is the decorator, not accepts. The accepts function is actually a function that *returns* decorators. Now about that word function. Decorators are actually *callables* that accept a single *callable* and return a *callable*. Why does the terminology matter? Because I can construct decorators from classes too (from [2]): class memoized(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: return self.func(*args) Now the memoized decorator can be used just like any other decorator, e.g.: @memoized def fibonacci(n): if n in (0, 1): return n return fibonacci(n-1) + fibonacci(n-2) Note however that memoized is a *callable*, not a *function*. STeVe [1] http://www.python.org/peps/pep-0318.html [2] http://wiki.python.org/moin/PythonDecoratorLibrary -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the use of changing func_name?
Thanks to Robert Kern. You mean that though we can change the func_name of a function, but we still can't call it by func_name, and the func_name is only useful in some other circumstances? I also think so now after I have tried so many times on this puzzled func_name property. On 5/19/05, Robert Kern [EMAIL PROTECTED] wrote: could ildg wrote: Thank you for your help. I know the function g is changed after setting the func_name. But I still can't call funciton g by using f(), when I try to do this, error will occur: code g.func_name=f print g function f at 0x00B2CEB0 f() Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined /code Since the name of g is changed into f, why can't I call it by using f()? Should I call it using f through other ways? Please tell me. Thanks~ Others have answered this particular question, but you're probably still wondering what is the use of changing .func_name if it doesn't also change the name by which you call it. The answer is that there are tools that use the .func_name attribute for various purposes. For example, a documentation generating tool might look at the .func_name attribute to make the proper documentation. Actually, that's probably *the* biggest use case because I can't think of any more significant ones. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Paul Rubin wrote: 2) If you want to display a gif image in tkinter, you can make a frame object, put a canvas in it, and put a PhotoImage object onto the canvas, which works fine. But if you use your own subclass of frame (maybe to add your own gui stuff), for some reason the gif doesn't display in the canvas. did you read the PhotoImage documentation? see e.g. the note at the bottom of this page: http://effbot.org/zone/tkinter-photoimage.htm (this used to be explained in the Python FAQ too, but it looks as if that was lost in the great FAQ reorganization). /F -- http://mail.python.org/mailman/listinfo/python-list
datetime
L.S., It is very simple question: Why doesn't work the next statments? import datetime today = datetime.date.today() and I get the next error: today = datetime.date.today() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: time I can't understand it! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to learn OO of python?
Harlin Seritt [EMAIL PROTECTED] writes: I think I know what you mean. When I first started trying to learn the OOP aspect of Python I thought it was strange since I had started with OOP on Java and C++. Nonetheless, once you get the hang of it, OOP will make way more sense than all of the complications of Java and C++ class implementations. Let me give you a quick example of what I'm talking about: Um, there are some problems with your commentary. class Animal: def eats(self): print 'The animal eats.' def walks(self): print 'The animal walks.' Here the class Dog instantiates the class Animal. 'Dog' will 'do' whatever 'Animal' does plus some other things which we will describe in this class code. class Dog(Animal): #the self keyword means that this function will be a class function def communicate(self): print 'The dog barks.' First, the correct terminology is class *method*. Yes, it looks like a function definition, but it's a class method. Second, self isn't a keyword. It's just a name. You can name any variable self. The first argument to all class methods is a reference to the instance of the class that is invoking the method. It can have any name you want, but by convention in Python is called self. Consider the following: py class C: ... def say(my, message): ... print message ... py self = C() py self.say(hello) hello py Finally, *every* def inside a class statement creates a class method. You don't really need to worry about this, but will see it on the group. The method can be wrapped, and the defined name rebound to the wrapper, either via the decorator syntax or directly, using the classmethod and staticmethod functions. # __init__ function defines what # #will happen as soon as this class is instantiated. Also, the overloaded variable designators (color = None, fur = None) allow the instantiator to optionally define these variables when called from elsewhere. def __init__(self, color=None, fur=None): # this time self will designate the variable 'color' # as a class variable. self.color = color self.fur = fur These aren't variable designators, and they aern't overloaded. They are parementers, and they are given default values. This means they can be omitted from an invocation of the method, in which case the default values will be used. if __name__ == '__main__': sparky = Dog(color=White, fur=Short) sparky.communicate() print sparky.color print sparky.fur print sparky.eats() # Here sparky will access 'Animal' methods that 'Dog' inherited. print sparky.walks() # Another method originating from the 'Animal' class. What happens if you don't use 'self' inside your class code? You won't be able to access it within the class outside of the method where you initialized it. For instance, if you don't designate color with self then you can only use the 'color' variable within the __init__() method. This is useful whenever you want to use 'color' as a private variable. I'm not sure where to start here. self is a variable name. By convention, it's use is reserved for the first argument of methods, in which case it is passed the instance that is invoking the method. By assigning something to self.feature, you are assigning a value to an attribute - feature of this instance. This means it'll persist beyond the function existing. Assuming you have access to another object - let's call it foo - you can assign values to it's attributes in the same way, by assigning to foo.feature. Once made, such an assignment will persist until it's either changed, or the object foo ceases to exist. If you assign to a bare variable name - i.e., one with no dot - it will by default be local to that function. This means the variable will cease to exist when the function exits. Some details you should keep in mind, but can genarlly ignore: When the variable ceases to exist, the object it reference will lose a reference, which may or may not cause that object to cease to exist. You can cause an assignment to refer to a variable in the enclosing modules global name space with the global statement. Finally, if you referene a varaible rather than assigning to it, it's searched for in the enclosing scopes, out to the module global namespace. The same also goes for methods. Hopefully, you see how useful this can be down the road. This way you won't have to use variable/method access modifiers like Public, Private, Protected and so forth. If this doesn't make sense or you want more clarity, please let me know. Generally, methods are referred to by referring to a feature of an instance of an object. The first argument to the method is left off such an invocation, as the instance the method reference is attached to will be passed as that parameter. This is the way self.method works - it's a reference to a method of the instance that was used to invoke the currently executing method. Sometimes,
Re: datetime
Nader Emami [EMAIL PROTECTED] writes: L.S., It is very simple question: Why doesn't work the next statments? import datetime today = datetime.date.today() and I get the next error: today = datetime.date.today() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: time I can't understand it! It works fine here (Python 2.4.1 on FreeBSD 5-STABLE). Possibly you have a corrupt file? mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Fredrik Lundh [EMAIL PROTECTED] writes: did you read the PhotoImage documentation? see e.g. the note at the bottom of this page: http://effbot.org/zone/tkinter-photoimage.htm Thanks! I hadn't seen that. It explains what otherwise seemed completely bizarre. (this used to be explained in the Python FAQ too, but it looks as if that was lost in the great FAQ reorganization). I wouldn't have thought of looking there either. Do you think you could mention it in your Tkinter doc? That would be a logical place for it. -- http://mail.python.org/mailman/listinfo/python-list
Re: [pysqlite] pysqlite2.dbapi2.OperationalError: cannot commit transaction - SQL statements in progress
On Wed, May 18, 2005 at 09:41:39PM +0200, F. GEIGER wrote: I've troubles to let my app take off using pysqlite. What I wonder most for now is that pysqlite2.dbapi2.OperationalError: cannot commit transaction - SQL statements in progress when I do this: Urgh! I would have preferred simplified demo code. But after a little thinking, I guessed right. [...] pysqlite 2 currently has problems doing .commit() .rollback() on the connection object after a cur.execute(select ...) in a few cases. I know why and I will fix it in 2.0.2 (originally only MacOS X fixes planned) or if it takes longer to test, in 2.0.3. Current workarounds: - don't commit/rollback after SELECT. It doesn't make much sense anyway. .commit()/.rollback() after your DML statements instead (INSERT/UPDATE/DELETE). - Use fetchall()[0] for fetching single rows instead of fetchone() for queries like your SELECT COUNT. -- Gerhard -- Gerhard Häring - [EMAIL PROTECTED] - Python, web database development signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime
Nader Emami wrote: L.S., It is very simple question: Why doesn't work the next statments? import datetime today = datetime.date.today() Works on python 2.3.5 Mage -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov chain with extras?
[EMAIL PROTECTED] wrote: I want to use it for music. So given list 1 (melody), list 2 (chords) could be generated by a Markov chain. Also, given the chords the melody could be generated again by a chain. I have this small module, that can be used for markov chains. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science from random import random, randint from bisect import bisect class Randomizer: Various stochastic methods def inverse_scale(self, rng): Returns a list of probablitites corresponding to 1/i in range return [1.0 / (i + 1.0) for i in range(rng)] def n_scale(self, rng, n=2.0): Returns a list of probablitites corresponding to i/n n_scale = [] value = 1.0 for i in range(rng): value /= n n_scale.append(value) return n_scale class Selector: Returns random elements by probability according to their frequency def __init__(self, frequencies, elements): self.sum = sum(frequencies) acumulated_frequencies = [] acumulated_frequency = 0 for frequency in frequencies: acumulated_frequency += frequency acumulated_frequencies.append(acumulated_frequency) self.decorated = zip(acumulated_frequencies, elements) self.decorated.sort() def get(self): Randomly returns an element by probability rnd = random() * self.sum index = bisect(self.decorated, (rnd, 0)) return self.decorated[index][-1] def get_range(self, n): Randomly returns a range of elements by probability return [self.get() for itm in xrange(n)] class MarkovIn: Implements a Markov chain for arbitrary objects. The objects has same rules as dictionary keys to be valid. def __init__(self, key_size=1): key_size: how many steps in the chain self.key_size = key_size self.in_history = [] self.chain = {} def _update_chain(self, obj): Puts the object into the chain # shortcuts ch = self.chain # update the chain key = tuple(self.in_history) stat = ch.setdefault(key, {}) ch[key][obj] = stat.setdefault(obj, 0) + 1 def _update_history(self, obj): Updates the history his = self.in_history his.append(obj) if len(his) self.key_size: his.pop(0) def add_object(self, obj): Adds an object to the chain self._update_chain(obj) self._update_history(obj) def reset(self): Resets the history self.in_history = [] class MarkovOut: A Markov Chain wrapper. Generates a random walk from a markov chain. It is a seperate object for performance reasons. def __init__(self, markov): markov: A populated MarkovIn object self.markov = markov self.key_size = markov.key_size self.out_history = [] # Set up a cache of selector objects selectors = {} ch = self.markov.chain for key in ch.keys(): m = ch[key] selectors[key] = Selector(m.values(), m.keys()) self.selectors = selectors def _update_history(self, obj): Updates the history his = self.out_history his.append(obj) if len(his) self.key_size: his.pop(0) def step(self): A 'random' step from the chain, returns an object his = self.out_history key = tuple(his) obj = self.selectors[key].get() # keep track of history self._update_history(obj) new_key = tuple(his) self.handle_step(obj) if not self.selectors.has_key(new_key): # reset history and start over self.out_history = [] self.restart() def handle_step(self, obj): Handles a single step self.steps.append(obj) def do_walk(self, steps=1): returns A 'probable' walk self.steps = [] for itm in xrange(steps): self.step() def get_walk(self): Returns the walk return self.steps def _reset(self): Resets the history self.out_history = [] def restart(self): A hook for when a walk restarts pass if __name__ == '__main__': f = open('input.txt') text = f.read() lines = text.split('\n') mi = MarkovIn(1) for line in lines: mi.reset() words = line.split() for word in words: mi.add_object(word) class mo(MarkovOut): def __init__(self, markov_out): MarkovOut.__init__(self, markov_out) def restart(self): self.steps.append('\n\n') m = mo(mi) m.do_walk(100) print ' '.join(m.get_walk()) -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime
Why doesn't work the next statments? You talk like Yoda.. import datetime today = datetime.date.today() and I get the next error: today = datetime.date.today() Traceback (most recent call last): File stdin, line 1, in ? AttributeError: time I can't understand it! Understand it, I cannot too. Work fine, on my machine, the statements. -- http://mail.python.org/mailman/listinfo/python-list
Re: help with generators
Steven Bethard wrote: It would help if you explained what you expected. But here's code that prints about the same as your non-generator function. py def bin(n): ... s = [] ... def bin(n): ... if n == 0: ... yield s ... else: ... s.append(0) ... for s1 in bin(n - 1): ... yield s1 ... s.pop() ... s.append(1) ... for s1 in bin(n - 1): ... yield s1 ... s.pop() ... return bin(n) ... py for s in bin(1): ... print s ... [0] [1] py for s in bin(2): ... print s ... [0, 0] [0, 1] [1, 0] [1, 1] Note that to make the recursive calls work, you *must* iterate through them, thus what was in your code: bin(n - 1) now looks like: for s1 in bin(n - 1): yield s1 This is crucial. bin(n - 1) creates a generator object. But unless you put it in a for-loop (or call it's .next()) method, the generator will never execute any code. HTH, STeVe A caveat of the implementation above: it yields the same instance (s), which is unsafe if the loop variable is modified (e.g. in the for s in bin(n) loop, s should not be modified). Moreover, each yielded value should be 'consumed' and then discarded; attempting to store it (as in list(bin(n))) references only the last yielded value. Here's a shorter, clear and safe implementation: def bin2(n): if n: for tail in bin2(n-1): yield [0] + tail yield [1] + tail else: yield [] It also turns out to be faster than the original despite yielding a new list every time: $ python /usr/local/lib/python2.4/timeit.py -s from bin import bin for i in bin(10): pass 100 loops, best of 3: 5.21 msec per loop $ python /usr/local/lib/python2.4/timeit.py -s from bin import bin2 for i in bin2(10): pass 100 loops, best of 3: 2.68 msec per loop The reason is that the original computes the same permutations (for s1 in bin(n - 1)) twice. Here's a faster version that preallocates the list and sets the 0s and 1s for each permutation: def bin3(n): array = [None]*n def _bin(n): if not n: yield array else: n -= 1 for perm in _bin(n): # replace 'yield perm' with 'yield list(perm)' for safe # mutation and accumulation of yielded lists perm[n] = 0; yield perm perm[n] = 1; yield perm return _bin(n) $ python /usr/local/lib/python2.4/timeit.py -s from bin import bin3 for i in bin3(10): pass 1000 loops, best of 3: 587 usec per loop Cheers, George -- http://mail.python.org/mailman/listinfo/python-list
What's the difference between str and 'hello' ?
I am new to python. I was confused: a = list('hello') a ['h', 'e', 'l', 'l', 'o'] I want to combine the items in the list into a string. So: ''.join(a) 'hello' but: str.join(a) Traceback (most recent call last): File stdin, line 1, in ? TypeError: descriptor 'join' requires a 'str' object but received a 'list' So why TypeError raised? and What's the difference between str and 'hello' ? Thanks a lot. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython and wxtextctrl
Ok, as I guessed, it was Boa installation which changed the wxpython version used. I removed Boa... Thanks ! Nicolas Greg Krohn a écrit : Nicolas Pourcelot wrote: Hello, my script worked well until today : when I tried to launch it, I got the following : frame = MyFrame(None,-1,Geometrie,size=wx.Size(600,400)) File /home/nico/Desktop/wxGeometrie/version 0.73/geometrie.py, line 74, in __init__ self.commande.Bind(wx.EVT_CHAR, self.EvtChar) AttributeError: wxTextCtrl instance has no attribute 'Bind' (self.commande is a wxTextCtrl instance) I don't understand : why did wxTextCtrl lost its Bind attribute ?? As there's not so much changes on my computer since yesterday, I suppose this is due to Boa package installation on my Ubuntu Hoary ? Does Boa installation changes wxpython version ? Is wxTextCtrl attribute .Bind() obsolete ?? Thanks, Nicolas control.Bind is relativly new. The wxTextCtrl notation (vs wx.TextCtrl) is the old way (but it IS kept around for backwards compatablility). My guess is that your code is for for a newer version of wxPython than what you actually have. Try printing the version from in your code: import wxPyhon print wxPython.__version__ self.commande.Bind(wx.EVT_CHAR, self.EvtChar) -greg -- http://mail.python.org/mailman/listinfo/python-list
Re: self-promotion of the decorator module
Notice that the decorator module is at version 0.4 and I still consider it as experimental. The reason why I posted the link here is to get feedback and it seems I got it ;) I will upgrade to version 0.5 shortly, fixing the easily fixable bugs and documenting what cannot be easily fixed. Thanks for testing border cases I would have never imagined! Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Paul Rubin http://[EMAIL PROTECTED] writes: ... Do you think you could mention it in your Tkinter doc? That would be a logical place for it. Ehhh, specifically I meant it would be good to mention this in the PhotoImage example in Chapter 16 of An Introduction to Tkinter (The Canvas Image Item). That's the example I followed and was confused as heck why the image only appeared some of the time (I never saw it actually appear and then disappear, but that's just luck). Thanks again, I never would have figured this one out. -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime
I have the next on my machine: Python 2.3.3 (#1, Apr 6 2004, 01:47:39) [GCC 3.3.3 (SuSE Linux)] on linux2 Maybe this is a problem! Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between str and 'hello' ?
Am Donnerstag, 19. Mai 2005 11:27 schrieb hong Yu: str.join(a) Traceback (most recent call last): File stdin, line 1, in ? TypeError: descriptor 'join' requires a 'str' object but received a 'list' What's the difference between str and 'hello' ? str.join(,a) = .join(a) (= as in equivalence relation) HTH! -- --- Heiko. listening to: Bjork Guðmundsdottir Trio - Luktar-Gvendur see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/ pgpuGp5l6jjVT.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
john67 wrote: The company I work for is about to embark on developing a commercial application that will cost us tens-of-millions to develop. When all is said and done it will have thousands of business objects/classes, Ok, that sounds like a big app, but does it really have to be like that, or is that something you imagine because things usually get that complex using other tools? In my experience, development costs grow faster than linearly with class model size. (Of course, this is true regardless of programming language.) Prototyping things with Python is often an good way to discover simpler ways of handling a problem, and it's not unheard of that a Python prototype is good enough to keep as the final implementation. Thus, apart from the fact that you typically meed much less code to develop the same functionality in Python than in Java, you might also discover that you can do things in a smarter way which reduces you application size even more. There are plenty of descriptions of successful use of Python at: http://www.pythonology.com/ Of course, every language has a sweetspot, and particularly if you have a bunch of experienced Java developers who will think in Java idioms whatever language they code in, they might end up building a really stupid system in Python. Perhaps you should also read: http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html some of which will have hundreds-of-thousands of instances stored in a DB. That sounds like a moderately sized database.Hundreds of thousands of new entries per month might be big if you need to keep data for years, but this doesn't seem to be a limiting factor for you assuming a system which uses a real database backend. Our clients will probably have somewhere between 50-200 users working on the app during the day, possibly in mutiple offices, and then a large number of batch processes will have to run each night. This is not a problem in itself. There are a number of different ways to partition such a system between clients and different kinds of servers, but it can certainly be done in Python. It will also need to have a web interface for certain users. It needs to be robust, easy to maintain, and able to be customized for each client. This sounds like a good fit. Python is at least excellent for the customization part. I'll talk about how we do that here at Carmen Systems at the Europython conference in June. Slides will be available. Mail me if you want to have a look at a draft. We basically use Python for customization and use C++ for the core code. Python and C++ is a very good mix. Java and CPython might not be such a good fit, but that depends a bit what your intentions with Java is. (E.g. is JNI ok, or is hardware independence considered very important?) Java/Jython is a better pair of course, but Jython has few maintainers and is a few versions behind CPython. Right now it looks like Java is the language of choice that the app will be developed in. However, I have been looking and reading a lot about Python recently and it seems to me that Python could handle it. To be perfectly honest, I'd be very wary to stick out my neck and be a Python champion if my trust in Python was based only on reading... As a manager I'd also find it rather unconvincing... Let me put it this way: Python has a potential to make your system better, and to reach your goals in a shorter time. It fits very well with an agile approach, and in most systems of the kind I imagine you intend to build, agile development is very helpful in tracking project progress. You produce *real* programs early, not a lot of paperwork which a year later turns out to represent a misunderstanding of the actual problem, or how an effective solution should behave. I think it would be worthwile to investigate what Python could mean to you. It might certainly be very useful in the toolbox of the developers. It might be just a tool to aid in the development, it might be used as a glue language to connect interacting components written in other languages (Java, C++, C# etc), it might be an embedded macro language, a prototyping tool, or the implementation language for at least parts of the application. After all, one tool is unlikely to fit all tasks. Why not hire a well respected Python trainer for a few days, let a few developers learn Python and explore how it could fit into your system. The big attraction to me is the developer productivity. It seems that if Python can handle it, then we could gain a huge savings by using Python instead of Java from a productivity standpoint alone. Quite possible, but the choice of programming language(s) is just one of many very important decisions that determine the outcome of a software development project. So, given the very general requirements in the first paragraph, do you think that Python could handle it? If anyone has direct experience
Re: What's the difference between str and 'hello' ?
hong Yu wrote: I am new to python. I was confused: a = list('hello') a ['h', 'e', 'l', 'l', 'o'] I want to combine the items in the list into a string. So: ''.join(a) 'hello' but: str.join(a) Traceback (most recent call last): File stdin, line 1, in ? TypeError: descriptor 'join' requires a 'str' object but received a 'list' So why TypeError raised? and What's the difference between str and 'hello' ? Thanks a lot. str is a class, 'hello' is instance of the class; the method join expects to receive an instance as its first parameter so:- str.join( '', a ) 'hello' Regards, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
brian == brian [EMAIL PROTECTED] writes: brian to build expertise and confidence, etc. People are more brian important than programming language. Or so you would think before writing sizeable software in C++. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: self-promotion of the decorator module
Duncan Booth: Fortunately you have a list of argument names readily available so it shouldn't be too hard to generate unique names to use in their place. It does not look too simple either. Whereas I can easily build valid Python identifiers which are extremely unlikely to clash with any identifier I can have in my program, it seems impossible to get an identifier which cannot be shadowed later . What about renaming name- _name_, call - _call_, func- _func_, defarg-_defarg_ and checking that the argument list does not contain such reserved names by means of an assert statement? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
len wrote: I am an old time cobol programmer from the IBM 360/370 eria and this ingrained idea of file processing using file definition (FD's) I believe is causing me problems because I think python requires a different way of looking at datafiles and I haven't really gotten my brain around it yet. Yup, Python uses the same world view as C, C++, Unix etc. I would like to create a small sequential file, processing at first to store a group id, name, amount, and date which I can add to delete from and update. Could someone point me to some code that would show me how this is done in python. Eventually, I intend to expand my little program to process this file as a flat comma delimited file, move it to some type of indexed file and finally to some RDBMS system. My little program started out at about 9 lines of code and is now at about 100 with 5 or six functions which I will eventually change to classes (I need to learn OOP to but one step at a time). I think it's much easier to go directly to SQL without those diversions. In a way, an SQL database maps better to your idea of files / records, and it just takes much less code and effort to use SQL than to twist normal (for me) files into behaving like main frame dittos. I'd suggest that you download pysqlite. Then you have a small embedded SQL database in your python program and don't need to bother with a server. See http://initd.org/tracker/pysqlite Another obvious solution, since you are saying that it's a small file, is to always read the whole file into memory, and to rewrite the whole file when you change things. For info in CSV handling, see http://docs.python.org/lib/module-csv.html For other non-SQL solutions, please have a look at http://www-106.ibm.com/developerworks/library/l-pypers.html and http://docs.python.org/lib/node77.html -- http://mail.python.org/mailman/listinfo/python-list
RE: Is Python suitable for a huge, enterprise size app?
That is why you can distribute only the .pyc files and not the .py files. This would be like distributing the .class files and not giving out the .java files. I had this issue at a company in the late 1980's and why I submitted the patches to make Python not require the .py files if the .pyc files existed. Now days, you can go one step further and zip up the .pyc files into a single zip file and distribute that instead of individual .pyc files. If you really want to go further, you can also modify the module loading code and encrypt the .pyc files when they are generated from the .py files. Your module loading code can then decrypt the .pyc files at load time. Lance Ellinghaus I speak for myself and not for the company I work for. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Maurice LING Sent: Thursday, May 19, 2005 8:20 AM To: python-list@python.org Subject: Re: Is Python suitable for a huge, enterprise size app? You can see Python going down the sewer pipes, right on their faces. Two, security. This python sounds pretty interesting. Tell me about the security. How can we prevent people from stealing our source code, which we just spent millions developing? ... Hmm, trust the developers out there not to peek? Oh, sure, let's use it. Just like Java, which is so easy to reverse-engineer... It makes big difference (legally) to if the codes are there and someone sees it, to if the codes are locked in some packaged or zipped form and someone reverse-engineer it. It is legally as different as if you drop money on the ground and I pick it up, to pick-pocketing you and take the money. Nobody seems to be able to understand this simple logic. Yes, Java class files can be reverse-engineered quite easily but the act of doing that is criminal, unless performed under specified Council Directives (in EU) or under any statutory law in specific countries. But the act of looking at the codes if it is there is not criminal, just like reading a book in bookstore. If anyone can program in binary today, no codes will be safe with them anyway... maurice -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
George Sakkis [EMAIL PROTECTED] wrote: Another issue that hasn't been mentioned so far is staffing. You can find java programmers and software engineers a dime dozen, but for python it will be harder. Yes, there are a lot more people out there who put Java on their resume than put Python on their resume. Most of those so-called Java programmers write total crap. Of course, there's a lot of crap written in Python too. But since there're a lot more Java programmers out there, it stands to reason that there's a lot more crappy Java programmers too. It's a lot easier to teach a good programmer Python than it is to teach a crappy programmer good software engineering skills. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
In article [EMAIL PROTECTED], vincent wehren [EMAIL PROTECTED] wrote: . . . If the application is really huge, you should consider using a set of programming languages that do the particular job best. That is, go for a complementary, concurrent approach in your choice of programming languages. I wouldn't want to religiously stick to any one language just for the sake of being religious. . . . How embarrassing--I've followed up twice in this thread already, and utterly failed to mention this. YES! The question should never be, What one language is least imperfect for our requirements?, but rather, What specific combination of languages best fits our situation? I'll refer again to Phaseit's deliveries: we *always* are working in multiple languages. If we had responsibility for the project the Original Poster described, I suspect we'd involve Python and C++, or Jython and Java, and of course SQL and XHTML, and ... At this level, part of my endorsement of Python has to do with its propensity to play nicely with others. As others have written, though, it would be rather ... ambitious to commit tens of millions of dollars to a language with which the organization is almost entirely unfamiliar. 'Course, Big Organizations do that all the time, without realizing it ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing 2 similar strings?
On Thu, 19 May 2005 06:38:59 +1000, John Machin [EMAIL PROTECTED] wrote: On Wed, 18 May 2005 15:06:53 -0500, Ed Morton [EMAIL PROTECTED] wrote: William Park wrote: How do you compare 2 strings, and determine how much they are close to each other? Eg. aqwerty qwertyb are similar to each other, except for first/last char. But, how do I quantify that? However you like is probably the right answer, but one way might be to compare their soundex encoding (http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?soundex) and figure out percentage difference based on comparing the numeric part. Fantastic suggestion. Here's a tiny piece of real-life test data: compare the surnames Mousaferiadis and McPherson. I remember a word processor, MultiMate, which used Soundex to do matching for its suggestions for spelling correction. One of my cow-orkers typed the word 'agains' -- it was supposed to be 'against' but 'again' would also have been a sensible suggestion. MultiMate, however, suggested neither of those reasonable words, it did suggest iguanas amd Utahns... (I wonder what it does with Talliafero and Tolliver, and with Featherstone-Howe and Fanshaw...) The answer to the OP, which someone just pointed out to me on comp.programming, is edit distance or Levenshtein Distance[1]. A google search on either produces some good descriptions in the first few links, including http://www.merriampark.com/ld.htm which has not only a description of the algorithm but also source code in Java, C++ and Visual Basic (no Awk, thought there are links to pages with implementations in Perl, Python, Delphi and many more)... [1] I would have spelt it 'Levenstein', and pronounced it 'Levenshtein' in Schwaebisch (south German) fashion, but apparently the author of the algorithm was one Vladimir I. Levenshtein and that is how he is credited on the IEEE site. There are also a number of Google hits under the 'stein' spelling, though... Chris C -- http://mail.python.org/mailman/listinfo/python-list
Re: Python forum
Ivan Van Laningham wrote: Robert Kern wrote: dict.org says _forums_. I used _fora_, but I'm silly. It also says appendixes and indexes are OK. Yahoos. Should that be Yaha? -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for bored python newbies
Never mind this was a stupid question -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
#! rnews 1636 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!newsfeeder.wxs.nl!textfeed1.on.meganewsservers.com!meganewsservers.com!feeder2.on.meganewsservers.com!216.196.98.140.MISMATCH!border1.nntp.dca.giganews.com!border2.nntp.dca.giganews.com!nntp.giganews.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George [EMAIL PROTECTED] Subject: Re: NaN support etc. X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=iso-8859-1 Message-ID: [EMAIL PROTECTED] User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 38 Sender: [EMAIL PROTECTED] Content-Transfer-Encoding: 8bit Organization: The Boeing Company References: [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] Mime-Version: 1.0 Date: Thu, 19 May 2005 13:14:32 GMT Xref: news.xs4all.nl comp.lang.python:378109 Sébastien Boisgérault [EMAIL PROTECTED] writes: Martin v. Löwis a écrit : Andreas Beyer wrote: How do I find out if NaN, infinity and alike is supported on the current python platform? [snip] But, practically, I have never found a platform where the following fpconst-like code did not work: import struct cast = struct.pack big_endian = cast('i',1)[0] != '\x01' if big_endian: nan = cast('d', '\x7F\xF8\x00\x00\x00\x00\x00\x00')[0] else: nan = cast('d', '\x00\x00\x00\x00\x00\x00\xf8\xff')[0] Can anybody provide an example of a (not too old or exotic) platform where this code does not behave as expected ? Cheers, SB I use fpconst too. I've been concerned that its source home seems to wander. Any chance of it being added to the base distro? -- [EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
#! rnews 2056 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!border2.nntp.ams.giganews.com!nntp.giganews.com!fi.sn.net!newsfeed2.fi.sn.net!newsfeed3.funet.fi!newsfeed1.funet.fi!newsfeeds.funet.fi!newsfeed1.swip.net!swipnet!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George [EMAIL PROTECTED] Subject: Re: ElementTree and xsi to xmlns conversion? 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.4 Lines: 43 Sender: [EMAIL PROTECTED] Organization: The Boeing Company References: [EMAIL PROTECTED] [EMAIL PROTECTED] Mime-Version: 1.0 Date: Thu, 19 May 2005 13:24:58 GMT Xref: news.xs4all.nl comp.lang.python:378110 Fredrik Lundh [EMAIL PROTECTED] writes: [snip] are you sure? the prefix shouldn't matter; it's the namespace URI that's important. if you're writing code that depends on the namespace prefix rather than the name- space URI, you're not using namespaces correctly. when it comes to namespaces, elementtree forces you to do things the right way: http://www.jclark.com/xml/xmlns.htm (unfortunately, the XML schema authors didn't understand namespaces so they messed things up: http://www.w3.org/2001/tag/doc/qnameids-2002-04-30 to work around this, see oren's message about how to control the namespace/prefix mapping. in worst case, you can manually insert xsi:-attributes in the tree, and rely on the fact that the default writer only modifies universal names) /F First, thanks for ElementTree and cElementTree. Second, I've read the docs and see a lot of examples for building trees, but not a lot for traversing parsed trees. Questions: 1. Is there a good idiom for namespaces? I'm currently doing things like: UML='{href://org.omg/UML/1.3}' packages=ns2.findall(UML+'Package') 2. Is there a similar idiom which works for Paths? I've tried: packages=pkg1.findall(UML+'Namespace.ownedElement/'+UML+'Package') but haven't found the right combination, so I do step-at-a-time descent. -- [EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Maurice LING wrote: It makes big difference (legally) to if the codes are there and someone sees it, to if the codes are locked in some packaged or zipped form and someone reverse-engineer it. It is legally as different as if you drop money on the ground and I pick it up, to pick-pocketing you and take the money. Nobody seems to be able to understand this simple logic. So you're saying that reverse engineering Java bytecode is illegal, while doing the same with Python bytecode is not? Or something like that? (And you're a lawyer, right? Because if you're not, and you're not citing your sources, why is it we should put any value in these comments about what is (legally) true?) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python forum
Hi All-- Peter Hansen wrote: Ivan Van Laningham wrote: Robert Kern wrote: dict.org says _forums_. I used _fora_, but I'm silly. It also says appendixes and indexes are OK. Yahoos. Should that be Yaha? g Nope. I appreciate the sentiment, but Yahoo is neither Latin nor Greek. Instead, it was invented by Jonathan Swift for _Gulliver's Travels_, published in 1726; since it is a made-up English word, it follows the rules of English. Metta, Ivan -- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours -- http://mail.python.org/mailman/listinfo/python-list
Re: socket programming and port scans
rbt wrote: I don't fully understand sockets, I just know enough to be dangerous. The below is not detected by nmap, but is affected by iptables or ipsec. Can anyone explain why that is? s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((ip_param, port_param)) while 1: s.listen(5) This, by the way, is wrong. s.listen(5) just tells the stack that you would like to allow a backlog of up to 5 waiting-to-be-connected connection attempts while you are accepting another. The call doesn't block and needn't be called repeatedly. You could just as well do the call to listen first, then have an empty while 1: pass loop (but note that in either case it is a busy wait, consuming 100% CPU while it runs). What you are looking for is more like this: s.listen(5) while 1: s.accept() # wait for connection, and ignore it If you want to simulate a little server to allow multiple connections, you would of course need to use the value returned by accept() and probably call close() on the client socket right away. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
Thanks for the reply. I just read your response and will be taking your suggestion immediatly Len Sumnler -- http://mail.python.org/mailman/listinfo/python-list
ssl issues with socket timeout
Hello, anyone knows a way to deal with this problem ? http://sourceforge.net/tracker/index.php?func=detailaid=1153016group_id=5470atid=105470 This bug has been fixed in 2.3 but there is a regression in 2.4 Tarek -- Tarek ZIADE, Nuxeo SARL: Zope Service Provider. Mail: [EMAIL PROTECTED] - Tel: +33 (0)6 30 37 02 63 Nuxeo Collaborative Portal Server: http://www.nuxeo.com/cps Gestion de contenu web / portail collaboratif / groupware / open source -- http://mail.python.org/mailman/listinfo/python-list
Convert from numbers to letters
Hi All, While I know there is a zillion ways to do this.. What is the most efficient ( in terms of lines of code ) do simply do this. a=1, b=2, c=3 ... z=26 Now if we really want some bonus points.. a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc.. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
Thanks for the reply I think you might be right. I have been playing around with Linux at home. What I may have to do in switch my mindset from IBM/Microsoft to a more Unix way of thinking. Also thanks for the code samples. Len Sumnler -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
Thanks for the reply Everyone seems to be saying the same thing which is jump into some RDBM. Len Sumnler -- http://mail.python.org/mailman/listinfo/python-list
Re: help with generators
Thanks a lot! This clarified [I think] my misunderstanding about yield, and I also learned something about efficiency from George's code -- Thanks. So, The function tel(aString) takes a string (or a number) that denote a phone number, using digits or letters, and returns a generator for the set of all possible words that are made up of that phone number. It's not a terribly useful program, but it's short and it's a lot of fun. Mayer import string def addKeyString(keyString): for ch in keyString: keypad[ch] = keyString keypad = {} addKeyString('0') addKeyString('1') addKeyString('2ABC') addKeyString('3DEF') addKeyString('4GHI') addKeyString('5JKL') addKeyString('6MNO') addKeyString('7PQRS') addKeyString('8TUV') addKeyString('9WXYZ') def tel(phone): phoneString = str(phone) length = len(phoneString) buffer = [Null] * length def run(n): if n == length: yield string.join(buffer, '') else: for word in run(n + 1): for letter in keypad[phoneString[n]]: buffer[n] = letter yield buffer return run(0, '') -- http://mail.python.org/mailman/listinfo/python-list
Re: help with generators
George Sakkis wrote: Steven Bethard wrote: py def bin(n): ... s = [] ... def bin(n): ... if n == 0: ... yield s ... else: ... s.append(0) ... for s1 in bin(n - 1): ... yield s1 ... s.pop() ... s.append(1) ... for s1 in bin(n - 1): ... yield s1 ... s.pop() ... return bin(n) ... [snip] A caveat of the implementation above: it yields the same instance (s), which is unsafe if the loop variable is modified (e.g. in the for s in bin(n) loop, s should not be modified). Moreover, each yielded value should be 'consumed' and then discarded; attempting to store it (as in list(bin(n))) references only the last yielded value. Yup. However, this was the most direct translation of the OP's original function (which also only had a single list). Since the question was about how generators worked, I figured the most direct translation would probably be the most useful response. Here's a shorter, clear and safe implementation: def bin2(n): if n: for tail in bin2(n-1): yield [0] + tail yield [1] + tail else: yield [] This is definitely the way I would have written it. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
On 19 May 2005 06:56:45 -0700, rh0dium [EMAIL PROTECTED] wrote: Hi All, While I know there is a zillion ways to do this.. What is the most efficient ( in terms of lines of code ) do simply do this. a=1, b=2, c=3 ... z=26 (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) = range( 1, 27 ) Now if we really want some bonus points.. a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc.. It's still one line, following the pattern from above, just longer. Now why do you want to do this? Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
I am interested in any further progress with this, you may have made? I am facing a similar issue. In short, I need to connect to a https site (in this case a WSDL) that I need to access through an Http proxy. I have tried various things to no avail. I did find a couple recipes on the ASPN python cookbook that talk about tunneling via a CONNECT request is what I believe I need to do. The recipes are: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/301740 this particular example establishes the proxy connection and then issues the connect request to establish the connection to the https site, then tries to establish an SSL Socket connection to the proxy then talk through it to get the data from the https via the proxy, I get the same EOF error when I run this sample with our proxy.. The other recipe I looked at was: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213238 This is a tunneling mechanism. When I try this, I basically get nowhere in other words, the get request never gets picked up by the various socket/servers setup to do the tunneling and it just loops around seemingly forever.. I am running on Windows XP if that matters. Of course, Mozilla and I.E. work fine accessing the https site in question via our proxy. In short, I simply need to connect to a http proxy and through it get at a url which is an https. I do not need any user name or password etc. to get to the site. The standard Python libraries fail as the GET request through the proxy is dismissed as a bad request. Any help is greatly appreciated. - Andrew Bushnell Bloke wrote: Thanks Martin. The problem seems to lie with our company proxy (which requires authentication). I have tried retrieving the page on another network with a transparent proxy, and it all works fine. Unfortnately, any https page I try to retrieve on the company network fails in this way with after a long period of inactivity. However, I can retrieve the page using a standard browser through the same company network. I think there must be something weird going on with our proxy server. -- Andrew Bushnell Lead Development Engineer Fluent Inc. 10 Cavendish Court Centerra Resource Park Lebanon, NH 03766 [EMAIL PROTECTED] Phone: 603-643-2600, ext. 757 Fax: 603-643-1721 www.fluent.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
On 19 May 2005 06:56:45 -0700, rh0dium [EMAIL PROTECTED] wrote: Hi All, While I know there is a zillion ways to do this.. What is the most efficient ( in terms of lines of code ) do simply do this. a=1, b=2, c=3 ... z=26 Now if we really want some bonus points.. a=1, b=2, c=3 ... z=26 aa=27 ab=28 etc.. just for fun, here is one way to do it with a listcomp. Obfuscated python fans, rejoice! alpha = 'abcdefghijklmnopqrstuvwxyz' for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha \ for y in [''] + [z for z in alpha]], key=len)): ... locals()[digraph] = i + i ... a 1 b 2 ac 29 dg 111 zz 702 26**2 + 26 702 Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
Paul Rubin wrote: Kay Schluehr [EMAIL PROTECTED] writes: To answer Your initial question: there is probably no technical reason against Python as a language or the CPython runtime. Both are very stable and mature. I'd like to agree with this but I just can't. Python is a great language for prototyping and trying stuff out. It's fast and pleasant to write. But you're right when you say that constant testing and integration is absolutely necessary to develop anything substantial in Python. [snip] I'm in the middle of prototyping something in Python and it's going pretty well despite occasional snags like those mentioned above. But at the end of the day I don't think what we get will be solid enough for use in production. We're planning to use the Python prototype to get the feature set and protocols figured out, then reimplement in Java. The OP might consider that approach. You bring up some good points and I imagine the bugs you've encountered are pretty frustrating, but I'm surprised at how different our experience has been. I know my comments about Python probably come across a total fan boy - but for us Python has been extremely positive. We currently use Python, in production, in the following ways: - custom HTTP web servers - custom HTTP proxies - behind-the-scenes log processors and other operational tools - several Zope-based applications, both internally and externally facing - both the client and server sides of a distributed work cluster - the client side of a media encoding farm (server is a Zope app) - a downloadable Windows client that our customer's customers use, that includes a Windows COM server (an ActiveX control we implemented using ctypes). Most of these have been in production for a year or more, with the oldest being about 4 years (not a long time, but certainly long enough to be considered stable). The toughest pieces initially were the Zope apps and the Windows COM stuff - Zope because of documentation and COM because, well, it's COM. During that time, the biggest problem we had with Python and its standard libraries was one issue with socket.recv and memory allocation when doing lots of receives. That lost us a few days of hunting for a memory leak, but we were able to resolve it by looking at the C source. Another problem was the need to call unlink (or something like that) on XML minidom elements in some circumstances. Apart from that, we haven't encountered much of anything in terms of bugs in the language or the standard library in *years*. In fact, I don't recall encountering a bug in the language itself. We've generally trailed the standard Python releases by about a year (although this week I moved the encoding farm to Python 2.4.1, which is half a year early). We don't use Tkinter. We don't use much outside the standard library: we make heavy use of ctypes, psycopg (Postgres), and lately CherryPy, but that's about it. So for us, the number of bugs in Python + stdlib has been really low. One thing from your experience that did resonate with me is that, except for ftplib and occasionally urllib (for basic, one-shot GETs), we don't use any of the standard library's protocol modules - partly because we had to implement our own HTTP libraries for performance and scalability reasons anyway, and partly because we had trouble figuring out e.g. all the ins and outs of urllib/urllib2/httplib. Overall it's been such a positive experience for us that nobody in the company - from grunt testers up to the CTO - has any reservations about using Python in production anymore (even though initially they all did). All of the developers have previous experience with using Java in production systems, and none seriously consider it for new projects at all. -Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie file/DB processing
len [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am an old time cobol programmer from the IBM 360/370 eria and this ingrained idea of file processing using file definition (FD's) I believe is causing me problems because I think python requires a different way of looking at datafiles and I haven't really gotten my brain around it yet. Welcome, Len. I would like to create a small sequential file, processing at first to store a group id, name, amount, and date which I can add to delete from and update In addition to the suggestions already given, you might take a look at the struct module. This will let you use fixed-width binary records. The concept of streams found in UNIX takes some getting used to. Many files are maintained as text using delimited, variable length fields with a newline at the end. Try 'cat /etc/passwd' on a UNIX/Linux host to see such a file using a colon ':' as the delimiter. I turn to the 'od' command when I want the truth. Use it to see what bytes are -really- in the file. The following should work on Linux or under Cygwin if you are still using Windows. od -Ax -tcx1 thefile.dat You can use od to look at data in the stream. The output of the print command is going into the od command. $ print now|od -Ax -tcx1 00 6e 6f 77 0a n o w \n 6e 6f 77 0a 04 -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing 2 similar strings?
On Thu, 19 May 2005 07:07:56 +1000, John Machin wrote: On Wed, 18 May 2005 13:45:30 -0700, Don [EMAIL PROTECTED] wrote: http://www.personal.psu.edu/staff/i/u/iua1/python/apse/ The above is broken, not meeting one of the elementary conditions for a distance metric: distance(a, b) == distance(b, a) I agree that this makes the edit distance broken in the context of text strings, but you should be aware that distance is only commutative if there are no constraints on travel. If you've ever driven around cities like Sydney that use lots of one-way streets, you will know that the distance from point A to point B is not necessarily the same as the distance from B back to A. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Twisted an several CPUs
Hi, Out of sheer curiosity: Does Twisted scale if the server has several CPUs? As far as I know twisted uses one interpreter. This means a prefork server modul might be better to server database driven web-apps. Has anyone experience high load and twisted? Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing 2 similar strings?
On Thu, 19 May 2005 14:09:32 +1000, John Machin wrote: None of the other approaches make the mistake of preserving the first letter -- this alone is almost enough reason for jettisoning soundex. Off-topic now, but you've made me curious. Why is this a bad idea? How would you handle the case of barow and marow? (Barrow and marrow, naturally.) Without the first letter, they sound identical. Why is throwing that information away a good thing? Thanks, -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: self-promotion of the decorator module
Michele Simionato wrote: Duncan Booth: Fortunately you have a list of argument names readily available so it shouldn't be too hard to generate unique names to use in their place. It does not look too simple either. Whereas I can easily build valid Python identifiers which are extremely unlikely to clash with any identifier I can have in my program, it seems impossible to get an identifier which cannot be shadowed later . What about renaming name- _name_, call - _call_, func- _func_, defarg-_defarg_ and checking that the argument list does not contain such reserved names by means of an assert statement? I'm not sure I see the problem. You only have to pick names which are not the name of the current function not any of its arguments. These names get substituted into the string used to define the function which is exec'ed in its own private namespace. So long as they are unique within that namespace there shouldn't be a problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: self-promotion of the decorator module
Yep, I was wondering about irrelevant things, there is no problem in this case, actually. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie running IDLE with command line arguments
Hmm, I submitted an earlier message, but something seems to have gone wrong. Try this: import sys usingIdle = 0 for eachPath in sys.path: if eachPath.find(idlelib): usingIdle = 1 break if usingIdle: host=localhost port=2000 msg=Hello world else: host, port, message = sys.argv[1], int(sys.argv[2]), sys.argv[3] import sys, socket size = 1024 print host -- http://mail.python.org/mailman/listinfo/python-list
Re: Python forum
Ivan Van Laningham wrote: Hi All-- Peter Hansen wrote: Ivan Van Laningham wrote: Robert Kern wrote: dict.org says _forums_. I used _fora_, but I'm silly. It also says appendixes and indexes are OK. Yahoos. Should that be Yaha? g Nope. I appreciate the sentiment, but Yahoo is neither Latin nor Greek. Instead, it was invented by Jonathan Swift for _Gulliver's Travels_, published in 1726; since it is a made-up English word, it follows the rules of English. Yeeha, possibly? regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter special math chars
I wrote the following code: import Tkinter t = Tkinter.Label() t.configure( text=uAs the function approaches \N{INFINITY}, \N{HORIZONTAL ELLIPSIS}) t.pack() t.mainloop() It worked for me on Windows NT 4.0 with Python 2.4, and on RedHat 9 with a self-compiled Python 2.3, showing an infinity symbol and an ellipsis. u'\N{...}' stands for the Unicode character named '...'. Unicode.org (and other sites) have lists of Unicode character names. Tk tries very hard to find the requested character in some font available on the system, but when it fails it just displays a unicode escape sequence like \u220e (instead of the END OF PROOF symbol, in this case), and there's really no way for Python to find out and fall back in some graceful way. Relying on this behavior, here's a somewhat-falliable way to detect the presence of a symbol in the font used in a given widget: def symbol_exists(s, w, f = None): if f is None: f = w.cget(font) width_symbol = w.tk.call(font, measure, f, s) width_bench = w.tk.call(font, measure, f, 000) return width_symbol width_bench This finds the width in pixels of the given symbol (s) and the string 000, in the font f. If the width of the symbol is smaller, then it's probably available. If it's wider, then it's probably rendered as an escape sequence like \u220e. This is falliable because there's no guarantee that the symbol would not be as wide as 000, but also it's possible for some escape code (say \u) to be narrower than 000. Neither of these seem very likely in practice. Jeff pgpCovRiRsUh0.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Bill Mill wrote: py alpha = 'abcdefghijklmnopqrstuvwxyz' py for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha ...for y in [''] + [z for z in alpha]], key=len)): ... locals()[digraph] = i + i ... It would probably be better to get in the habit of writing globals()[x] = y instead of locals()[x] = y You almost never want to do the latter[1]. The only reason it works in this case is because, at the module level, locals() is globals(). You probably already knew this, but I note it here to help any newbies avoid future confusion. Steve [1] For 99% of use cases. Modifying locals() might be useful if you're just going to pass it to another function as a dict. But I think I've seen *maybe* 1 use case for this. -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
Andrew, It seems I'm not the only one going nuts here. I have just spent the last 4 hrs stepping through the code in the debugger. It seems to get stuck somewhere in the socket module (when it calls ssl) but haven't as yet figured out exactly where. I am _very_ interested to find that you have the same prob with a non-authenticating proxy. I had considered I was doing something wrong with the authentication, but from what you say, and from what I have deduced from the code, it is not the authentication that is at fault. Like you, a standard browser works fine, so I'm inclined to think there is something buggy with the way the sockets module talks to the proxy. There has been some suggestion that it may me a 'Microsoftish' proxy which is at fault, but I believe it is a Squid proxy our company uses. There is an interesting note here ( http://www.squid-cache.org/Doc/FAQ/FAQ-11.html setcion 11.34 ) regarding malformed https requests sent through Squid with buggy clients. It may be worth looking into. Anyway, if you have any luck, _please_ let me know - I'm getting desparate. -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
Thanks for the update. I will/can keep you posted. I know for a fact we use a Squid proxy which sounds like what you are using. I am going to check out the faq you sent and see what it comes up with. I have also been perusing the net a bit and looking at other client packages and see if they work, such as cURL etc. Thanks, Andrew Bloke wrote: Andrew, It seems I'm not the only one going nuts here. I have just spent the last 4 hrs stepping through the code in the debugger. It seems to get stuck somewhere in the socket module (when it calls ssl) but haven't as yet figured out exactly where. I am _very_ interested to find that you have the same prob with a non-authenticating proxy. I had considered I was doing something wrong with the authentication, but from what you say, and from what I have deduced from the code, it is not the authentication that is at fault. Like you, a standard browser works fine, so I'm inclined to think there is something buggy with the way the sockets module talks to the proxy. There has been some suggestion that it may me a 'Microsoftish' proxy which is at fault, but I believe it is a Squid proxy our company uses. There is an interesting note here ( http://www.squid-cache.org/Doc/FAQ/FAQ-11.html setcion 11.34 ) regarding malformed https requests sent through Squid with buggy clients. It may be worth looking into. Anyway, if you have any luck, _please_ let me know - I'm getting desparate. -- Andrew Bushnell Lead Development Engineer Fluent Inc. 10 Cavendish Court Centerra Resource Park Lebanon, NH 03766 [EMAIL PROTECTED] Phone: 603-643-2600, ext. 757 Fax: 603-643-1721 www.fluent.com -- http://mail.python.org/mailman/listinfo/python-list
Self-modifying Code
Hi all, when I was young I programmed in an interpreted language that allowed to modify itself. Also Python can (writing and running a module, in-line): fNew =open(newModule.py,'w') lNew=['print 123\n','print 454\n','print 789\n'] fNew.writelines(lNew) fNew.close() from newModule import * Running this small example it correctly displays: 123 456 789 Did you know? Certainly someone has already discovered and applied that, because the applications are several (think only to the possibility of reducing code length by eliminating the coding of false alternatives, or the possibility to convert a list of instructions taken somewhere in a running code...) Bye. -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
Hi! HTTPS over a proxy (CONNECT) hasn't worked for a long time in python (actually it has never worked). A quick glance at the 2.4 Changelog doesn't suggest that this has been fixed. So basically you've got the following options: a) redo your own http/https support. b) look around on the net for some patches to httplib (google is your friend) be aware that these are quite old patches. c) using some external solution, like pycURL. Andreas On Thu, May 19, 2005 at 12:53:11PM -0400, Andrew Bushnell wrote: Thanks for the update. I will/can keep you posted. I know for a fact we use a Squid proxy which sounds like what you are using. I am going to check out the faq you sent and see what it comes up with. I have also been perusing the net a bit and looking at other client packages and see if they work, such as cURL etc. Thanks, Andrew Bloke wrote: Andrew, It seems I'm not the only one going nuts here. I have just spent the last 4 hrs stepping through the code in the debugger. It seems to get stuck somewhere in the socket module (when it calls ssl) but haven't as yet figured out exactly where. I am _very_ interested to find that you have the same prob with a non-authenticating proxy. I had considered I was doing something wrong with the authentication, but from what you say, and from what I have deduced from the code, it is not the authentication that is at fault. Like you, a standard browser works fine, so I'm inclined to think there is something buggy with the way the sockets module talks to the proxy. There has been some suggestion that it may me a 'Microsoftish' proxy which is at fault, but I believe it is a Squid proxy our company uses. There is an interesting note here ( http://www.squid-cache.org/Doc/FAQ/FAQ-11.html setcion 11.34 ) regarding malformed https requests sent through Squid with buggy clients. It may be worth looking into. Anyway, if you have any luck, _please_ let me know - I'm getting desparate. -- Andrew Bushnell Lead Development Engineer Fluent Inc. 10 Cavendish Court Centerra Resource Park Lebanon, NH 03766 [EMAIL PROTECTED] Phone: 603-643-2600, ext. 757 Fax: 603-643-1721 www.fluent.com -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter special math chars
So far, on RedHat Linux: I have used your method successfully in a Label and in Canvas Text. very slow.?? In A Text box I just get \N{INFINITY}. But thanks, I will investigate Text Box more. Jeff Epler wrote: I wrote the following code: import Tkinter t = Tkinter.Label() t.configure( text=uAs the function approaches \N{INFINITY}, \N{HORIZONTAL ELLIPSIS}) t.pack() t.mainloop() It worked for me on Windows NT 4.0 with Python 2.4, and on RedHat 9 with a self-compiled Python 2.3, showing an infinity symbol and an ellipsis. u'\N{...}' stands for the Unicode character named '...'. Unicode.org (and other sites) have lists of Unicode character names. Tk tries very hard to find the requested character in some font available on the system, but when it fails it just displays a unicode escape sequence like \u220e (instead of the END OF PROOF symbol, in this case), and there's really no way for Python to find out and fall back in some graceful way. Relying on this behavior, here's a somewhat-falliable way to detect the presence of a symbol in the font used in a given widget: def symbol_exists(s, w, f = None): if f is None: f = w.cget(font) width_symbol = w.tk.call(font, measure, f, s) width_bench = w.tk.call(font, measure, f, 000) return width_symbol width_bench This finds the width in pixels of the given symbol (s) and the string 000, in the font f. If the width of the symbol is smaller, then it's probably available. If it's wider, then it's probably rendered as an escape sequence like \u220e. This is falliable because there's no guarantee that the symbol would not be as wide as 000, but also it's possible for some escape code (say \u) to be narrower than 000. Neither of these seem very likely in practice. Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
Thanks for the feedback. andreas. I am looking into how to work my own connection logic into the code. Google has quickly become my friend and I am actually poking at cURL (pyCurl) to see what benefit it will be. Thanks again. [EMAIL PROTECTED] wrote: Hi! HTTPS over a proxy (CONNECT) hasn't worked for a long time in python (actually it has never worked). A quick glance at the 2.4 Changelog doesn't suggest that this has been fixed. So basically you've got the following options: a) redo your own http/https support. b) look around on the net for some patches to httplib (google is your friend) be aware that these are quite old patches. c) using some external solution, like pycURL. Andreas On Thu, May 19, 2005 at 12:53:11PM -0400, Andrew Bushnell wrote: Thanks for the update. I will/can keep you posted. I know for a fact we use a Squid proxy which sounds like what you are using. I am going to check out the faq you sent and see what it comes up with. I have also been perusing the net a bit and looking at other client packages and see if they work, such as cURL etc. Thanks, Andrew Bloke wrote: Andrew, It seems I'm not the only one going nuts here. I have just spent the last 4 hrs stepping through the code in the debugger. It seems to get stuck somewhere in the socket module (when it calls ssl) but haven't as yet figured out exactly where. I am _very_ interested to find that you have the same prob with a non-authenticating proxy. I had considered I was doing something wrong with the authentication, but from what you say, and from what I have deduced from the code, it is not the authentication that is at fault. Like you, a standard browser works fine, so I'm inclined to think there is something buggy with the way the sockets module talks to the proxy. There has been some suggestion that it may me a 'Microsoftish' proxy which is at fault, but I believe it is a Squid proxy our company uses. There is an interesting note here ( http://www.squid-cache.org/Doc/FAQ/FAQ-11.html setcion 11.34 ) regarding malformed https requests sent through Squid with buggy clients. It may be worth looking into. Anyway, if you have any luck, _please_ let me know - I'm getting desparate. -- Andrew Bushnell Lead Development Engineer Fluent Inc. 10 Cavendish Court Centerra Resource Park Lebanon, NH 03766 [EMAIL PROTECTED] Phone: 603-643-2600, ext. 757 Fax: 603-643-1721 www.fluent.com -- http://mail.python.org/mailman/listinfo/python-list -- Andrew Bushnell Lead Development Engineer Fluent Inc. 10 Cavendish Court Centerra Resource Park Lebanon, NH 03766 [EMAIL PROTECTED] Phone: 603-643-2600, ext. 757 Fax: 603-643-1721 www.fluent.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the use of changing func_name?
Robert Kern [EMAIL PROTECTED] writes: could ildg wrote: Thank you for your help. I know the function g is changed after setting the func_name. But I still can't call funciton g by using f(), when I try to do this, error will occur: code g.func_name=f print g function f at 0x00B2CEB0 f() Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'f' is not defined /code Since the name of g is changed into f, why can't I call it by using f()? Should I call it using f through other ways? Please tell me. Thanks~ Others have answered this particular question, but you're probably still wondering what is the use of changing .func_name if it doesn't also change the name by which you call it. The answer is that there are tools that use the .func_name attribute for various purposes. For example, a documentation generating tool might look at the .func_name attribute to make the proper documentation. Actually, that's probably *the* biggest use case because I can't think of any more significant ones. Error messages! Cheers, mwh -- There are two kinds of large software systems: those that evolved from small systems and those that don't work. -- Seen on slashdot.org, then quoted by amk -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree and xsi to xmlns conversion?
Thanks for the reply I am understanding it better now. Please forgive my ignorance. So the xsi is just an arbitrary name space prefix, I get that now. And it make sense to me why it gets converted to an xmlns. What I really need to know is why it is not inherited by the child elements? From what I an told, I need the second namespace, so that I can point to the schema, so that I can validate the document. Is that the wrong way to link to the schema? Can I force both namespaces to be inherited by the child elements? Thanks for all the help -Matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: Twisted an several CPUs
On Thu, 19 May 2005 17:22:31 +0200, Thomas Guettler [EMAIL PROTECTED] wrote: Hi, Out of sheer curiosity: Does Twisted scale if the server has several CPUs? No more than any other single-process Python application (no less, either). Unless you run multiple processes... As far as I know twisted uses one interpreter. This means a prefork server modul might be better to server database driven web-apps. Why does it mean that? Your database is already running in a separate process, right? So there's SMP exploitation right there, regardless of whether your Python process is running with Twisted or anything else. Has anyone experience high load and twisted? Distributing load across multiple machines scales better than distributing it over multiple CPUs in a single machine. If you have serious scalability requirements, SMP is a minor step in the wrong direction (unless you're talking about something like 128-way SMP on a supercomputer :) Plus, any solution that works across multiple machines is likely to be trivially adaptable to work across multiple CPUs on a single machine, so when your desktop has a 128-way cell processor in it, you'll still be able to take advantage of it :) Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python suitable for a huge, enterprise size app?
In article [EMAIL PROTECTED], Fredrik Lundh [EMAIL PROTECTED] wrote: (this used to be explained in the Python FAQ too, but it looks as if that was lost in the great FAQ reorganization). Send e-mail to [EMAIL PROTECTED] -- actually, you can have commit privs if you want. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ The only problem with Microsoft is they just have no taste. --Steve Jobs -- http://mail.python.org/mailman/listinfo/python-list
Re: SSL (HTTPS) with 2.4
If you need some help, send me an email and if we figure this out we can post a resolution. I have used both approaches (having authored them). Or at least let me know what site you are going to and I will try them on a windows box and see if I can debug that the [EMAIL PROTECTED]@ is going on. john -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter special math chars
text=uAs the function approaches \N{INFINITY}, \N{HORIZONTAL ELLIPSIS}) Never mind, works in a Text widget, my bad. Why is it so slow? (RH Linux, 2.4.20, 1.6Ghz AMD) 3/4 second slower to display widget w/unicode, even if I encode u'\u221e' Works though, this is great. -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Hi rh0dium, Your request gives me the opportunity of showing a more realistic example of the technique of self-modification coding. Although the coding is not as short as that suggested by the guys who replayed to you, I think that it can be interesting # newVars.py lCod=[] for n in range(1,27): . lCod.append(chr(n+96)+'='+str(n)+'\n') # other for-loops if you want define additional variables in sequence (ex. aa,bb,cc etc...) # write the variable definitions in the file varDef.py fNewV=open('varDef.py','w') fNewV.writelines(lCod) fNewV.close() from varDef import * # ... If you open the generated file (varDef.py) you can see all the variable definitions, which are runned by from varDef import * Bye. -- http://mail.python.org/mailman/listinfo/python-list
Re: Byte-operations.
For anyone who cares out there, I tried a slice with hex values: IDLE 1.0.3 a =['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17 ','18','19','20'] print a[3:4] ['4'] print a[0xa:0xc] ['11', '12'] print a[0xa:0xa+5] ['11', '12', '13', '14', '15'] -Dave Jeff Epler [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] In Python, chr gives a 1-byte string from a small integer, ord does the reverse. Strings are concatenated with + and substrings are taken with the slice operator, s[pos1:pos2]. I'm not a visual basic expert, but it looks like these are the operations the code below performs. Jeff -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov chain with extras?
Hi Gentlemen, First off, thanks for the work/time you've put into this - much appreciated! Let me play around with the code and I'll get back to you tomorrow. Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter special math chars
On Thu, May 19, 2005 at 12:56:12PM -0500, phil wrote: Why is it so slow? (RH Linux, 2.4.20, 1.6Ghz AMD) 3/4 second slower to display widget w/unicode, even if I encode u'\u221e' u'\u221e' vs u'\N{INFINITY}' should make no noticible run-time difference--they both specify exactly the same string, and the decoding takes place at the time the script or module is byte-compiled. What Tk does at runtime is inspect a large number of fonts until it finds one with the desired character---or all the fonts, if the character doesn't exist. Querying all the fonts on your system can take quite a bit of time. I believe that Tk caches this information until program exit, or at least as long as the font is in use, and characters that are nearby in their unicode values will be resolved at the same time. I'm not aware of a good explanation of the low-level font handling in Tk; The information in the above paragraph was gleaned by reading the source code (tkUnixFont.c and tkWinFont.c). Jeff pgpEsZ31qI4Yx.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Call me crazy.. But it doesn't work.. for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha for y in [''] + [z for z in alpha]], key=len)): globals()[digraph]=i+1 How do you implement this sucker?? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
This is great but backwards... Ok because you all want to know why.. I need to convert Excel columns A2 into , [1,0] and I need a simple way to do that.. ( The way this works is A-0 and 2-1 -- Yes they interchange -- So B14 == [13,1] ) So my logic was simple convert the A to a number and then do the swap. I didn't really care about the function so to speak it was a minor step in the bigger picture.. By the way if you haven't played with pyXLWriter is it really good :) So can anyone simply provide a nice function to do this? My logic was along the same lines as Dans was earlier - but that just seems too messy (and ugly) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
On 19 May 2005 11:52:30 -0700, rh0dium [EMAIL PROTECTED] wrote: Call me crazy.. But it doesn't work.. What doesn't work? What did python output when you tried to do it? It is python 2.4 specific, it requires some changes for 2.3, and more for earlier versions of python. for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha for y in [''] + [z for z in alpha]], key=len)): globals()[digraph]=i+1 How do you implement this sucker?? Works just fine for me. Let me know what error you're getting and I'll help you figure it out. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to receive events (eg. user mouse clicks) from IE
Hi Thanks for the response and for the code. However, I want to trap events like mouse click on the HTML document loaded by the web browser control. The code mentioned below provides events from the web browser control. I need to find out on which particular HTML tag did the user click for example. How do I find that out? There should be some way to refer to a document from a given web browser control and start receiving events from it Roger Upole wrote: The two you'll need to run makepy for are Microsoft Internet Controls and Microsoft HTML object Library. If you run them manually, you should be able to look at the generated code to get the guids. Here's a minimal example: import win32com.client ie_mod=win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-C05BAE0B}',0, 1, 1) class IE_Events(ie_mod.DWebBrowserEvents2): def OnNavigateComplete2(self, pDisp, URL): print 'OnNavigateComplete2:', URL ie=win32com.client.DispatchWithEvents('InternetExplorer.Application',IE_Events) ie.Visible=1 ie.Navigate('http://www.google.com') hth Roger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am trying to trap events from internet explorer eg. when user clicks on an html link - I need to get notified for that event. After looking through the newgroups / internet and reading through various sections in programming python on win32 - I understand that this can be done using DispatchWithEvents. I have also referred to discussions on comp.lang.python http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a3c502d06412a5f8/0ee3083e71316da7?q=dispatchwitheventsrnum=43#0ee3083e71316da7 and http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1da0668794851296/5bcec1fda216c598?q=dispatchwitheventsrnum=19#5bcec1fda216c598 So far - none of the newgroups postings report that IE events were trapped successfully (at least I could not find any). However, there is enough evidence that it can be done. My problems at the moment: a) The examples use early binding. However, I cannot get Python makepy to generate the code to force makepy process at run time - since COM makepy utility that I invoke from python win 32 does not have any entry for internet explorer. I tried to find the CLSID for IE 3050F613-98B5-11CF-BB82-00AA00BDCE0B but I get an exception b) Also one of the examples suggest that following code should work mod = EnsureModule(...) class MyEvents(mod.IDocumentEvents): # your methods here handler = MyEvents(ie.document) # handler should start recieving events. however, what CLSID is to be used in EnsureModule... . I tried with a few but I always get the error 'NoneType' object has no attribute 'IDocumentEvents' An example that 'works' will be very useful == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
On 19 May 2005 11:59:00 -0700, rh0dium [EMAIL PROTECTED] wrote: This is great but backwards... Ok because you all want to know why.. I need to convert Excel columns A2 into , [1,0] and I need a simple way to do that.. ( The way this works is A-0 and 2-1 -- Yes they interchange -- So B14 == [13,1] ) why didn't you say this in the first place? def coord2tuple(coord): row, col = '', '' alpha = 'abcdefghijklmnopqrstuvwxyz'.upper() pairs = [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]] pairs = sorted(pairs, key=len) coord = coord.upper() for c in coord: if c in alpha: row += c else: col += c return (int(col)-1, pairs.index(row)) coord2tuple('B14') (13, 1) coord2tuple('ZZ14') (13, 701) coord2tuple('ZZ175') (174, 701) coord2tuple('A2') (1, 0) Are there cols greater than ZZ? I seem to remember that there are not, but I could be wrong. Hope this helps. Peace Bill Mill [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Self-modifying Code
[EMAIL PROTECTED] schrieb: [...] Also Python can (writing and running a module, in-line): fNew =open(newModule.py,'w') lNew=['print 123\n','print 454\n','print 789\n'] fNew.writelines(lNew) fNew.close() from newModule import * [...] You don't even need a file for this. Try: exec(print 123; print 456; print 789) Bye, Dennis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to receive events (eg. user mouse clicks) from IE
ie.Document will give you the document object. That's where the Html object library comes in, it contains the early-binding code for the Document interface. Then you can hook one of the event classes for the Document (I see several in the generated file) using the same methodology as shown for the web browser events. Roger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi Thanks for the response and for the code. However, I want to trap events like mouse click on the HTML document loaded by the web browser control. The code mentioned below provides events from the web browser control. I need to find out on which particular HTML tag did the user click for example. How do I find that out? There should be some way to refer to a document from a given web browser control and start receiving events from it Roger Upole wrote: The two you'll need to run makepy for are Microsoft Internet Controls and Microsoft HTML object Library. If you run them manually, you should be able to look at the generated code to get the guids. Here's a minimal example: import win32com.client ie_mod=win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-C05BAE0B}',0, 1, 1) class IE_Events(ie_mod.DWebBrowserEvents2): def OnNavigateComplete2(self, pDisp, URL): print 'OnNavigateComplete2:', URL ie=win32com.client.DispatchWithEvents('InternetExplorer.Application',IE_Events) ie.Visible=1 ie.Navigate('http://www.google.com') hth Roger [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am trying to trap events from internet explorer eg. when user clicks on an html link - I need to get notified for that event. After looking through the newgroups / internet and reading through various sections in programming python on win32 - I understand that this can be done using DispatchWithEvents. I have also referred to discussions on comp.lang.python http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a3c502d06412a5f8/0ee3083e71316da7?q=dispatchwitheventsrnum=43#0ee3083e71316da7 and http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1da0668794851296/5bcec1fda216c598?q=dispatchwitheventsrnum=19#5bcec1fda216c598 So far - none of the newgroups postings report that IE events were trapped successfully (at least I could not find any). However, there is enough evidence that it can be done. My problems at the moment: a) The examples use early binding. However, I cannot get Python makepy to generate the code to force makepy process at run time - since COM makepy utility that I invoke from python win 32 does not have any entry for internet explorer. I tried to find the CLSID for IE 3050F613-98B5-11CF-BB82-00AA00BDCE0B but I get an exception b) Also one of the examples suggest that following code should work mod = EnsureModule(...) class MyEvents(mod.IDocumentEvents): # your methods here handler = MyEvents(ie.document) # handler should start recieving events. however, what CLSID is to be used in EnsureModule... . I tried with a few but I always get the error 'NoneType' object has no attribute 'IDocumentEvents' An example that 'works' will be very useful == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups = East and West-Coast Server Farms - Total Privacy via Encryption = == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News== http://www.newsfeeds.com The #1 Newsgroup Service in the World! 100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
On 19 May 2005 12:20:03 -0700, rh0dium [EMAIL PROTECTED] wrote: Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'sorted' is not defined I think you're probably using 2.4 ?? Yes, sorted() is new in python 2.4 .You could use a very lightly tested pure-python partial replacement: def sorted(lst, **kwargs): l2 = lst[:] if kwargs.has_key('key'): f = kwargs['key'] l2.sort(lambda a,b: cmp(f(a), f(b))) return l2 l2.sort() return l2 And from your other email: I need to go the other way! tuple2coord Sorry, I only go one way. It should be transparent how to do it backwards. Peace Bill Mill [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Bill Mill wrote: Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'sorted' is not defined I think you're probably using 2.4 ?? Yes, sorted() is new in python 2.4 .You could use a very lightly tested pure-python partial replacement: By the way, sorted() can be removed from your original post. Code has no effect :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Self-modifying Code
Hi, you, also ! A view, with a little difference : def titi(par): if par222: return par*2 else: return par*10 print titi(123) print titi(1234) #now, change the function, on instant txt=def titi(par): if par222: return str(par)*2 else: return str(par)*5 exec(txt,globals(),globals()) print titi(123) print titi(1234) Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list