problems importing from /usr/lib/pyshared/
Dear all, I recently upgraded my system from ubuntu 11.4 to 12.4 and since run into an issue when trying to import several packages in python2.7, e.g. harold@ubuntu:~$ python -c 'import gtk' Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py", line 30, in import gobject as _gobject File "/usr/share/pyshared/gobject/__init__.py", line 26, in from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "/usr/share/pyshared/glib/__init__.py", line 22, in from glib._glib import * ImportError: No module named _glib the same, for example, with pysvn: harold@ubuntu:~$ python -c 'import pysvn' Traceback (most recent call last): File "", line 1, in File "/usr/share/pyshared/pysvn/__init__.py", line 99, in import _pysvn_2_7 ImportError: No module named _pysvn_2_7 After playing around a bit, I realized that I can import said packages without problems, if I delete /usr/lib/pyshared from the python path: >>> import sys >>> sys.path ['', '/usr/share/pyshared', '/home/harold', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode'] >>> del sys.path[1] >>> import gtk >>> import pysvn >>> Is /usr/lib/pyshared supposed to be in the python path? If not, how can I ensure that it is not included? Where is PYTHONPATH initialized by default, anyway? Thanks, harold. -- http://mail.python.org/mailman/listinfo/python-list
Re: problems importing from /usr/lib/pyshared/
Thank you Dieter, > Ubuntu 12 has introduced important changes with respect to "glib" (and > depending packages). In fact, there are now two quite incompatible > implementations - the old "static" one and a new "dynamic" one. > It looks as if in your case, old and new implementations were mixed. > > I had a similar problem when upgrading to "Ubuntu 12.4". In my case, > it turned out that my (custom) "PYTHONPATH" setting was responsible for > getting into the incompatibility. > > The new way to use "gtk" is via the "gi" (probable "gnome interface") > module. It looks like: > > from gi.repository import Gtk,GdkPixbuf,GObject,Pango,Gdk,Gio I will investigate this gi module. As for my import problem, it turned out that it was my own fault: following some recommendation on the web, I had added /usr/share/pyshared to the python path in ~/.profile and forgot to log out and in again after undoing this change. Everything works fine again, and I am ready to explore the new modules. -- http://mail.python.org/mailman/listinfo/python-list
Significant figures calculation
Hi, I am looking for an easy way to do significant figure calculations in python (which I want to use with a class that does unit calculations). Significant figure calculations should have the semantics explained, e.g., here: http://chemistry.about.com/od/mathsciencefundamentals/a/sigfigures.htm My hope was that the decimal module would provide this functionality, but: >>> print Decimal('32.01') + Decimal(5.325) + Decimal('12') 49.335 # instead of 49 >>> print Decimal('25.624') / Decimal('25') 1.02496 # instead of 1.0 >>> print Decimal('1.2') == Decimal('1.23') False # actually not sure how the semantics should be I tried to modify the DecimalContext (e.g. getcontext().prec = 2) but that did not lead to the correct behavior. Google and this list didn't yield a good answer yet... so I'd be happy to get a good recommendations or pointers. P.S. I am aware that significant figure calculation is controversial and makes implicit assumptions on the probability distributions of the variables. I am simply looking for an implementation of the (well defined) arithmetics as defined on the cited website. -- http://mail.python.org/mailman/listinfo/python-list
Re: Significant figures calculation
> > I tried to modify the DecimalContext (e.g. getcontext().prec = 2) but > > that did not lead to the correct behavior. > > Really? It works for me. You are right, I did something wrong when attempting to set the precision. And the trick with rounding the decimal with the unary + is neat. It's the first time for me to play with decimals, so bare with me if I miss the obvious. However, this approach forces you to know the number of significant figures beforehand -- which is precisely what the arithmetics should do for you. What would indeed be nice, is Jerry's suggestion to obtain the number of significant bits and write a small wrapper around the number protocoll implementation that accounts significance and have __str__/__repr__ set the context dynamically. I haven't seen anything obvious in the docs, though it might be possible to use log10 of the length of some normalized string representation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Significant figures calculation
> >I'm curious. Is there a way to get the number of significant digits > >for a particular Decimal instance? > > Yes: > > def sigdig(x): > "return the number of significant digits in x" > return len(x.as_tuple()[1]) Great! that's exactly what I needed. thanks Chris! -- http://mail.python.org/mailman/listinfo/python-list
Re: Significant figures calculation
On Jun 25, 9:04 pm, Chris Torek wrote: > >I'm curious. Is there a way to get the number of significant digits > >for a particular Decimal instance? > > Yes: > > def sigdig(x): > "return the number of significant digits in x" > return len(x.as_tuple()[1]) Great, Chris, this is (almost) exactly what I needed. To make it work for numbers like 1200, that have four digits but only two of them being significant, I changed your snippet to the following: class Empirical(Decimal) : @property def significance(self) : t = self.as_tuple() if t[2] < 0 : return len(t[1]) else : return len(''.join(map(str,t[1])).rstrip('0')) >>> Empirical('1200.').significance 2 >>> Empirical('1200.0').significance 5 now it's only about overriding the numerical operators :) -- http://mail.python.org/mailman/listinfo/python-list
problems when unpacking tuple ...
Dear all, Maybe I stared on the monitor for too long, because I cannot find the bug ... My script "transition_filter.py" starts with the following lines: import sys for line in sys.stdin : try : for a,b,c,d in line.split() : pass except ValueError , err : print line.split() raise err The output (when given the data I want to parse) is: ['0.0','1','0.04','0'] Traceback (most recent call last): File "transition_filter.py", line 10, in ? raise err ValueError: need more than 3 values to unpack What is going wrong here? Why does python think that I want to unpack the outcome of line.split() into three values instead of four? I must be really tired, but I just cannot see the problem. Any clues?? Thanks, - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: problems when unpacking tuple ...
Rene Pijlman schrieb: > harold: > >The output (when given the data I want to parse) is: > > If you'd told us that data, and told us what version of Python you're > using, we could have reproduced the problem to look into it. > Thank you for the answers and sorry that I did not provide more information in the first place. My data file is white space seperated data (space seperated data to be precise) and I am using python 2.4.2 As can be seen, the output of the print statement in the lines except ValueError , err: print line.split() raise err has exactly four values... > >ValueError: need more than 3 values to unpack > > > >Why does python think that I want to unpack the outcome of > >line.split() into three values instead of four? > > That's not what it says. It says there are only 3 values in the outcome, > and it needs more (4 to be precise). A similar error happens in an interpreter session, when typing >>> for line in ["1 2 3 4"] : ...for a,b,c,d in line.split() : ...pass ... Traceback (most recent call last): File "", line 2, in ? ValueError: need more than 1 value tyo unpack maybe this might help to track down the error. Thanks! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: problems when unpacking tuple ...
Thank you Gerard. This must be the problem. Now I can get it working. -- http://mail.python.org/mailman/listinfo/python-list
Re: problems when unpacking tuple ...
Thanks for all your answer! Of course, I wanted to assign the outcome of the split(), not to iterate over them. Thinks are done so easy in python that, sometimes, one does not even notice that one actually does them ;-) Cheers, - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: check whether a value is scalar
would isinstance(value,(type(None),str,int,float,bool)) be enough? This yields true if the type value is in the list of type objects given as second argument, or a subtype of one of them. What, however, do you mean with "I care about the value only, and not its class method"? -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclass str: where is the problem?
[EMAIL PROTECTED] schrieb: > Hello, can anybody explain/help me: > > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > > > class Upper(str): > def __new__(cls, value): > return str.__new__(cls, value.upper()) > > u = Upper('test') > u > 'TEST' > type(u) > > u = Upper('') > u > '' > type(u) > > > > All seems to be ok... > > class MyObject(object): > def __init__(self, dictionary = {}): > self.id = dictionary.get('id', '') > def __setattr__(self, attribute, value): > value = type(value) is type('') and Upper(value) or value > object.__setattr__(self, attribute, value) > > m = MyObject({'id': 'test'}) > m.id > 'TEST' > type(m.id) > > m = MyObject() > m.id > '' > type(m.id) > > > Why is m.id a str ? Because Upper(value) will be False in the line > value = type(value) is type('') and Upper(value) or value and thus, you assign value itself to value again. rewrite it for exmaple in this way: def __setattr__(self, attribute, value): if type(value) is type('') : value = Upper(value) object.__setattr__(self, attribute, value) -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclass str: where is the problem?
Hi Pascal, Indeed, the example you show work corrctly. But in the code you posted before, you wonder about the behavior of these lines: > m = MyObject() > m.id > '' > type(m.id) > So what happens when you provide the empty string '' to your and-or construct? value = '' value = type(value) is type('') and Upper(value) or value As you can easily check, bool('') resolves to False. Thus, your line becomes: value = False and False or value Python first evaluates the and expression, which resolves to False. The or expression evaluates the second argument and returns that one as the result if and only if the first one evaluates to False, which is the case here. So the result of False or value is value. You can check that >>> value is (False or value) True so, in you code, the empty string gets indeed assign as value again. Be carefull with the condition/and/or chain! You must be 110% sure, that the desired return value in case of condition==True can never evaluate to False! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: how to free the big list memory
pydoc gc.collect pydoc xrange -- http://mail.python.org/mailman/listinfo/python-list
Re: how do I make a class global?
basically, you can create new types on the fly using type() with three arguments: my_class = type("className",(BaseClass,),class_dict) then, you can assign this vlass to the golbal namespace using globals(): globals()["className"] = my_class In your case, you would need to populate the class_dict by a function object that you parameterize to your needs, e.g. def create_class(name,params) : def cls_init(self) : BaseClass.__init__(self) self.params = params cls_dict = { "__init__" : cls_init } new_cls = type(name,(BaseClass,),cls_dict) globals()[name] = new_cls the result would be like this: >>> create_class("test_class",42) >>> instance = test_class() >>> print instance.params 42 -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
In <[EMAIL PROTECTED]> Brian Utterback: [Snip...] > that the laws have been in place since the late 1800's, the consent > decree explicitly and in no uncertain terms informed them of their > violations, and they continued to violate the law even afterward. It's M$ corporate DNA; they literally couldn't change and survive: Howard University law professor Andrew Gavil said he wonders whether Microsoft's early demands -- which would have compelled manufacturers to distribute to consumers only Microsoft's Windows Media Player software -- were a genuine mistake or a signal the company intends to revert to its hardball tactics. "It's somewhat amazing it even happened," said Gavil, who has closely followed the Microsoft case. "It's troubling that anyone inside Microsoft was still thinking this was a legitimate business strategy." Well, duh. All they got was a useless wrist-slap from the dickless US DOJ in 2002, so this is not at all surprising--just bidness as usual for M$. More: http://biz.yahoo.com/ap/051020/microsoft_antitrust.html?.v=6 And any M$ apologists are just as much liars and thieves as M$ itself. -- Regards, Weird (Harold Stevens) * IMPORTANT EMAIL INFO FOLLOWS * Pardon any bogus email addresses (wookie) in place for spambots. Really, it's (wyrd) at airmail, dotted with net. DO NOT SPAM IT. Kids jumping ship? Looking to hire an old-school type? Email me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
In <[EMAIL PROTECTED]> Paul Rubin: [Snip...] > The trial court determined and two different appeals courts upheld > that MS had an illegal monopoly. And M$ is still intransigent about that LEGAL FACT, much to the dismay of the federal judge overseeing the latest (toothless) consent decree: In a rare display of indignation, U.S. District Judge Colleen Kollar-Kotelly demanded an explanation from Microsoft's lawyers and told them, "This should not be happening." Legal and industry experts said Microsoft's demands probably would have violated a landmark antitrust settlement the same judge approved in 2002 between the company and the Bush administration. The government and Microsoft disclosed details of the dispute in a court document last week. More at: http://biz.yahoo.com/ap/051026/microsoft_antitrust.html?.v=3 Just to really get her riled, the M$ snakes pulled another stunt: "This needs to get done," U.S. District Judge Colleen Kollar-Kotelly said of a project designed to help put potential rivals on a more equal competitive footing with Microsoft. "If there's an issue of resources, then put them in," said Kollar-Kotelly, who endorsed the settlement with the U.S. government and state attorneys general in November 2002. More at (line wrapped): http://yahoo.reuters.com/financeQuoteCompanyNewsArticle.jhtml?duid=mtfh193 85_2005-10-26_23-14-09_n26509630_newsml Any M$ apologists saying M$ isn't an illegal monopoly are just as much a part of that pack of liars and thieves as M$ itself. They need to discuss it with Judge Colleen, and STignorantFU about it. -- Regards, Weird (Harold Stevens) * IMPORTANT EMAIL INFO FOLLOWS * Pardon any bogus email addresses (wookie) in place for spambots. Really, it's (wyrd) at airmail, dotted with net. DO NOT SPAM IT. Kids jumping ship? Looking to hire an old-school type? Email me. -- http://mail.python.org/mailman/listinfo/python-list
Re: cosmetic Tkinter question
On 26.12.2004, at 16:38, Sean McIlroy wrote: I've got a bunch of Frames, all packed into the root window with side=TOP, and in each Frame I've got a Checkbutton packed with side=LEFT. I expected the Checkbuttons to be flush with the left edge of the window, but they're not, and it looks a little gross. How do I get them to align? if you pack the frames with option fill=X they should be well aligned -- This commands the frame to use all available space in the horizontal direction: your_frame.pack(side=TOP,fill=X) your_button.pack(side=LEFT) - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
syntax error in eval()
Hi all, I am trying to dynamically add class attributes at runtime using the function eval(), i.e. I want to do something like >>> class X : pass ... >>> X.attr = 5 but without knowing either the attributes name nor its value. However, I encounter a syntax error I cannot understand: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class X : pass ... >>> attrname = "attr" >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) Traceback (most recent call last): File "", line 1, in ? File "", line 1 X.attr = val ^ SyntaxError: invalid syntax Does anyone have a clue what might be wrong? Thanks in advance. - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman -- http://mail.python.org/mailman/listinfo/python-list
Re: syntax error in eval()
Thank you, Duncan and Steven. I completely forgot about setattr. Of course that's the way ... as its name might suggest *g* What you are doing wrong is attempting to use eval before exhausting all the simpler techniques. Why not just call 'setattr'? setattr(X, 'attr', 5) BTW, the syntax error is because eval evaluates an expression and an assignment statement is a statement not an expression. -- Abandon the search for Truth -- settle for a good fantasy. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: here document
On 11.01.2005, at 11:34, Nader Emami wrote: Would somebody help me how i can write the 'here document' in Python script please? I have a csh script in which a program is invoked with some argument in the form of here document: /bin/exe.x << End_Here CategorY = GRIB etc. End_Here I translate this script to Python and i don't know how can I do this! f = open("/bin/exe.x","w") print >>f , """CategoryY = GRIB etc. """ -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen -- http://mail.python.org/mailman/listinfo/python-list
how to set doc-string of new-style classes
Hello, does anyone know a way to set the __doc__ string of a new style class? Any attempt I tried results in the following error: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object) : ... pass ... >>> Foo.__doc__ = "bar" Traceback (most recent call last): File "", line 1, in ? TypeError: attribute '__doc__' of 'type' objects is not writable I can understand someone arguing that "changing a doc string is during programm execution and should therefore be forbidden!" But, I cannot even find out a way to set the doc string, when I CREATE a class using type(name,bases,dict) ... At least this should be possible, IMHO. - harold - -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. -- http://mail.python.org/mailman/listinfo/python-list
Re: exporting from Tkinter Canvas object in PNG
On 11.01.2005, at 19:14, Nicolas Pourcelot wrote: Hello, I'm new to this mailing list and quite to Pyhon too. I would like to know how to export the contain of the Canvas object (Tkinter) in a PNG file ? Thanks :) Nicolas Pourcelot -- http://mail.python.org/mailman/listinfo/python-list you can make a postscript dump using >>> canvas = Tkinter.Canvas(master) >>> canvas.postscript(file="your_file_name.ps") If you have ImageMagick, you can later use % convert your_file_name.ps your_file_name.png on the comand line, if you want to have png. - harold - -- Science is to see what everybody else has seen, and think what nobody else has thought. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: how to set doc-string of new-style classes
On 11.01.2005, at 19:35, Alex Martelli wrote: harold fellermann <[EMAIL PROTECTED]> wrote: ... But, I cannot even find out a way to set the doc string, when I CREATE a class using type(name,bases,dict) ... At least this should be possible, IMHO. x=type('x',(),dict(__doc__='hi there')) x.__doc__ 'hi there' yes, you're right ... a subsequent question, that puzzles me: where can I apply for the "most-stupid-question"-award, now *g* thanks anyway, - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
On 12.01.2005, at 18:35, It's me wrote: For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? because len() works only for sequence and mapping objects: >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. - harold - -- Ceci n'est pas une signature. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
On 12.01.2005, at 18:35, It's me wrote: For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? the problem is, that (1,len(a)) is evaluated, neither what type a actually has (python has no builtin lazy evaluation like ML). You have to do it this way instead: a=3 ... b = isinstance(a,(list,tuple,dict)) and len(a) or 1 - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Unclear On Class Variables
Hi Tim, If you have class Foo(object) : x = 0 y = 1 foo = Foo() foo.x # reads either instance or class attribute (class in this case) foo.x = val # sets an instance attribute (because foo is instance not class) Foo.x = val # sets a class attribute foo.__class.__x = val # does the same this might be sometimes confusing. IMHO, the following is especially nasty: >>> foo = Foo() >>> foo.x += 1 >>> >>> print foo.x 1 >>> print Foo.x 0 although the += operator looks like an inplace add it isn't. it is just syntactic sugar for foo.x = foo.x + 1. - harold - On 13.01.2005, at 07:18, Tim Daneliuk wrote: I am a bit confused. I was under the impression that: class foo(object): x = 0 y = 1 means that x and y are variables shared by all instances of a class. But when I run this against two instances of foo, and set the values of x and y, they are indeed unique to the *instance* rather than the class. It is late and I am probably missing the obvious. Enlightenment appreciated ... -- --- - Tim Daneliuk [EMAIL PROTECTED] PGP Key: http://www.tundraware.com/PGP/ -- http://mail.python.org/mailman/listinfo/python-list -- Everyone is a genius. It's just that some people are too stupid to realize it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickling a class instead of an instance
have a look at the thread "copying classes?" some days ago. what goes for copying goes for pickling also, because the modules use the same interface. - harold - On 13.01.2005, at 13:32, Sebastien Boisgerault wrote: Hi, It seems to me that it's not possible with the pickle module to serialize a class rather than an instance, as in from pickle import * class C(object): "... doc ..." a = 1 pickstr = dumps(C) I mean, it does *something*, there is no error indeed, but from the string pickstr, I am unable to rebuild the class C in a brand new context (got a "you're really stupid, all you deserve is an AttributeError because you know there is no attribute 'C' in the 'module' object" error). Am I wrong ? Why would the "(new-style) classes are regular objects too" mantra not apply in this case ? Could we imagine a patch to the pickle module to handle this kind of situation ? SB -- http://mail.python.org/mailman/listinfo/python-list -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Tix and Tkinter
On 31.12.2004, at 16:50, Harlin Seritt wrote: import Tix from Tkconstants import * from Tkinter import * root = Tix.Tk() Label(root, text="Hello!").pack() Tix.tixControl().pack() root.mainloop() When I run this, I get the following error: Traceback (most recent call last): File "TixTest.py", line 8, in ? Tix.tixControl().pack() AttributeError: 'module' object has no attribute 'tixControl' in the Tix module this widget is called Control. writing Tix.Control().pack() should work. - harold - -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Tix.FileSelectDialog wait for user?
Hi, I have a question concerning the Tix file select mechanisms. Unfortunately, I have very little experience with neither tk, Tkinter nor Tix. Somewhere in my GUI I have a save button. What I want is that pressing the button opens a file requester. The user can either select a filename or cancel the action. I have found Tix.FileSelectDialog which seems to be nice for the task. But how can I use this dialog after all? how can I e.g. attach a command to the "Ok"-Button. Or isn't there a simple function that 1.) opens the requester 2.) waits until the requester is closed 3.) returns either a string (filename) or None (canceled) so that I can just write something like: fname = FileSelect() if fname != None : do_something_with(fname) Damn, I hate Tk's and Tix' so called "manuals": The Tk manual takes a user and makes it into a grammar parser. Further information, like common usage or examples, that might normally be expected in a manual cannot be found with no additional arguments. The Tk manual returns the completely clueless programmer. Start to like pydoc(Tkinter) and pydoc(Tix), though :-) - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." -- http://mail.python.org/mailman/listinfo/python-list
pickling extension class
Hi all, I have a problem pickling an extension class. As written in the Extending/Embedding Manual, I provided a function __reduce__ that returns the appropreate tuple. This seams to work fine, but I still cannot pickle because of the following error: >>> from model import hyper >>> g = hyper.PeriodicGrid(4,4,1) >>> g.__reduce__() (,(4.,4.,1.)) >>> import pickle >>> pickle.dump(g,file("test","w")) Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/sw/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/sw/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/sw/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/sw/lib/python2.4/pickle.py", line 414, in save_reduce save(func) File "/sw/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid >>> dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] >>> hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? Any help appreceated, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
Re: pickling extension class
On 18.01.2005, at 20:31, Alex Martelli wrote: harold fellermann <[EMAIL PROTECTED]> wrote: File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? These symptomps are pretty weird -- let's try to pin things down a bit more. The relevant few lines of pickle.py are: try: __import__(module) mod = sys.modules[module] klass = getattr(mod, name) except (ImportError, KeyError, AttributeError): raise PicklingError( so, could you please edit your pickle.py to provide VASTLY more info, [...] and let us know exactly what his modified pickle.py outputs...? Here it goes...: OOPS, error (exceptions.ImportError): No module named hyper Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 1387, in dump Pickler(file, protocol, bin).dump(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 231, in dump self.save(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 414, in save_reduce save(func) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 765, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid I have noticed that the error does not occur, when the imported module ('hyper') is in the same directory as the script that pickles. When it is imported from a subpackage (like in the code I sent you) it goes wrong. - harold - -- Reality is for people who lack imagination. -- http://mail.python.org/mailman/listinfo/python-list
Re: Class introspection and dynamically determining functionarguments
On 20.01.2005, at 12:24, Mark English wrote: I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to restrict the functionality to these requirements. I am working on nearly the same thing! Small sort of generic attribute editor in Tkinter (and Tix). Altough my implementation is still very unpythonic (== ugly) in many places, it can edit the attributes of instances and classes, as well as generate new instances / classes. I would like to create new attributes or delete them as well, but haven't done it so far. A still faraway dream would be, to allow the user to enter source code, that will be compiled into byte code and assign it to the instance, so the user can modify code at run time (if it is possible to disallow access to insecure modules while code is compiled). Secondly, the code won't know exactly how to initialise the class instance used to determinte the attributes. Do I need to make it a prerequesite that all instances can be created with no arguments ? I did it this way, too. Maybe you can provide a parameterless __new__ in addition to the __init__. I imagine this is the way that e.g. pickle does the job. Well, I don't know. Let this sentence just be an invitation for an expert to write something here. Should I force/allow the user to pass an instance instead of a class ? However you like. I prefer passing classes, otherwise you end up in a situation where you need to create dummy instances that are only used as "copying templates". If you get an instance: foo = type(bar)() would give you an instance of the same class as bar. But this just looks like a hack to me when compared to foo = Bar(). Passing an instance allows you to look at its __dict__ of course. But you have no assurance that the variables you find there are present in all instances of that class. Phython is just to dynamic for that. Should I be using inspect.getargspec on the class __init__ method and then a loop with a try and a lot of except clauses, or is there a nicer way to do this ? Presumably the pickling code knows how do serialise/deserialise class instances but I'm not sure how I'd use this without already having a class instance to hand. Personally, I ended up writing a class Attribute that provides access to the attributes and allows more finetuning than a generic approach would do (think of e.g. validation). My overall setting works like this: For each attribute that you want to appear in the GUI you define an Attribute class Attribute(object) : def __init__(self, name, # name of the attribute type, # specifies the widget type values=None,# then OptionMenu is used instead validate=None, # if given, a callable that returns # either True or False get=None, # callable to get the actual value # None: generic getattr() widget_options={} # passed to the Tix widget used ) : pass # [...] The "controller" of an editable object gets the object and a list of those Attribute()'s. There is a generic one that handles validation and generic setattr(), but can be overwritten to allow more sophisticated stuff. When creating a new instance, I ask for initial arguments which I know (like __name__ and __doc__ if its a class that I create) in nearly the same way. If you already have your instance, it is possible to generate the Attribute()-list from the dict of this instance: attributes = [ Attribute(name,type(getattr(instance,name))) for name in dir(instance) ] Lastly, does such an app already exist ? As you see, my solution is not as general as what you might have in mind. I needed to finetune so much of the underlying generic plan, that it looks more like declaration-based now. Anyway, if you are interested: This is the edit part of my app (It's only the mapping from attributes to widgets, so no instance creation in this part). As this was only a short snippet in the project I am doing, I could, never give it the time it deserved. So I am sure that my code is not the best sollution, but maybe it serves as a starting point for further discussion. All the best, - harold - import Tkinter import Tix class Attribute(object) : def __init__(self, name, type, values=None, v
Re: eval() in python
> the doc seems to suggest that eval is only for expressions... it says > uses exec for statements, but i don't seem to see a exec function? Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> s="print 'hello Xah Lee :-)'" >>> exec(s) hello Xah Lee :-) >>> - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called "brightness", but it doesn't seem to work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals and parser
Hi, On 22.06.2005, at 23:18, Michael Barkholt wrote: > Is there any detailed documentation on the structure of Pythons > internals, > besides the source code itself? > > More specifically I am looking for information regarding the C parser, > since > I am looking into the viability of using it in another project that > needs > to parse python code (and I would like the code to be written in C). maybe this link might help you: http://wiki.cs.uiuc.edu/cs427/PYTHON -- "Wahrheit ist die Erfindung eines Lügners" -- Heinz von Foerster -- http://mail.python.org/mailman/listinfo/python-list
Re: I need help figuring out how to fix this code.
Hi, > I need help figuring out how to fix my code. I'm using Python 2.2.3, > and > it keeps telling me invalid syntax in the if name == "Nathan" line. The problem is that you indent the if statement. the if/elif/else statements are part of the outer block, so they do not need indentation. > Here is the code if you need it. > #This program asks for a password, then asks for the user's name > after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" name = raw_input("What is your name, plase? ") if name == "Nathan" : print "What a great name!" elif name in ["Madonna","Cher"] : # in better than == here :) print "May I have your autograph please!" else : # don't forget the ":" print name, ", thats a nice name!" cheers, - harold - -- You can imagine the opposite -- Maurizio Nannucci -- http://mail.python.org/mailman/listinfo/python-list
trace function calls to get signatures
Hi all, I am trying to write a script that prints out the signatures of each function call that occurs during the execution of a second script which is invoked by my program. i.e. if the inspected program is 'foo.py': def bar(x,y,z=None) : pass bar(1,"a",bar) bar(2,int) the output of my script should be: foo.bar(int,str,function) foo.bar(int,type,NoneType) I thought I go for sys.settrace() and achieved the following: import sys import types def tracefunc(frame,event,arg) : if event is 'call' : return trace_call(frame,event,arg) else : return None def trace_call(frame,event,arg) : code = frame.f_code scope = frame.f_locals try : print code.co_name+"("+",".join( [ str(type(scope[var])).split("'")[1] for var in code.co_varnames ] )+")" except KeyError : pass return None if __name__ == "__main__" : prog = sys.argv[1] sys.argv.pop(0) sys.settrace(tracefunc) __import__(prog) the output of the above example is: bar(int,str,function) bar(int,type,NoneType) which is pretty close, but I need / would like to improve several things, but have no idea how to do it: 1. I would like to have not only the name of the functions and type arguments but their full package/module/class-path, e.g. xml.dom.pulldom.PullDOM.clear However, I cannot find a way from the frame object to the function object where I could find the information. 2. The KeyError in my code is raised by the "from XXX import" statement: "from distutils import setup" results in File "tracetest.py", line 28, in ? __import__(prog) File "/Volumes/space/Users/harold/uni/pace/dpd/setup.py", line 1, in ? from distutils.core import setup, Extension File "tracetest.py", line 5, in tracefunc if event is 'call' : return trace_call(frame,event,arg) File "tracetest.py", line 12, in trace_call print code.co_name+"("+",".join( KeyError: 'setup' does anyone know how I can circumvent this? 3. Is there any way to set the __name__ attribute for the inspected script to "__main__", so that tracing is really transparent? 4. finally, does a functionality like this already exist in the library or did anyone of you come up with an implementation? thanks, - harold - -- Military intelligence is a contradiction in terms. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditionally implementing __iter__ in new style classes
> I'm trying to implement __iter__ on an abstract base class while I > don't > know whether subclasses support that or not. > Hope that makes sense, if not, this code should be clearer: > > class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > > class Concrete(Base): > def Iterator(self): > yield 1 > yield 2 > yield 3 I don't know how to achieve it, but why don't you simply use class Base: pass class Concrete(Base): def __iter__(self) : yield 1 yield 2 yield 3 What is the advantage to have a baseclass that essentially does some method renaming __iter__ ==> Iterator? - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: inheriting file object
On 06.07.2005, at 18:58, Jeremy wrote: > Hello all, > I am trying to inherit the file object and don't know how to do it. I > need to open a file and perform operations on it in the class I am > writing. I know the simple syntax is: > > class MyClass(file): > ... > > but I don't know how to make it open the file for reading/writing. Can > anyone help me out with this? just invoke file.__init__ inside your own init. if you don't need to do any initializiation in myFile.__init__, just leave the method and file.__init__ will be invoked automatically. class myFile(file) : def __init__(self,fname,mode="r") : file.__init__(self,fname,mode) for line in myFile('testfile') : print line - harold - -- If your only tool is a hammer, every problem looks like a nail. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: inheriting file object
> I don't know if I should be inheriting file or just using a file > object. > How would I determine which one would be more appropriate? Inheritance is often refered to as an IS relation, whereas using an attribute is a HAS relation. If you inherit from file, all operations for files should be valif for your class also. Usually the file-operations would be directly inherited and not overwritten. However, if you don't want to expose all file functionalities, a HAS relation is more appropriate. if you plan to use your class as a file handle, e.g. for formatting output in a special way, I woould prefer to make the file an attribute: class myFile : def __init__(self,fname,mode="r") : self.file = file(fname,mode) def write_formatted(self,string) : # format string self.file.write() If you would tell as your use case, it would be easier to give you an advice. - harold - -- Yesterday is but today's memory and Tomorrow is today's dream. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Cmd.exe Window
On 07.07.2005, at 15:25, Giles Brown wrote: > Nah. You're missing my point. I only want the command window not to > be closed if there is an *exception*. Picky I know, but there you go. well, then register raw_input as exit function: >>> import atexit >>> atexit.register(raw_input) works fine in my terminal. should do in your framework also. cheers, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Cmd.exe Window
On 07.07.2005, at 15:43, harold fellermann wrote: > On 07.07.2005, at 15:25, Giles Brown wrote: > >> Nah. You're missing my point. I only want the command window not to >> be closed if there is an *exception*. Picky I know, but there you go. > > well, then register raw_input as exit function: > >>>> import atexit >>>> atexit.register(raw_input) > > works fine in my terminal. should do in your framework also. sorry, I did not think. if you want to wait for input _only_ if an exception occured, your exit function needs to check for the exception: >>> import atexit >>> >>> def wait_on_exc() : ... import sys ... if sys.exc_type : ... raw_input() ... >>> atexit.register(wait_on_exc) this should do the job, now. - harold - -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing Something Simple
Hi, > I have a list of variables, which I am iterating over. I need to set > the value of each variable. My code looks like: > > varList = [ varOne, varTwo, varThree, varFour ] > > for indivVar in varList: > indivVar = returnVarFromFunction() > > However, none of the variables in the list are being set. You only change the value of the local variable in the body of the for loop. it has no effect on the list. you could do e.g. varList = [vorOne,varTwo,varThree,varFour] for i in len(varList) : varList[i] = returnVarFromFunction() However, as in this example the former list values are not used anyway, you could just write: varList = [ returnVarFromFunction for i varList ] cheers, - harold - -- Tages Arbeit, abends Gäste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing Something Simple
>>> I have a list of variables, which I am iterating over. I need to set >>> the value of each variable. My code looks like: >>> >>> varList = [ varOne, varTwo, varThree, varFour ] >>> >>> for indivVar in varList: >>>indivVar = returnVarFromFunction() >>> >>> However, none of the variables in the list are being set. >>> >> >> You only change the value of the local variable in the body >> of the for loop. it has no effect on the list. you could do e.g. >> >> varList = [vorOne,varTwo,varThree,varFour] >> for i in len(varList) : >> varList[i] = returnVarFromFunction() >> >> However, as in this example the former list values are not used >> anyway, >> you could just write: >> >> varList = [ returnVarFromFunction for i varList ] >> > The problem I have, is the variables are referenced elsewhere. They > have been declared before being used in the list. Basically, I'm > after the Python way of using deferencing. so, if I understand you right, what you want to have is a list of mutable objects, whose value you can change without changing the objects' references. class Proxy : def __init__(self,val) : self.set(val) def set(self,val) : self.val = val def get(self) : return self.val a = Proxy(1) b = Proxy(2) c = Proxy(3) varList = [a,b,c] for i in varList : i.set(returnVarFromFunction()) print a,b,c prints whatever returnVarFromFunction has returned. n.b.: instead of the Proxy class, you can use any other mutable objects, e.g. lists. - harold - -- "All unsere Erfindungen sind nichts als verbesserte Mittel zu einem nicht verbesserten Zweck." -- H.D. Thoreau -- http://mail.python.org/mailman/listinfo/python-list
Re: automatic form filling
> I would like to know how I could automatically fill a > (search) form on a web page and download the resulting > html page. More precisely I would like to make a > program that would automatically fill the "Buscador > lista 40" (in spanish, sorry) form in the following > webpage: > http://www.los40.com/actualidad/listas/lista40.html > and download the results for several dates > (dia/mes/año = day/month/year). > I am not sure this is the right place to ask, but I > would be very grateful if anybody can help or redirect > me to another mailing list... The relevant part of the sites source code is the following: from the first line you can see that submitting the result will request the page "busquedas_b.html" -- so your script has to request this site directly with the form parameters given as additional data (method="POST"). which form parameters to pass can be seen in the name attributes of the input-tags, e.g. . urllib provides the methods urlopen and urlencode to setup the query string and fetch the result: from urllib import urlopen,urlencode form_data = { 'byDay' : '12' , 'byMonth' : '07' , 'byYear' : '2005' } html_data = urlopen( "http://www.los40.com/actualidad/listas/busquedas_b.html";, urlencode(form_data) ).read() print html_data - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I import a py script by its absolute path name?
> for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') > import module_name > > Obviously, this throws: > > ImportError: No module named module_name > > Is there some way to do this? have a look at help(__import__) to import a module whose name is given as a string. - harold - -- Tages Arbeit, abends Gäste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe -- http://mail.python.org/mailman/listinfo/python-list
How to extend inner classes?
Thank you very much. Of course I know how to do it in python. The problem is that I want to reimplement these classes as a python extension in C. The question is: how can I add class members (like e.g. inner classes) to a PyTypeObject defined in a C extension? - harold - > You can define a class variable Pos with the class Pos as its value > > class PeriodicGrid : > class Pos: > pass > Pos = Pos > > >>> grid = PeriodicGrid() > >>> grid.Pos() > <__main__.Pos instance at 0x00EEFAD0> > > Ciao > Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Keyword arguments - strange behaviour?
Hi, I cannot see any strange behavior. this code works exacly as you and I suspect: >>> def otherfunction(x) : ... return x ... >>> def function(arg=otherfunction(5)) : ... return arg ... >>> function(3) 3 >>> function() 5 Or is this not what you excepted? - harold - On 21.12.2004, at 15:47, [EMAIL PROTECTED] wrote: def function(arg=otherfunction(value)): return arg My expectation would have been that otherfunction(value) would be called if (and only if) the arg keyword parameter was missing from the function() call (ie. the optional value is evaluated the lazy way). Also, otherfunction would be called each and every time this function() is called without the arg keyword. (At least, I would have assumed this before today) Still, I can see why it's been implemented the way it has, it just seems a shame there isn't a neat shortcut to default lots of optional arguments to new mutable objects. And since I'm not the only one to fall into this trap it makes me wonder why the default behaviour isn't made to be what most people seem to expect? -- http://mail.python.org/mailman/listinfo/python-list -- Freunde, nur Mut, Lächelt und sprecht: Die Menschen sind gut -- Bloß die Leute sind schlecht. -- Erich Kästner -- http://mail.python.org/mailman/listinfo/python-list
copying classes?
Hi all, In the documentation of module 'copy' it is said that "This version does not copy types like module, class, function, method, stack trace, stack frame, file, socket, window, array, or any similar types." Does anyone know another way to (deep)copy objects of type class? What is special about the objects of these types that they cannot be easily copied? Any help appreciated, - harold - -- I like pigs. Dogs look up to us. Cats look down to us. Pigs treat us as equal. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Re: copying classes?
On 30.12.2004, at 01:24, It's me wrote: I would not think that a generic deepcopy would work for all cases. An object can be as simple as a number, for instance, but can also be as complex as the universe. I can't imagine anybody would know how to copy a complex object otherthen the object itself. I always think that a well designed object should have a copyme method. :=) take a look at the __setstate__ and __getstate__ documentation of copy (e.g. pickle) -- with them you can customize the copying task. Anyway, they work only on instance but not on class objects :( - harold - -- Military intelligence is a contradiction in terms. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: property and virtuality
Hello, I asked this question some time ago, but as I got no answer, so I just try it a second time. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
class attributes and inner classes in C extensions
Hello, I just posted this question with a wrong subject... So here again with a better one. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? O.k. I found it out now, and in order to improve the knwoledge base of the mailing list, I will answer my question myself. The PyTypeObject structure has a field tp_dict that holds the dictionary of the class object. You can initialize it with a dictionary that holds class attributes. If you provide a custom dictiomary, you must do so _before_ PyType_Ready() is called, because PyType_Ready adds other entries to this dictionary. This is my C extension of the above. It works great for me: static PyTypeObject FooType = { /* ... snip ... */ 0, // tp_dict /* ... snip ... */ }; static PyTypeObject FooBarType = { /* ... snip ... */ }; PyMODINIT_FUNC inithyper(void) { /* the following lines add class attributes to the types tp_dict: */ FooType.tp_dict = PyDict_New(); PyDict_SetItemString(FooBarType,"Bar",(PyObject *)&FooBarType); PyDict_SetItemString(FooBarType,"spam",PyString_FromString("foobar")); PyObject* m; if (PyType_Ready(&hFooType) < 0) return; if (PyType_Ready(&hFooBarType) < 0) return; m = Py_InitModule3("my_module", NULL, "some documentation"); Py_INCREF(&FooType); PyModule_AddObject(m, "Foo", (PyObject *)&FooType); Py_INCREF(&hyper_FooBarType); PyModule_AddObject(m, "Bar", (PyObject *)&FooBarType); } Documentation for tp_dict can be found in the API: http://docs.python.org/api/type-structs.html - harold - -- "2x2 = grün" -- Heinz von Foerster -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I think you could as well, after PyType_Ready() is called, set it yourself with PyObject_SetAttrString(FooType, "Bar", FooBarType); You *may* have to cast the FooType and FooBarType to (PyObject *), to avoid compiler warnings. I tried this. Its shorter and and works fine, too. thanks for the proposal. - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called "brightness", but it doesn't seem to work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: Class, object question.
What I am wondering is if I have a 2nd init or something similar to create a vector. Such as what follows and if I can how do I go about implementing it? Class vector(point): def __init___(self, point1, point2): self.i = point2.get_x() - point1.get_x() self.j = point2.get_y() - point1.get_y() self.k = point2.get_z() - point1.get_z() def __init___(self, i, j, k): self.i = i self.j = j self.k = k That way I can define a vector either using 2 points or if I have the vector data itself? Well, what you want to do -- polymorphism of function signatures -- can be implemented like this: class vector_1(point) : def __init__(self,*args) : if len(args) == 2 and isinstance(args[0],point) and isinstance(args[1],point) : self.i = args[0].get_x() - args[1].get_x() self.j = args[0].get_y() - args[1].get_y() self.k = args[0].get_z() - args[1].get_z() elif len(args) == 3 : self.i,self.j,self.k = args else : raise ValueError, "wrong arguments for instance initialization" You can also find a nice implementation by Guido van Rossum using decorators at Artima (look for multimethods). However, I would prefer to avoid this sort of polymorphism because it only obfuscates your code. IMHO, there should be exactly one clear way to initialize an instance. Therefore, I suggest the provide a class method that serves as a special instance factory: class vector_2(point) : def __init__(self,i,j,k) : self.i = i self.j = j self.k = k @classmethod def difference(cls,point1,point2) : return cls( point1.get_x() - point2.get_x(), point1.get_y() - point2.get_y(), point1.get_z() - point2.get_z() ) # how to use it: point1 = Point(4,5,6) point2 = Point(1,2,3) vec = vector_2.difference(point1,point2) I wonder, why your vector inherits from point though. And of course, class is written lower case. Cheers, - harold - -- Es ist schon längst alles gesagt worden -- aber noch nicht von jedem. -- Karl Valentin -- http://mail.python.org/mailman/listinfo/python-list
richcmpfunc semantics
Hi all, I want to implement rich comparision in an extension class. Problem is I cannot find good documentation of the richcmpfunc semantics. Given the signature richcmpfunc compare(PyObject *,PyObject, int); I supposed the two objects passed are the ones to be compared. What is the meaning of the integer argument? Does it specify the kind of comparision operator (e.g. __eq__ or __le__), and if so, how? What is my richcmpfunc supposed to return? 0 or 1 indicating False or True? What has to be done, if the function is invoked for an operator I don't want to define? Maybe there is some good documentation available, but I cannot find it. So, any references or help is appreciated. Cheers, - harold - -- "Scientist are very good in answering the questions they choose to answer." -- Richard Alley -- http://mail.python.org/mailman/listinfo/python-list
Re: richcmpfunc semantics
Thank you Greg, I figured most of it out in the meantime, myself. I only differ from you in one point. What has to be done, if the function is invoked for an operator I don't want to define? Return Py_NotImplemented. (Note that's return, *not* raise.) I used PyErr_BadArgument(); return NULL; instead. What is the difference between the two and which one is to prefer. Also, do you need to increment the reference count of Py_NotImeplemented before returning it? Thanks, - harold - -- I like pigs. Dogs look up to us. Cats look down to us. Pigs treat us as equal. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent string.find method for a list of strings
I have read a text file using the command lines = myfile.readlines() and now I want to seach those lines for a particular string. I was hoping there was a way to "find" that string in a similar way as searching simply a simple string. I want to do something like lines.find.('my particular string') Is there a module that already exists that allows me to do this or will I have to created my own method? file.readlines() returns a list of lines. You can either call find on each element in this list, like: for line in myfile.readlines() : if line.find('my particular string') : do_something() of just read in the whole file, if you are not interested in the particular line, where 'my particular string occurs': myfile.read().find('my particular string') Cheers, - harold - -- "All unsere Erfindungen sind nichts als verbesserte Mittel zu einem nicht verbesserten Zweck." -- H.D. Thoreau -- http://mail.python.org/mailman/listinfo/python-list
curses for different terminals
Hi all, I want to use curses in a server application that provides a GUI for telnet clients. Therefore, I need the functionality to open and handle several screens. Concerning http://dickey.his.com/ncurses/ncurses-intro.html#init this can be done using the function newterm(type,ofp,ifp). However, this function seems not to be defined in the python library. Does anyone know how this can be done in python? cheers, - harold - -- Life is what happens while you're busy making other plans -- John Lennon -- http://mail.python.org/mailman/listinfo/python-list
Re: curses for different terminals
On 14.04.2005, at 19:17, Christos TZOTZIOY Georgiou wrote: On Thu, 14 Apr 2005 18:39:14 +0200, rumours say that harold fellermann <[EMAIL PROTECTED]> might have written: Hi all, I want to use curses in a server application that provides a GUI for telnet clients. Therefore, I need the functionality to open and handle several screens. Just to make sure we understand what you want to do: 1. Are you doing an single process application that produces output on many terminals? ie the program is kind of like a service? gotcha. I want to write a TCP server that handles incoming requests in threads (one thread per request using SocketServer.ThreadingTCPServer). Now, I want the server to use curses for client-server communication (client will be telnet). Thus, my programm runs in a single process (although several threads) and provides several curses screens (one for each client.) Concerning http://dickey.his.com/ncurses/ncurses-intro.html#init this can be done using the function newterm(type,ofp,ifp). However, this function seems not to be defined in the python library. Does anyone know how this can be done in python? Select one of the above, or describe more the desired situation if I didn't cover your case, and we will try to help you more. great, thanks, - harold - -- Dieses Schreiben wurde maschinell erstellt und bedarf daher keiner Unterschrift. -- -- http://mail.python.org/mailman/listinfo/python-list
ScientificPython - LeastSquareFit diverges
Dear all, I am trying to fit a powerlaw to a small dataset using Scientific.Functions.LeastSquares fit. Unfortunately, the algorithm seems to diverge and throws an OverflowException. Here is how I try it: >>> from Scientific.Functions.LeastSquares import leastSquaresFit >>> >>> data = [ ... (2.5, 589.0, 0.10001), ... (7.5, 442.0, 0.10001), ... (12.5, 96.0, 0.10001), ... (17.5, 36.0, 0.10001), ... (22.5, 16.0, 0.10001), ... (27.5, 7.0, 0.10001), ... (32.5, 6.0, 0.10001), ... (37.5, 3.0, 0.10001), ... (42.5, 3.0, 0.10001), ... (47.5, 1.0, 0.10001), ... (52.5, 3.0, 0.10001), ... (57.5, 1.0, 0.10001), ... (67.5, 1.0, 0.10001), ... (77.5, 2.0, 0.10001), ... (82.5, 1.0, 0.10001), ... (87.5, 2.0, 0.10001) ... ] >>> >>> def powerlaw((a,b),x) : ... return a*x**b ... >>> params,chisq = leastSquaresFit(powerlaw,(10,-3),data) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py", line 72, in leastSquaresFit next_chi_sq, next_alpha = _chiSquare(model, next_p, data) File "/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py", line 22, in _chiSquare f = model(parameters, point[0]) File "", line 2, in powerlaw File "/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py", line 182, in __rpow__ return pow(other, self) File "/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py", line 171, in __pow__ raise OverflowError, "Numerical result of pow(%s,%s) out of range." % (self.value,other.value-1) OverflowError: Numerical result of pow(2.5,8376.79243687) out of range. >>> I added some debugging output in /usr/lib/python-2.4/site-packages/Scientifc/Functions/LeastSquares.py in the function _chiSquare that prints the fit parameters during the Levenberg-Marquardt iteration. The procedure seems do diverge after the first step: ((10, [1]), (-3, [0, 1])) [(-67402.311817579117, [1]), (8377.7924368716158, [0, 1])] Note that I could easily fit the above data using gnuplots internal fitting procedure. Any idea what is going wrong here? Is it a known problem? Are there any work arounds or other packages? Any help is appreciated! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter help
hi, groves wrote: > Now let me tell you that i was able to create a simple listbox which > had 6 options which one can select, but Now what I want is that from > the available menu, if I select an option it should give me another > menu associated with that option. Its like digging up that option to do > advance search. If I understood you correctly, this is how I would go for it: consider to create all submenus during initialization but make them invisible (put each of them in a single frame) anf toggle the visibility of these frames in the handler of your option menu. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: ScientificPython - LeastSquareFit diverges
Thanks for your advices, Terry and Konrad, using the linear fit as initial condition for the pawerlow fit works pretty well for my data. (I already had the two calculations but performed them vice versa ... :-) Anyway, I had the impression that the leastSquaresFit in Scientific Python is an implementation of the Levenberg Marquardt algorithm as it is presented in the Numerical Recipes. Accoring to reviews, this algorithm is not famous for its stability (e.g. http://www.stanford.edu/class/cme302/wnnr/nr.html). Better implementations are out there (e.g. http://www.ics.forth.gr/~lourakis/levmar/). Are there any plans to improve the SciPy algorithm? Would it be a welcome contribution to SciPy to work this part out? - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: A suggestion/request for IDEs
John Salerno wrote: > I apologize for the slightly off-topic nature, but I thought I'd just > throw this out there for anyone working on text editors or IDEs with > auto-completion. > > I think it should be a feature, when an item is selected for > auto-completion in a drop-down box, that pressing the spacebar (in > addition to tab or enter) will automatically finish the word and add a > space. This is how Microsoft's new IDEs for .NET work, and I found it > very helpful to be able to just press space as normal and keep typing. I > know it sounds minor, but I find it to be a time saver instead of having > to press tab or enter, and then also the spacebar. > > Thanks. I use Eclipse with PyDev and PyDev extensions. SlickEdit (awesome editor) has auto-completion as well. -- http://mail.python.org/mailman/listinfo/python-list
how to switch from os.tmpnam to os.tmpfile
Hi, I need to create a temporary file and I need to retrieve the path of that file. os.tmpnam() would do the job quite well if it wasn't for the RuntimeWarning "tmpnam is a potential security risk to your program". I would like to switch to os.tmpfile() which is supposed to be safer, but I do not know how to get the path information from the file object returned by tmpfile(). any clues? thanks! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: From Python to Shell
> Im not a total noob but i don't know the command and the module to go > from python to the default shell. there are several ways depending on what exactly you want to achieve: sys.exit(return_value): terminates the python process and gives controll back to the shell os.system(command_string): execute command string in a subshell. result is the return value of command_str subprocess.Popen(command): starts command as a subprocess and allows you to "communicate" with that process, i.e. lets you send something to its stdin and retrieve data from its stdout and stderr streams. have a look at the docs of that module for more information. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: how to switch from os.tmpnam to os.tmpfile
Maric Michaud wrote: > Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a écrit : > > to os.tmpfile() which is supposed to be safer, but I do not know how to > > get > > the path information from the file object returned by tmpfile(). any > > clues? > There is no path for tmpfile, once it's closed, the file and its content are > lost. from the doc : > " The file has no directory entries associated with it and will be > automatically deleted once there are no file descriptors for the file." > > You must maintain a reference to it in your program untill you don't need it > anymore. I am doing so. But still, I need its path. To give you some context: I have an app built on Tk that uses gnuplot behind the scenes. My application creates a temporary file where which gnuplot writes its results to (using the tkcanvas terminal). Later, I load the contents of that file into the a tk canvas. I don't care about the temporary file after my app is closed, so I have its reference all the time. But I need its path to tell both gnuplot and tk where to read/write data to/from. class PlotWindow(Tk.Canvas) : def plot(self,commands) : tmp = os.tmpnam() gnuplot = subprocess.Popen( "gnuplot", shell=True, stdin=subprocess.PIPE, stdout=file(tmp,"w") ) stdout,stderr = gnuplot.communicate(""" set terminal tkcanvas interact set output "%s" """ % tmp + commands) assert not stderr self.tk.call("source",tmp) self.tk.call("gnuplot",self._w) Of course, I could just use matplotlib or Gnuplot.py but the problem is not necessary enough to make any refacturing. If there is no way to use os.tmpfile(), I just go ahead with the security warning. Its only a small personal app, anyway. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: how to switch from os.tmpnam to os.tmpfile
Chris Lambacher wrote: > You should be able to find exactly what you need in the tempfile module. > http://docs.python.org/lib/module-tempfile.html thanks! tempfile.NamedTemporaryFile() is exaclty what I have been looking for. Using python for such a long time now, and still there are unknown goodies in the library, great :-) - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching and manipulating lists of tuples
MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] > > I tried to create an algorithm of the following form: > >>> def algorith(list,str): > ... flag = True > ... for l in list: > ... if l[0] == str: > ... l[1] += 1 > ... flag = False > ... if flag: > ... list.append((str,1)) > ... > > > But: > > >>> algorith(L,"X") > > gives: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in algorith > TypeError: object does not support item assignment Your approach does not work because the tuples in the list a imutable. The problem occurs in the line l[1] += 1. You could solve the problem by using lists of lists, rather than lists of tuples. However, if you only want to know the frequency of items in the list (i.e. want to build a histogram) and you are not interested in the original order of items in the list, a dictionary is suited better for this task, because you avoid the linear time behavior of: def histogram(liste) : result = {} for item in liste : result[item] = result.get(item,0) + 1 return result.items() -- http://mail.python.org/mailman/listinfo/python-list
Using SQLite3 with python 2.5 beta
>From the release notes I read that "If you're compiling the Python source yourself, note that the source tree doesn't include the SQLite code, only the wrapper module. You'll need to have the SQLite libraries and headers installed before compiling Python, and the build process will compile the module when the necessary headers are available." I do have SQLite3 installed on my system, but after doing a plain vanilla compilation of the the 2.5 beta and trying the SQLite code given in the release notes I get the message "NameError: name 'sqlite3' is not defined". I wonder what the requirement means that "when the necessary headers are available"? How would they need to be made available? Does anyone have any success with this? -- http://mail.python.org/mailman/listinfo/python-list
Re: mp3 libs and programs
hi, Jay wrote: > I'm writing a python script that involves playing mp3 files. The first > approach I had was sending commands to unix command-line programs in > order to play them. I tired mpg123 and moosic, but there was a key > feature to my program's success that's missing. SEEK! I need to be > able to start playing a song at an arbitrary point in the song. I > can't find anything to let me do this. Does anyone have any advice or > has anyone needed something similar? check out pyxmms. -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb for Python 2.5
Hi everyone, Does anyone know the status of a version of MySQLdb that will work with Python 2.5? I will accept a workaround if you know one. Thanks in advance. Harold Trammel -- http://mail.python.org/mailman/listinfo/python-list
Generating text files (newbie)
Assume I have a tab-delimited text file called foo.txt organized as follows: x11 -0.04 x22 -0.42 x33 0.3 My goal is to read in this file and use the information therein to output a new file that is organized as follows: x11 IRM=3PL IPB= -0.04 x22 IRM=3PL IPB= -0.42 x33 IRM=3PL IPB= 0.3 I am a newbie with python and am trying to put the pieces together. Now, I know if I had a list, I could do something like: a = [-0.04, -0.42, 0.3] >>> for i in a: print "IRM = 3PL", "\t", "IPB = ", i IRM = 3PL IPB = -0.04 IRM = 3PL IPB = -0.42 IRM = 3PL IPB = 0.3 And then I could write this to a file. But I am not sure how to I might tackle this when I read in a text file. So far, my basic skills allow for me to accomplish the following # read in file params = open('foo.txt', 'r+') # Write to the file params.write('Add in some new test\n') params.close() Any pointers are appreciated. I'm using python 2.3 on a windows xp machine. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Beginner question on text processing
I am beginning to use python primarily to organize data into formats needed for input into some statistical packages. I do not have much programming experience outside of LaTeX and R, so some of this is a bit new. I am attempting to write a program that reads in a text file that contains some values and it would then output a new file that has manipulated this original text file in some manner. To illustrate, assume I have a text file, call it test.txt, with the following information: X11 .32 X22 .45 My goal in the python program is to manipulate this file such that a new file would be created that looks like: X11 IPB = .32 X22 IPB = .45 Here is what I have accomplished so far. # Python code below for sample program called 'test.py' # Read in a file with the item parameters filename = raw_input("Please enter the file you want to open: ") params = open(filename, 'r') for i in params: print 'IPB = ' ,i # end code This obviously results in the following: IPB = x11 .32 IPB = x22 .45 So, my questions may be trivial, but: 1) How do I print the 'IPB = ' before the numbers? 2) Is there a better way to prompt the user to open the desired file rather than the way I have it above? For example, is there a built-in function that would open a windows dialogue box such that a user who does not know about path names can use windows to look for the file and click on it. 3) Last, what is the best way to have the output saved as a new file called 'test2.txt'. The only way I know how to do this now is to do something like: python test.py > test2.txt Thank you for any help -- http://mail.python.org/mailman/listinfo/python-list
RE: Wow, Python much faster than MatLab
R is the open-source implementation of the S language developed at Bell laboratories. It is a statistical programming language that is becoming the de facto standard among statisticians. Rpy is what allows an interface between python and the R language. Harold > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On > Behalf Of Stef Mientki > Sent: Saturday, December 30, 2006 9:24 AM > To: python-list@python.org > Subject: Re: Wow, Python much faster than MatLab > > Mathias Panzenboeck wrote: > > A other great thing: With rpy you have R bindings for python. > > forgive my ignorance, what's R, rpy ? > Or is only relevant for Linux users ? > > cheers > Stef > > > So you have the power of R and the easy syntax and big > standard lib of > > python! :) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about extending the interperter
> The problem for me is that the pointer "p" in the last function points > to the arguments: > If a user caller foo("123") - p points to '123'. > What I need is to point it to the whole string received - 'foo > ("123")'. > > Is there a way I can do this? no. at least not a simple one. you can obtain the function name by func_name, as the corresponding python code suggests: >>> def f() : ... pass ... >>> print f.func_name f However, you still don't know, how the function has been invoked. Consider: >>> g=f >>> print g.func_name f of course, the situation can be much more sphisticated. f could be a value in a dict returned by some other function, and so on. Of course there are ways to inspect the source code (like pdb or exceptions do), but are you sure this is the functionality to want? Cheers, - harold - -- Learn from the mistakes of others. You can't live long enough to make them all yourself. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring self in PyObject_CallMethod
Hi, > Calling a python method from C++ has the following signature: > > PyObject * > PyObject_CallMethod(PyObject *self, char *method_name, > char *arg_format, ...); > > I'm having trouble figuring out how to declare self. > > Let's say my python file is called stuff.py and is like the following, > doMath() is defined in stuff.py and is not part of any class: > > #stuff.py > > def doMath(): >val = val + 1 > > > In C++, I think my codes should be like the following: > > PyObject *resultObj = PyObject_CallMethod( self, "doMath", ""); > > What do I put for self? Any help please? it looks like you are confusing methods (bound to class objects) and functions (bound to modules). if your doMath is a function defined in a module, use PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) i.e. PyObject resultObj = PyObject_Call(doMath,NULL,NULL); If, however, doMath is declared as a class-bound method, you have to use PyObject_CallMethod() with a pointer to an instance of this class as the first argument. Cheers, - harold - -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
Hi, > I want a reliable way of knowing when the child > thread finished execution so that I can make the main thread wait till > then. > > Any ideas? use a lock. the subthread allocates the lock and releases it after processing. the main thread must wait until the lock is released. otherwiese, use the higher level Threading module which provides a function Thread.join that allows the main thread to wait for the subthread. I think it uses the same mechanism that I explained above. - harold - -- Outside of a dog, a book is a man's best friend: and inside a dog, it's too dark to read. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
we had some off-group mails. A summary is posted to improve the knowledge base of the list. Prashanth wrote: > Hi, > > I can use the threading module but I am just looking if there is a > reliable way using the thread module. > > If I use a lock... > Let us assume that the child thread has done a lck.release() but does > not get a chance to quit before execution is whisked away from it and > given to the main thread. Now the main thread sees that the lock has > been released and quits. The child thread hasn't quit yet and we are > back in the same problem. > > Don't you think? Harold wrote: I think it depends on when you release the child lock. if you do it after refering to any data, e.g. as the last command in the child thread, you should be on the save side, no? - harold - > Yes, I can assume that in most cases. However I don't think it happens > so always. Even though infinitesimal, there is still a chance that it > will not quit. I am looking for a mechanism using which I can make > sure. I don't understand what you mean. Why should the following code fail in any case? import thread def parentThread() : lock = thread.allocate_lock() child = thread.start_new_thread(childThread,(parent,)) lock.acquire() def childThread(parent) : parent.lock.acquire() do_something_with_vars_from(parent) parent.lock.release() # don't do anything with parents vars after releasing the lock I did not test it, but I cannot see any reason why this should fail. > After the childThread executes parent.lock.release() execution may be > taken away from it and given to the parent thread(note that the child > thread hasn't quit yet). The parent thread which is waiting on the > lock gets released and quits. Now the "still running" child thread > tries to exit and based on my assumption attempts to call some cleanup > func in some module which has been GC'ed due to the exit of the parent > thread. This leads to an exception being thrown. o.k. with this assumption, things might become a little more tricky. one possibility: bind the modules you use to local variables in your child thread. then they won't be GC'ed before childThread stops. or (better): use Threading. it really isn't complicated to change your code and timing issues become much simpler. Referencing the module locally on the child thread does not seem like an elegant solution besides I don't know which modules are involved in cleaning up. Yes, I will use the Threading module but am just curious as to what can be done to reliably use thread module. -- http://mail.python.org/mailman/listinfo/python-list
Re: redirecting messgaef from sys.stdout
On 07.06.2005, at 16:43, Ahmad Hosseinzadeh wrote: > Hello, > > I’m trying to run an external program in my > application. Both are coded in python. I need to write > an independent module that is used in the main > application. Its responsibility is to run the external > program and redirect its stdout and stderr to the main > application. > The application’s stdout and stderr are set to an > object and they are not command prompt anymore. > The output is selected by a flag; if true the stdout > and stderr will be redirected to application’s stdout > and stderr. If false, the stdout and stderr will be > redirected o command prompt. I don’t know how to > redirect the output. > Can anyone help please? have a look at: http://www.python.org/doc/current/lib/module-popen2.html -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
On 07.06.2005, at 16:44, harold fellermann wrote: > import thread > > def parentThread() : > lock = thread.allocate_lock() > child = thread.start_new_thread(childThread,(parent,)) > lock.acquire() > > def childThread(parent) : > parent.lock.acquire() > do_something_with_vars_from(parent) > parent.lock.release() > # don't do anything with parents vars after releasing the lock > > > I did not test it, but I cannot see any reason why this should fail. > >> After the childThread executes parent.lock.release() execution may be >> taken away from it and given to the parent thread(note that the child >> thread hasn't quit yet). The parent thread which is waiting on the >> lock gets released and quits. Now the "still running" child thread >> tries to exit and based on my assumption attempts to call some cleanup >> func in some module which has been GC'ed due to the exit of the parent >> thread. This leads to an exception being thrown. >> Referencing the module locally on the child thread does not seem like an >> elegant solution besides I don't know which modules are involved in >> cleaning I wander how much an issue this fear really is. To my understanding, this situation can only happen, when the child thread accessess a module that was imported locally within the parent thread. Does anyone with a better understanding of the internals of the interpreter know whether such a thing can occur? If so, in what circumstances? - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 15:52, Xavier Décoret wrote: > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have >>>> a=A() > and I want to write >>>> a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? the short answer is: no. the long answer: if you write >>> a=A() an instance of class A is created and bound to the local identifier 'a'. If you later write >>> a=5 the object 5 is reassigned to the same identifier, deleting whatever value was stored there before. The identifier itself does not impose any restrictions on the type of instances that can be bound to it. Binding an instance of class A in the first part, does not make the identifier of the kind 'can-only-bind-A-instances'. In other words: identifiers don't have types. Thus, there is no mechanism that allows to change the binding behavior of identifiers. As a general advise, don't try to write C++ in python. I think, for most cases, there are far better solutions than changing the assign operator anyway... explicit is better than implicit: If class A has only one dedicate value and no internal state, make it a construcotr call: >>> a=A(5) Otherwise, it is worth mentioning the name of the member to set. IMHO this increases the readability of your source code: >>> a.pressure=5 Cheers, - harold - -- "I was born not knowing and have had only a little time to change that here and there." -- Richard Feynman -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
> to return 'WHERE name LIKE %smith%'I have tried using escapes, > character codes for the % sign, and lots of other gyrations with no > success. The only thing that works is if I modify searchterm first: > >searchterm = 'smith' >searchterm ='%'+'smith'+'%' >sql += 'WHERE name LIKE %s' % searchterm > > Any Ideas? >>> "%%%s%%" % "here you go" '%here you go%' Cheers, - harold - -- If your only tool is a hammer, every problem looks like a nail. -- -- http://mail.python.org/mailman/listinfo/python-list
extending Python base class in C
Hi all, I once read that it is possible to use a python base class for a C extension class. To be precise, I want to achieve the following behavior: class PythonClass : pass class CClass(PythonClass) : "this class should be implemented as C extension" pass Unfortunately, google could not find me the right reference. Does anyone know how to do it, or where I can find relevant information? Thanks, - harold - -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 19:23, Terry Reedy wrote: > > "harold fellermann" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> if you write >>>>> a=A() >> an instance of class A is created and bound to the local identifier >> 'a'. > > I think it perhaps better to think of the label 'a' being bound to the > object rather than vice versa. For one, a label can only be bound > (stuck > to, like a stick note) to one object at a time while one object can > have > many labels (and other references) stuck to it. > >> If you later write >>>>> a=5 >> the object 5 is reassigned to the same identifier, > > Or one could say that the label 'a' is removed from the A() object and > reassigned to the 5 object. Since the 5 object may have numerous other > connections, and since those connections are unaffected by the new > connection to 'a', whereas the previous assignment of 'a' is broken, I > think it better to say that 'a' is being reassigned, not 5. yeah. I have never seen it this way, but you are right! Binding the identifier/label to the object is a much better perspective. thanks for the lesson :) - harold - -- Ceci n'est pas une signature. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: translating C++ exceptions to python
On 13.06.2005, at 13:23, [EMAIL PROTECTED] wrote: > Hi all, > > I have a C++ library I call from python. The problem is I have c++ > exceptions that i want to be translated to python. I want to be able to > do stuff like: > try: > my_cpp_function() > except cpp_exception_1: > do_stuff > except cpp_exception_2: > do_other_stuff > > any ideas how can i do the translation? If you do not already use it, have a look at http://www.boost.org/libs/python/ a C++ -- library to wrap the Python C API, i.e. it helps you to extend Python in C++. AFAIK it has fascilities to transform exceptions from one type into the other. - harold - --- Everybody lies. but it does not matter, as no one listens. --- -- http://mail.python.org/mailman/listinfo/python-list
Problem with simple C extension
} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inithyper(void) { PyObject* m; m = Py_InitModule3("hyper", hyper_methods, "Faster C implementation of the underlying physics."); hyper_PhysicsDPDType.tp_new = PyType_GenericNew; if (PyType_Ready(&hyper_PhysicsDPDType) < 0) return; Py_INCREF(&hyper_PhysicsDPDType); PyModule_AddObject(m, "physics_DPD", (PyObject *)&hyper_PhysicsDPDType); } Now, compilation and import works without problem. But I cannot assign members in the init-call. >>> import simulation.hyper.physics_DPD as Physics >>> p = Physics(1,2,3,4) 0.00 0.00 0.00 0.00 >>> p.friction 5.3049894774131808e-315 I must be blind today. Can anyone see what I am doing wrong in init??? Thanks a lot! - harold - -- A country without army is like a fish without bicycle. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with simple C extension
On 14.06.2005, at 18:58, harold fellermann wrote: > Am I stupid or what? Yes I was ... > // PhysicsDPD instance structure > typedef struct { >PyObject_HEAD >double cutoff; >double friction; >double noise; >double dt; > } hyper_PhysicsDPD; > > > // > // tp_init > // > static int > hyper_PhysicsDPD_init(hyper_PhysicsDPD *self, PyObject *args, PyObject > *kwds) > { >if (!PyArg_ParseTuple(args,"", > &self->cutoff, > &self->friction, > &self->noise, > &self->dt > )) > return -1; > >printf("%f %f %f > %f\n",self->cutoff,self->friction,self->noise,self->dt); > >return 1; > } format string must be "" - as the members are defined as doubles, not floats. Sorry to bother you. - harold - -- A country without army is like a fish without bicycle. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: extending Python base class in C
> "harold fellermann" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > Hi all, > > I once read that it is possible to use a python base class for a C > extension class. On 14.06.2005, at 09:29, Grigoris Tsolakidis wrote: > There was good article of how to do this on DDJ home page www.ddj.com unfortunately, I could not find it yet. I managed to do the following: I the initmodule function of my extension, I import the module and look for the class I want to use as a base class: PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; This gives me a pointer to the class I want to use as base class. Does anyone know how to assign this to the extension class? I tried to build a tuple (BaseClass,) and assign it (after the respective PyType_Ready call) to CClass.__bases__ like this: PyObject_SetAttrString( &cclassType, "__bases__", Py_BuildValue("(O,)",base_class) ); but this raises a TypeError when executed during import: TypeError: can't set attributes of built-in/extension type 'ext_module.CClass' Any ideas how to proceed? - harold - -- You can imagine the opposite -- Maurizio Nannucci -- http://mail.python.org/mailman/listinfo/python-list
Re: extending Python base class in C
Yah! Finally, I got the thing to work. Here is how I did it. /* import the module that holds the base class */ PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; /* get a pointer to the base class */ PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; /* assign it as base class */ cclassType.tp_bases = Py_BuildValue("(O)",BaseClass); I am doing all this before the call to PyType_Ready() -- as Scoot Daniels suggested. Using the python API's SetAttrString() did not work (I suppose for the same reason, why assigning cls.__bases__ does not work in pure python either). I also checked cclassType.tp_base = (PyTypeObject *) base_class; which also works and I am not aware of the difference of these two slots. Anyway, for my simple purposes it works just fine. - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." -- http://mail.python.org/mailman/listinfo/python-list
Re: dir() with string as argument
On 16.06.2005, at 20:59, Shankar Iyer ([EMAIL PROTECTED]) wrote: > Hi, > > Suppose I have a string, sModuleName, that contains the name of a > module. I now want to see what functions are in that module, but if I > call dir(sModuleName), I instead get the list of operations that can > be done on a string. Is there any way to convert the string into a > format that I could feed to dir to cause the desired effect? I think > I could modify the string a bit and then use the exec command, but I > was advised against that on this board last week. you have to import the module: name = "sys" mod = __import__(name) dir(mod) - harold - -- Bitte verlassen Sie diese Welt so, wie Sie sie vorfinden möchten. -- -- http://mail.python.org/mailman/listinfo/python-list
Output to csv
I've hacked together a small utility program that I assume can be written much better. The program reads in output from a statistical program and spits out the relevant data needed. The purpose of the program is to reach into the original data file (which is a text file), pull out the relevant informaiton, and spit out a file that can be opened in Excel in order to create tables for some reports we need. To accomplish this, I enter in commas by brute force so that the output is a csv file that excel can open. This program works fine, but, as I am still learning python, I am interested in ways to write better code. If anyone has any suggestions, they are most appreciated. Below is the program in its current form. Harold filename = raw_input("Please enter the WinSteps ISF file: ") new_file = raw_input("Enter the name of the csv file to output: ") # create a new file defined by the user f = open(new_file, 'w') f.write("Num, Measure, SE, Measure, SE, Measure, SE, Measure, SE \n") params = open(filename, 'r') for line in params: x = line if x[15] == '1': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',,,' elif x[15] == '2': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',,' elif x[15] == '3': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',' ,x[140:147], ',' ,x[149:155], ',' elif x[15] == '4': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',' ,x[140:147], ',' ,x[149:155], ',',x[190:197], ',' ,x[199:205] f.close() -- http://mail.python.org/mailman/listinfo/python-list
Sorting Unix mailboxes
Was your mailbox module competed? If so where can i find it? -- http://mail.python.org/mailman/listinfo/python-list
Checking if elements are empty
Dear list: Suppose I have a string as follows x = ' \t'ff' I can split this up as y = x.split('\t') Which gives [ ' ', 'ff'] len(y) 2 Is there a way to check if the first element of y is null? -- http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
Hi Alan, > One last point. While I remain interested in examples of how > "late" addition ofattributesto class instances is useful, > I must note that everyone who responded agreed that it > has been a source of bugs. This seems to argue against a > general ban on "locking" objects in some way, in some > circumstances. If you want to restrict "late" addition of attributes, no-one will prevent you to do so. Arnaud has already given you an example implementation. Here is mine: >>> class Foo(object) : ... ... _locked = False ... ... def __setattr__(self,attr,var) : ... if self._locked and not attr in dir(self): ... raise RuntimeError ... else : ... object.__setattr__(self,attr,var) ... ... def lock(self) : ... self._locked = True ... >>> foo = Foo() >>> foo.bar = 'allowed' >>> foo.lock() >>> foo.spam = 'fails' Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __setattr__ NotImplementedError >>> >>> foo.bar = 'still works' See how it works? The lock method *dynamically* adds the attribute foo._locked *after* initialization to the instance. Before the call of foo.lock() foo._locked is a class attribute. Now you might argue that one should better set foo._locked = False in the __init__ method rather than as a class attribute. Something like: class Foo(object) : def __init__(self) : self._locked = False But no! The initialization would trigger Foo.__setattr__(foo,'_locked',False) which naturally runs into an attribute error since __setattr__ looks up this attribute. So this very same implementation is one of the pro examples you asked for :-) cheers, - harold - -- http://mail.python.org/mailman/listinfo/python-list
passing options to __import__
Dear list, I looked through the list but could not find any solutions for my current problem. Within my program, I am importing a module via __import__(module_name,globals(),locals()) and I want to pass comand line options to this module. I would prefer not to save them in a config module or a Config class but rather use the globals and locals dictionaries that are given to __import__. Unfortunately, they don't show up in the globals or locals in the module. Even setting them specifically by params = globals() params['module_opts'] = module_opts __import__('my_module',params,locals()) does not work. When I put the debug statement print 'module_opts' in globals() into my_module, it prints 'False'. Unfortunately, the docs for __import__ are a bit vague about the precise role of the globals argument. Is there any way, to acheive what I am trying, or do I need to fall back on a config module/class? Thanks! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: why did MIT drop scheme for python in intro to computing?
On Tue, 09 Oct 2007 03:28:53 -, [EMAIL PROTECTED] wrote: >On Oct 8, 1:23 pm, [EMAIL PROTECTED] (Brian Harvey) wrote: >> "Kjetil S. Matheussen" <[EMAIL PROTECTED]> writes: >> >I don't think your speculations makes very much sence. >> Amen. >> And, in any case, there's no need to speculate. >> MIT has published, on their web site, pages and >> pages of rationale for the new curriculum. >> The most important point, imho, is that the >> programming language was the /least/ important >> aspect of the decision. The most important >> aspect was the move to an application-based >> (rather than topic-based) organization of the >> curriculum. The details flow out of that big >> shift of focus. >[ much snipped. ] >Does scheme have a gui library? >I really dont follow the logic. I really REALLY hope that not a single GUI is constructed in 6.01-2; adding that to the load would be stark raving mad (look and you'll agree). As Brian points out, languages are a means to the end of teaching stuff, and I wouldn't be surprised if not a single GUI is constructed in the entire required/restricted elective curriculum. That's just not to the point of an EECS education that has to be squeezed into 4/5 years (most students take the combined MEng path, where the MS degree is terminal and leads straight to industry). If any library was a consideration in choosing Python, it was the robots one for 6.01. Note also that Hal helped design and teach 6.01, and fully supports the new curriculum. As a total LISP/Scheme fanatic who finds parts of Python's syntax to be too hard for his brain (not the indentation, that's weird but useful and cool, much like S-expressions in LISP), I looked hard at the beginning of 6.01 where they're only teaching SICP. For that purpose, Python is not "awful" (remember, I believe LISP is the One True Way of Computing). For that initial bit of SICP material, I do not believe the students will be handicapped. Beyond that initial bit of material, I have no informed opinions. - Harold -- http://mail.python.org/mailman/listinfo/python-list
Re: Better writing in python
Hi Alexandre, On Oct 24, 2:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote: > I'm just wondering, if I could write a in a "better" way this code Please tell us, what it is you want to achieve. And give us some context for this function. > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if arg is True: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) This snippet will seperate d.Arguments into two lists: one that holds all elements that are references to True(!) and another list that holds the rest. The condition 'if args is True' will only be hold if arg actually _is_ the object _True_. This is probably not what you want. Apart from that, you might go with lMandatory = [ arg for arg in cls.dArguments if condition() ] lOptional = [ arg for arg in cls.dArguments if not condition() ] the second line could be rewritten lOptional = list(set(cls.dArguments)-set(lMandatory)) If lMandatory and lOptional do not need to be lists, you can also write lMandatory = set(arg for arg in cls.dArguments if condition()) lOptional = set(cls.dArguments) - lMandatory But please, give us some more context of what you want to do. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Protocols for Python?
[EMAIL PROTECTED] wrote: > Still, I'm designing an application that I want to be extendable by > third-party developers. I'd like to have some sort of documentation > about what behavior is required by the components that can be added to > extend the application. I'd thought I might try documenting these > behaviors as "protocols" instead of creating abstract classes with no > method implementations. Use doc strings :-) They are easy to learn, easy to understand (once you learned how to write meaningful ones, that is), integrated into the core language and supported by IDEs and editors. Combine a good documentation with proper exception handling and extending your application will be easy. Bateries inluded, you know. -- http://mail.python.org/mailman/listinfo/python-list
Re: python game with curses
Jerry, if you want anyone to answer your question, please read this: http://www.catb.org/~esr/faqs/smart-questions.html -- http://mail.python.org/mailman/listinfo/python-list