Re: Python declarative
Looking at my own code after four years, I just realized that most of parentheses can be avoided by redefining the += operators to be a synonym of the add method. Go figure, I guess that with age it _does_ come a little wisdom ... :-) Ciao - FB -- https://mail.python.org/mailman/listinfo/python-list
Re: Python declarative
Some time ago I played with Tkinter trying a more declarative way of coding the GUI building part and I come out with this: top = Tk( 'top' ).add ( Frame( 'frame' ).add ( Pack( side = 'top' ), Frame ( 'panel1' ).add ( Pack( side='left'), Label ( 'label', text=Entry 1 : ), Entry ( 'entry' ) ), Frame( 'panel2' ).add ( Pack( side='left'), Label ( 'label', text=Entry 2 : ), Entry( 'entry' ) ), Pack( side = 'bottom' ), # packing change Button( 'button', text='Click Me' )) ) top.frame.button[command] = functools.partial(button_cb, top) top.realize().mainloop() which, without changing the underlying plumbing, may also be written this way, which avoid nesting but still looks declarative-ish : top = Tk( 'top' ) top.add( Frame( 'frame' ) ) top.frame.add ( Pack( side = 'top' ), Frame ( 'panel1' ), Frame( 'panel2' ), Pack( side = 'bottom' ), # packing change Button( 'button', text='Click Me', command = functools.partial(button_cb, top) ) ) top.frame.panel1.add( Pack( side='left'), Label ( 'label', text=Entry 1 : ), Entry ( 'entry' ) ) top.frame.panel2.add( Pack( side='left'), Label ( 'label', text=Entry 1 : ), Entry( 'entry' ) ) top.realize().mainloop() The underlying plumbing for those two examples is just two classes amounting to about fifty lines of code, plus one-liner wrappers for each kind of widgets/geometry This just to tell you that yes, with python you can write declarative-looking code ... if you don't mind parenthesis :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: I love the decorator in Python!!!
On 8 Dic, 12:22, K.-Michael Aye kmichael@gmail.com wrote: On 2011-12-08 08:59:26 +, Thomas Rachel said: Am 08.12.2011 08:18 schrieb 8 Dihedral: I use the @ decorator to behave exactly like a c macro that does have fewer side effects. I am wondering is there other interesting methods to do the jobs in Python? In combination with a generator, you can do many funny things. For example, you can build up a string: def mkstring(f): Turns a string generator into a string, joining with , . return , .join(f()) def create_answer(): @mkstring def people(): yield Anna yield John yield Theo return The following people were here: + people Many other things are thinkable... Thomas I am still perplexed about decorators though, am happily using Python for many years without them, but maybe i am missing something? For example in the above case, if I want the names attached to each other with a comma, why wouldn't I just create a function doing exactly this? Why would I first write a single name generator and then decorate it so that I never can get single names anymore (this is the case, isn't it? Once decorated, I can not get the original behaviour of the function anymore. So, above, why not def mkstring(mylist): with the same function declaration and then just call it with a list of names that I generate elsewhere in my program? I just can't identify the use-case for decorators, but as I said, maybe I am missing something. Michael I had/have similar feelings. For instance, this is something that I tought useful, but then I never used in real code. The idea was to find a way to automate this code pattern, which I do a lot: class SomeClass: def __init__(self, some, attribute, here ): self.some, self.attribute, self.here = some, attribute, here In other words, I often define classes in which the constructor list of arguments corresponds one-to-one to class attributes. So I thought of this (it uses class decorators so it only works with Python 3.x ) : class FieldsDecorator: def __init__(self, *names): self.names = names def __call__(self, cls): def constructor(instance, **kwds): for n,v in kwds.items(): if n in self.names: setattr(instance, n, v) else: raise TypeError(%s is not a valid field % s ) setattr(cls, '__init__', constructor ) return cls @FieldsDecorator(uno, due) class Prova: pass p = Prova(uno=12, due=9) print (p.uno, p.due ) It works and it is nice, but I don't find it compelling enough to use it. I keep assigning directly the attributes, which is more readable. Decorators are really useful when you have lot of repetitive boilercode that you _want_ to hide, since it has little to do with the problem logic and more to to with the technicalities of the programming language or of some framework that you are using. It is called separating of concerns I think, and is one of the principles of Aspect-Oriented Programming (and with decorators you can do some nice AOP exercises ... ). Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Maximize already running tkinter program on invocation
On 27 Lug, 10:18, Steven Kauffmann steven.kauffm...@gmail.com wrote: Hi all, I have written a small GUI application in python 3.x using the tkinter module. Program is running fine, but multiple instances of the program can now be created. I would like to reduce the number of instances of the program to only 1 instance. I know that this is possible by using a singleton class. This way it's possible to check if the program is already running or not. When I invoke the program and it detects that the program is already running, is it then possible to maximize the already running program? I can find a lot of examples about singleton classes in python on the web, but nothing about showing the already running application when 1 instance of the program already exists. Is there a way to realize this in python? I'm now doing the development on a linux machine, but the final program should work on Windows. Cheers, The multiprocesing module could help you in making sure that two instances of the same program are not started ( for instance using multiprocessing.Queue) as well as to signal the already running instance that it sould maximize its window ( for instance using multiprocessing.Queue ). Just make sure that what you use is supoorted on your target operating system(s). However, the integration of any form of inter-process communication with Tkinter main loop is going to be tricky ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
On 11 Giu, 11:41, Asen Bozhilov asen.bozhi...@gmail.com wrote: Hi all, I am beginner in Python. What is interesting for me is that Python interpreter treats in different way dot and square bracket notations. I am coming from JavaScript where both notations lead prototype chain lookup. In Python it seems square bracket and dot notations lead lookup in different store. Simple example with dict object: d = {key : value} print d[key] #value print d.key #AttributeError I found an implementation of dict which uses both notations for its keys lookup, which I think is stupid idea when obviously both notations lead different lookup. It will confuse me as a reader of the code. Anyway, I would like to know more about the lookup for key of dict and lookup for property of any object with dot notation. Any materials and explanations are highly appreciated. Since python is not javascript ( duh :-), [] and . notations are used for different purposes and, although they share some commonalities as I try to show later in this post, they should not be intermixed without a very good reeason ( and it's cool is not a good reason IMO). Broadly speaking, square brackets are used to access element in array, dict, tuples and sequences. The dot nootation is used to get the attributes and methods of instances. User classes - that is the ones you define with the class statement - can implement support for the squared bracket and dot notations: - the expression myinstance[index] is sort of translated into of myinstance.__getitem__(index) - the expression myinstance.myattribute is sort of translated of myinstance.__getattr__(myattribute) Classes also exposes a __dict__ attributes that allows to access to instance attributes and methods using dictionary semantics. That is, myistance.__dict__[myattribute] should give the same result as myinstance.myattribute. I believe this is because in the beginning class instances actually had a dictionary storing the instance attributes. Nowadays it is more complex than that, I think, but the interface is kept to allow dynamic access to instance contents, although the reccomended way to do it this is getattr(myinstance, myattribute). Of course it is only useful to use __dict__ or getattr when the parameter is not a constant string but a variable referring to a string computed at run time ( this is what I mean for 'dynamic access' ). HTH. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any python library that parse c++ source code statically
On 13 Mar, 10:14, kuangye kuangye19840...@gmail.com wrote: Hi, all. I need to generate other programming language source code from C++ source code for a project. To achieve this, the first step is to understand the c++ source code at least in formally. Thus is there any library to parse the C++ source code statically. So I can developer on this library. Since the C++ source code is rather simple and regular. I think i can generate other language representation from C++ source code. The problem is that C++ is a beast of a language and is not easy to find full parsers for it. I've never done it, but sometime I researched possible ways to do it. The best idea I could come with is doing it in 2 steps: - using gcc-xml ( http://www.gccxml.org/HTML/Index.html ) to generate an xml representation of the code - using one of the many xml library for python to read the xml equivalent of the code and then generate the equivalent code in other languages ( where you could use a template engine, but I found that the python built-in string formatting libraries are quite up to the task ). HTH Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple values for keyword argument
On 29 Gen, 12:10, Tobias Blass tobiasbl...@gmx.net wrote: Hi all I'm just learning python and use it to write a GUI (with Tkinter) for a C program I already wrote. When trying to execute the program below I get the following error message. Traceback (most recent call last): File ./abirechner.py, line 64, in module win =MainWin() File ./abirechner.py, line 43, in __init__ self.create_edit(row=i); TypeError: create_edit() got multiple values for keyword argument 'row' I don't really understand why create_edit gets multiple values, it gets one Integer after another (as I see it) Thanks for your help abirechner.py: # line 37 class MainWin(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.grid() self.edits=() for i in range(10): self.create_edit(row=i); def create_edit(row,self): # LineEdit is defined, but I don't consider it important here self.edits+=LineEdit() self.edits[-1].grid(row=row,column=0) # ... #line 64 win = MainWin() win.mainLoop() Try this: def create_edit(self, row): Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Case Sensitive Section names configparser
On 8 Dic, 11:32, RedBaron dheeraj.gup...@gmail.com wrote: Is there any way by which configParser's get() function can be made case insensitive? If you don't care about the case of the config parameter values, you could pre-convert the input to configParser all in UPPER or lower letter with a file-like object like this (NOT TESTED): class AllUpperFile(object): def __init__(self, fname): self.fp = file(fname) def readline(self): return self.fp.readline().upper() and the use configParser.readfp method to feed the file-like object to the config parser myConfigparser.readfp( AllUpperFile(myconnfigfile.cfg) HTH Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Comparing lists
Hi all, anybody can point me to a description of how the default comparison of list objects (or other iterables) works? Apparently l1 l2 is equivalent to all ( x y for x,y in zip( l1, l2) ), has is shown in the following tests, but I can't find it described anywhere: [1,2,3] [1,3,2] True [1,2,3] [1,2,4] True [1,2,3] [2,2,3] True [1,2,3] [0,1,3] False [1,2,3] [0,2,3] False [1,2,3] [1,1,3] False [1,2,3] [1,2,2] False Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird Python behaviour
On 10 Ago, 13:58, Jonas Nilsson j...@spray.se wrote: Hello, Lets say that I want to feed an optional list to class constructor: class Family(): def __init__(self, fName, members = []): self.fName = fName self.members = members Now, lets add members to two different instances of Family: f1 = Family(Smith) f1.members.append(Bill) f2 = Family(Smithers) f2.members.append(Joe) Finally, lets look at the members in the Smithers family: print f2.members output: ['Bill', 'Joe'] Why on earth is the output ['Bill', 'Joe']!? Is there a simple solution that separates f1 and f2 without forcing me to write code for the special case when you don't feed members to the __init__()-function? /Jonas You stumbled in two python common pitfalls at once :-) One, the default arguments issue, was already pointed to you. The other one is that python variables are just names for objects. Assigning a variable never mean making a copy, it just means using another name for the same object. There used to be a very nice (also graphic) explanationor this somewhere on the web, but my googling skills failed me this time, so instead I'll show you the concept using your own code: class Family: ... def __init__(self, fName, members = []): ... self.fname = fName ... self.members = members ... mlist = [Bill] f1 = Family(Smiths, mlist ) mlist.append( John ) # attempt to not-so-clever reyse of the sme variable f2 = Family(Smithers, mlist ) f1.members ['Bill', 'John'] Now my example is a bit contrieved but I'm sure you got the idea : in your example is better to copy the list with self.members = members[:]. Better yet, you could make use of python arguments grouping feature : class Family: ... def __init__(self, fName, *members ): ... self.members = list(members) # because members is a tuple ... self.fname = fName ... f1 = Family(Smith) f1.members.append(Bill) f2 = Family(Smithers) f2.members.append(Joe) f2.members ['Joe'] f1.members ['Bill'] This solves your no initial member special case and allows for an easier syntax for creating class instances (no brackets involved) f3 = Family(Bochicchio, Angelo, Francesco, Mario) f3.members ['Angelo', 'Francesco', 'Mario'] Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird Python behaviour
On 10 Ago, 17:57, Stefan Schwarzer sschwar...@sschwarzer.net wrote: Hi, On 2010-08-10 17:01, Francesco Bochicchio wrote: There used to be a very nice (also graphic) explanationor this somewhere on the web, but my googling skills failed me this time, so instead I'll show you the concept using your own code: Probably this isn't the page you're referring to, but I only recently gave a beginners' talk at EuroPython: http://sschwarzer.com/download/robust_python_programs_europython2010.pdf The topic of identity and assignments starts on slide 7, nice graphics start on slide 10. ;-) Stefan Also good :-) But I finally found the page I was referring to: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Minor annoyances with properties
On 27 Mag, 14:37, eb303 eric.brunel.pragma...@gmail.com wrote: Hello all, I've been using Python properties quite a lot lately and I've found a few things that are a bit annoying about them in some cases. I wondered if I missed something or if anybody else has this kind of problems too, and if there are better solutions than the ones I'm using ATM. The first annoyance is when I want to specialize a property in a subclass. This happens quite often actually, and it is even sometimes the reason why a plain attribute is turned into a property: a subclass needs to do more things than the superclass when the property is updated for example. So, of course, my first try was: class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p p = property(_get_p, _set_p) class B(A): def _set_p(self, p): ## Additional things here… super(B, self)._set_p(p) And of course, it doesn't work: the property has been bound to A._set_p in A, so any new definition of _set_p in any subclass does not replace the set method for the property. So I always have to add a line: p = property(A._get_p, _set_p) in the subclass too. This is a bit awkward to me, since I have to specify the superclass's name (super(…) can't be used, since it should take B as an argument, and B isn't defined yet…). Do I miss something? Is this the way to do it, or is there a better one? Don't know if is better, but you could add a level of indirection to solve it class A(object): def __init__(self): self._p = None def _get_p(self): return self._p def _set_p(self, p): self._p = p def _virtual_get_p (self): _get_p(self) def _virtual_set_p (self,v): _set_p(self, v) p = property(_virtual_get_p, _virtual_set_p) At this point, the subclasses of A can reimplement _get_p and _set_p as they like (I think) Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: First Tkinter script: requesting comments
On 21 Mag, 23:51, Bart Kastermans bkast...@gmail.com wrote: I wrote a first script using Tkinter. As I am new to its use, I am only just feeling my way around. I would very much like comments on the design of the script (and in fact any other comments on my code would also be very welcome). I have it posted (with syntax coloring) at: http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/ But will also include it here for convenience. Thanks for any help, Best, Bart *** #!/usr/bin/env python # # Getting a list of students and grades displayed so that grades can # be updated, and we poll these changes (so that in the future we can # act on it). # # Bart Kastermans,www.bartk.nl Design of the window +-+ | root | | +--+ | | | title_frame | | | | +--+ | | | | | Label(title) | | | | | | | | | | | +--+ | | | +--+ | | +--+ | | | exam_grades_frames | | | | +-+ | | | | | Frame(ex) | | | | | | ++ +-+ | | | | | | | Entry(name) | | Entry(grade) | | | | | | | | | | | | | | | | | ++ +-+ | | | | | +-+ | | | | | | | +--+ | | | | +-+ | | | quit_button | | | | | | | +-+ | +-+ from Tkinter import * # global info for this specific example # four students no_stud = 4 exam_grades = [1,2,3,4] names = [Ben, Jim, James, Mel] # upper bound for name length max_name_len = max (map (len, names)) # set up root window root = Tk() root.geometry (400x400) exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades) names_string = map (lambda x: StringVar (root, x), names) def setup (): setup the window with the list of students. This is test-code to figure out what the app finally should look like. # title frame, with title Grade Correction in it title_frame = Frame(root) title_frame.pack (fill=X) w = Label (title_frame, text = Grade Correction, font = (Helvetica, 25)) w.pack (side=LEFT) # from to hold the list of grades exam_grades_frame = Frame (root) exam_grades_frame.pack (fill=BOTH) exam_label = Label (exam_grades_frame, text=EXAMS) exam_label.pack () # set up the list of grades for i in range (0,no_stud): # a frame per student ex = Frame (exam_grades_frame) ex.pack () # name on the left name = Entry (ex, textvariable=names_string[i], width=max_name_len+2) name.config (state=DISABLED) name.pack (side=LEFT) # grade next to it grade = Entry (ex, textvariable=exam_grades_string [i], width=4) grade.pack (side=LEFT) # button to quit the application qb = Button (root) qb ['text'] = quit qb ['command'] = root.quit qb.pack () def to_int (st): helper function to convert strings to integers. Empty string represents 0. if len (st) == 0: return 0 else: return int (st) def get_curr_grades (): extract the grades from exam_grades_string. exam_grades_string consists of StringVar that get updated when the fields are updated in the GUI. grades = [] for i in range (0, no_stud): grades.append (exam_grades_string [i].get()) return grades # get the current grades curr_grades = map (to_int, get_curr_grades ()) def poll_exams (): function that keeps polling the current grades, looking for changes global curr_grades new_grades = map (to_int, get_curr_grades ()) if new_grades !=
Re: solve a newspaper quiz
On 9 Mag, 11:20, superpollo ute...@esempio.net wrote: if a b c are digits, solve ab:c=a*c+b solved in one minute with no thought: for a in range(10): for b in range(10): for c in range(10): try: if (10.*a+b)/c==a*c+b: print %i%i:%i=%i*%i+%i % (a,b,c,a,c,b) except: pass any suggestion for improvement? bye The obvious one-liner. Maybe not an improvement, but more compact (I included the solutions for the really lazy ones). But you need to think just one second to exclude 0 from the values of c and avoid a divide by zero exception. [(a,b,c) for a in range(10) for b in range(10) for c in range(1,10) if (a*10+b)/c == a*c+b ] [(0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 0, 5), (0, 0, 6), (0, 0, 7), (0, 0, 8), (0, 0, 9), (0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1), (0, 5, 1), (0, 6, 1), (0, 7, 1), (0, 8, 1), (0, 9, 1), (1, 0, 3), (1, 5, 2), (1, 6, 2), (2, 0, 3), (2, 1, 3), (3, 1, 3), (4, 1, 3), (4, 2, 3), (5, 2, 3), (6, 2, 3), (6, 3, 3), (7, 3, 3), (8, 3, 3), (8, 4, 3), (9, 4, 3)] Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Fast Efficient way to transfer an object to another list
On 1 Mag, 05:35, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: def transfer_stock(stock_code, old_list, new_list): Transfer a stock from one list to another while True: # loop forever try: i = old_list.index(stock_code) except ValueError: # not found, so we're done break new_list.append(old_list[i]) del old_list[i] return new_list -- Steven I think this could be slower than doing like the OP, since 'index' rescan the whole list every time while doing an explicit loop you only scan the list once. Anyway i think that list.extract( old_list, predicate ) - new_list would be a nice addition to the standard library (possibly a C faster version of what one could implement in python) ... and since the library is not under moratorium maybe we will have it ... the semantic could be like th OP asked: --- code begins class ListE(list): def extract(self, predicate): res = [] for idx, el in enumerate(self): if predicate(el): res.append( self.pop(idx) ) return res class Stock(object): def __init__(self, code): self.code = code def __repr__(self): return Stock: code=%d % self.code l = ListE( Stock(n) for n in range(19) ) subl = l.extract( lambda x: x.code in (1,4, 9) ) print l = , l print subl = , subl --- code ends --- results l = [Stock: code=0, Stock: code=2, Stock: code=3, Stock: code=5, Stock: code=6, Stock: code=7, Stock: code=8, Stock: code=10, Stock: code=11, Stock: code=12, Stock: code=13, Stock: code=14, Stock: code=15, Stock: code=16, Stock: code=17, Stock: code=18] subl = [Stock: code=1, Stock: code=4, Stock: code=9] Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: passing command line arguments to executable
On 3 Apr, 19:20, mcanjo mca...@gmail.com wrote: On Apr 3, 11:15 am, Patrick Maupin pmau...@gmail.com wrote: On Apr 3, 11:09 am, mcanjo mca...@gmail.com wrote: I have an executable (I don't have access to the source code) that processes some data. I double click on the icon and a Command prompt window pops up. The program asks me for the input file, I hit enter, and then it asks me for and output filename, I hit enter a second time and it goes off and does its thing and when it is finished running the Command Prompt goes away and I have my new output file in the same directory as my executable and input file. I would like to be able to batch process a group of files. I thought about using os.spawnv() in a loop and at each iteration of the loop passing in the file in and out names but that didn't work. Does anyone have any ideas? You need to look at the subprocess module, and use pipes. Regards, Pat I tried doing the following code: from subprocess import Popen from subprocess import PIPE, STDOUT exefile = Popen('pmm.exe', stdout = PIPE, stdin = PIPE, stderr = STDOUT) exefile.communicate('MarchScreen.pmm\nMarchScreen.out')[0] and the Command Prompt opened and closed, no exceptions were generated but the program didn't run. Am I doing something wrong? I would try a couple of things (never done what you are trying to do, so my suggestions may be useless ): 1. use shell=True as parameter of Popen 2. capture the output of communicate method, which returns whatever the process emits on standard output and standard error: there could be some message that give you hints about the solution. Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to access args as a list?
On 4 Apr, 00:58, kj no.em...@please.post wrote: Suppose I have a function with the following signature: def spam(x, y, z): # etc. Is there a way to refer, within the function, to all its arguments as a single list? (I.e. I'm looking for Python's equivalent of Perl's @_ variable.) I'm aware of locals(), but I want to preserve the order in which the arguments appear in the signature. My immediate aim is to set up a simple class that will allow me to iterate over the arguments passed to the constructor (plus let me refer to these individual arguments by their names using an instance.attribute syntax, as usual). The best I have managed looks like this: class _Spam(object): def __init__(self, x, y, z): self.__dict__ = OrderedDict(()) for p in inspect.getargspec(_Spam.__init__).args[1:]: self.__dict__[p] = locals()[p] def __iter__(self): return iter(self.__dict__.values()) but rolling out inspect.getargspec for this sort of thing looks to me like overkill. Is there a more basic approach? P.S. this is just an example; the function I want to implement has more parameters in its signature, with longer, more informative names. Hi, I once tried something to emulate in python the way Scala language allows to automatically generate class attributes from constructor parameter. I never tried in real code, but see if it fits your bill. It uses class decorators though, so only works with python3. Here is my code: class FieldsDecorator: It adds a generic scala-like constructor to a class. You can create as instance as c = MyClass(f1=3, f2=4) and have automatically c.f1=3, c.f2=4. Only parameter names listed in the decorator are allowed. def __init__(self, *names): self.names = names def __call__(self, cls): def constructor(instance, **kwds): for n,v in kwds.items(): if n in self.names: setattr(instance, n, v) else: raise TypeError(%s is not a valid field % s ) setattr(cls, '__init__', constructor ) return cls @FieldsDecorator(uno, due) class Prova: pass p = Prova(uno=12, due=9) print (p.uno, p.due ) Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: how to start a python script only once
On 13 Mar, 19:45, News123 news1...@free.fr wrote: Hi, I'd like to make sure, that a certain python program will only be run once per host. (linux/windows) so if the program is started a second time it should just terminate and let the other one run. This does not have to be the fastest solution, but it should be reliable. I have a few ideas, but wonder, which one is the most common My ideas so far: pid file and file locking -- create a file like program.pid with the pid of the running program an use file locking to avoid race connditions. However I currently don't know how to do file locking under windows and I don't know how to do file lockng with python and linux. I'll start googling. sqlite and locking quite some time ago I used a mysql table and locking as an inter-host mutex. Perhaps sqlite would be good enough for an inter process mutex for processes on the same host, but I don't know it well enough. interprocess mutex well I even don't know whether something like this exists on linux / windows Thanks in advanced for any tips N Apart from file, a portable solution would be to bind to an unused porta and assume that finding the port busy means that your program is already running on the port. On recent python installations there is the multiprocessing module which provides process-level semaphores, but I don't know how portable they are. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing FILE * types using ctypes
On Mar 4, 12:50 am, Zeeshan Quireshi zeeshan.quire...@gmail.com wrote: Hello, I'm using ctypes to wrap a library i wrote. I am trying to pass it a FILE *pointer, how do i open a file in Python and convert it to a FILE *pointer. Or do i have to call the C library using ctypes first, get the pointer and then pass it to my function. Also, is there any automated way to convert c struct and enum definitions to ctypes data types. Zeeshan Python file objects have a method fileno() whic returns the 'C file descriptor', i.e. the number used by low level IO in python as well as in C. I would use this as interface between python and C and then in the C function using fdopen to get a FILE * for an already open file for which you have a file descriptor. If you don't want change the C interface, you could try using fdopen in python by loading the standard C library ang using ctypes to call the function. (I tried briefly but always get 0 from fdopen ). But if you can change the C code, why not to pass the file name? The idea of opening the file in python and manage it in C feels a bit icky ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help to pass self.count to other classes.
On 6 Gen, 11:11, Bill bsag...@gmail.com wrote: After a year with Python 2.5 on my Windows box, I still have trouble understanding classes. Below, see the batch file and the configuration script for my Python interactive prompt. The widths of the secondary prompts increase when the self.count of SysPrompt1 exceeds 99. I am using a global variable zxc to share self.count, which is not Pythonic. How can I pass in self.count without a global? I did RTFM, aka Google, but to no avail. echo py.bat set PYTHONSTARTUP=c:\scripts\startup.py python ^Z # startup.py # inspired by: #http://www.doughellmann.com/PyMOTW/sys/interpreter.html import sys class SysPrompt1(object): def __init__(self): self.count = 0 def __str__(self): self.count += 1 global zxc zxc = self.count return '[%2d] ' % self.count class SysPrompt2(object): def __str__(self): global zxc if zxc 99: return '.. ' else: return '. ' class DisplayHook(object): def __call__(self, value): if value is None: return global zxc if zxc 99: print '[ out]', value, '\n' else: print '[out]', value, '\n' class ExceptHook(object): def __call__(self, type, value, trace): global zxc if zxc 99: print '[ err]', value, '\n' else: print '[err]', value, '\n' sys.ps1 = SysPrompt1() sys.ps2 = SysPrompt2() sys.displayhook = DisplayHook() sys.excepthook = ExceptHook() First of all, you shouldn't do OOP if you don't feel it. Python, unlike Java and like C++, supports also procedural programming, so you can write your scripts without writing classes (but still using objects, since all in python is an object). If you have classes with no data and a single __call_ method, then they are no classes, they are functions (or methods) in disguise. So, one solution could be to use plain functions and use global as you already do. 'global' is pythonic if you are not doing OOP, although I don't like it. If you want to stick to OOP, then I suggest to have a make display_hook and except_hook methods of your class SysPrompt1; This way all your code can access to self.count without needing globals. As for your class SysPrompt2, I don't understand enough your code to know what you are trying to do. maybe make it a sunclass of SysPrompt1 ? HTH Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: getting name of passed reference
On 29 Dic, 00:54, Joel Davis callmeclaud...@gmail.com wrote: I'm just curious if anyone knows of a way to get the variable name of a reference passed to the function. Put another way, in the example: def MyFunc ( varPassed ): print varPassed; MyFunc(nwVar) how would I get the string nwVar from inside of MyFunc? is it possible? The following code shows one way to get both function name and argument names from inside a function using module inspect in python 2.6: import inspect def myfunc(arg1, arg2): f = inspect.currentframe() funcname = inspect.getframeinfo(f).function numargs = f.f_code.co_argcount argnames = f.f_code.co_varnames[:numargs] print funcname, argnames myfunc(1, ppp) NOTE: it does not list parameters passed as list (*args) or as dict (**kwd). P.S . I use this to generate automatically trace messages of type called myfunc( arg1=1, arg2=ppp ). But I currently lack a way, from inside a method, to determine the name of the class to which the method belong, so I could automatically generate trace messages of type class.method called etc Pointers are welcome. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to iterate the input over a particular size?
On 27 Dic, 22:29, joy99 subhakolkata1...@gmail.com wrote: On Dec 27, 8:42 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Sun, Dec 27, 2009 at 9:44 AM, joy99 subhakolkata1...@gmail.com wrote: Dear Group, I am encountering a small question. Suppose, I write the following code, input_string=raw_input(PRINT A STRING:) string_to_word=input_string.split() len_word_list=len(string_to_word) if len_word_list9: rest_words=string_to_word[9:] len_rest_word=len(rest_words) if len_rest_word9: remaining_words=rest_words[9:] In this program, I am trying to extract first 9 words from an indefinitely long string, until it reaches 0. Am I writing it ok, or should I use while, or lambda? If any one can suggest. Hope you are enjoying a nice vacation of Merry Christmas. If any one is bit free and may guide me up bit. Wishing you a happy day ahead, Best Regards, Subhabrata. -- You want the first 9 words? string_to_word[:9] You want the last 9 words? string_to_word[-9:] If you want the groups of words, use a loop- that's the only way to get all of them for any length list. http://mail.python.org/mailman/listinfo/python-list-Hide quoted text - - Show quoted text -- Hide quoted text - - Show quoted text - Dear Group, Answers were good. But I am looking for a smarter solution like: for i[:2] in list: etc. or by doing some looping over loop. Do not worry I'll work out the answer. Wishing you a happy day ahead, Regards, Subhabrata. Not sure I understood your question, but if you need just to plit a big list in sublists of no more than 9 elements, then you can do someting like: def sublists(biglist, n ): Splits a big list in sublists of max n elements prev_idx = 0; res = [] for idx in xrange(n, len(biglist)+n, n ): res.append( biglist[prev_idx:idx] ) prev_idx = idx return res I would not be surprised if somewhere in python standard library there is something like this (possibly better), but could not find anything. Another solution could be this smarter-looking but less readeable one liner: sublists = [ big_list[i:(i+9)] for i in xrange( 0, len (big_list)+9, 9) if i len(big_list) ] P.S : if your biglist is huge (but being typed in I don't think so) then you better convert the sublists function in a generator. HTH Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: (help)Tkinter, how to make labels scrolling?
On 28 Dic, 09:44, Ren Wenshan renws1...@gmail.com wrote: Hi, everyone: I am new to programming and Python and these days I've been working on a tiny program for practice and encountered with a problem. My tiny program read a line from a data file one time, and store it in a list, till the list is full. This is the init. Then when I press Button Start, I want the program will read a line, list.pop(0) list.append(line) in a loop. Thus, make the labels scrolling. English is not my mother tongue, I hope I've made myself understood. the whole source code: from Tkinter import * import sys import time # position of buttons row_button = 5 col_button = 4 # font size size_title = 20 size_button = 12 size_text = 14 # the length of name_list Len_List = 3 class meal( Frame ): def __init__(self): Frame.__init__(self) self.pack( expand = YES, fill = BOTH) self.master.title(Languages) self.label_1 = Label(self, text = Too many languages to choose..., font = (arial, size_title)) self.label_2 = Label(self, text = Which is the Lucky one, font = (arial, size_title-4)) self.label_1.grid(row = 0, column = 0) self.label_2.grid(row = 1, column = 2) self.button_start = Button(self, text = start, font = (arial, size_button), command = self.start) self.button_stop = Button(self, text = stop, font = (arial, size_button)) self.button_quit = Button(self, text = quit, font = (arial, size_button), command = self.quit) self.button_start.grid(row = row_button, column = col_button) self.button_stop.grid(row = row_button, column = col_button+1) self.button_quit.grid(row = row_button,column = col_button+2) self.name_list = [None] * Len_List self.label_list = [None] * Len_List self.fp = open(data.txt, 'r') for i in range(Len_List): self.name_list[i] = self.fp.readline() for i in range(Len_List): self.label_list[i] = Label(self, text = self.name_list[i], font = (arial, 12)) self.label_list[i].grid(row = 2+i, column = 2) def start(self): self.line = self.fp.readline() if not self.line: self.fp.seek(0) self.line = self.fp.readline() self.name_list.pop(0) self.name_list.append(self.line) for i in range(Len_List): self.label_list[i].destroy() self.label_list[i] = Label(self, text = self.name_list[i], font = (arial, 12)) self.label_list[i].grid(row = 2+i, column = 2) def quit(self): sys.exit(0) app = meal() app.mainloop() Best wishes Vincent Ren Hi, if you want to realize an 'animated scrolling' effect, you need to move the scrolling code out of the start callback in a function which is called periodically by the GUI mainloop. In Tkinter, you can do that using Toplevel.after to have a fuction be called after a timeout. Here is your 'meal' class with the modifications needed to make an 'animated scroll'. I renamed your start method as _scroll_text and wrote new start and stop methods to start and stop the scrolling. Ciao - FB lass meal( Frame ): SCROLL_DELAY = 500 # milliseconds def __init__(self): Frame.__init__(self) self.pack( expand = YES, fill = BOTH) self.master.title(Languages) self.label_1 = Label(self, text = Too many languages to choose..., font = (arial, size_title)) self.label_2 = Label(self, text = Which is the Lucky one, font = (arial, size_title-4)) self.label_1.grid(row = 0, column = 0) self.label_2.grid(row = 1, column = 2) self.button_start = Button(self, text = start, font = (arial, size_button), command = self.start) self.button_stop = Button(self, text = stop, font = (arial, size_button), command = self.stop ) self.button_quit = Button(self, text = quit, font = (arial, size_button), command = self.quit) self.button_start.grid(row = row_button, column = col_button) self.button_stop.grid(row = row_button, column = col_button+1) self.button_quit.grid(row = row_button,column = col_button+2) self.name_list = [None] * Len_List self.label_list = [None] * Len_List self.fp = open(data.txt, 'r') for i in range(Len_List): self.name_list[i] = self.fp.readline() for i in range(Len_List): self.label_list[i] = Label(self, text = self.name_list[i], font = (arial, 12)) self.label_list[i].grid(row = 2+i, column = 2) self.after_id = None def _scroll_text(self): #print _scroll_text self.line = self.fp.readline() if not self.line: self.fp.seek(0) self.line = self.fp.readline() self.name_list.pop(0) self.name_list.append(self.line) for i in range(Len_List):
Re: iterators and views of lists
On Dec 16, 1:58 pm, Anh Hai Trinh anh.hai.tr...@gmail.com wrote: You might be interested in this library http://pypi.python.org/pypi/ stream. You can easily create arbitrary slice, for example i = mylist takei(primes()) will return an iterator over the items of mylist with a prime number index, given that primes() return an iterator over prime numbers. Nice :-) I was starting to experiment data flow programming with python myself, although I'm just playing with it.. I find the idea of data flow programming fascinatin, and wonder if it can be considered a general-purpose program paradigm. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for help getting tkinter to work.
On Nov 1, 4:06 am, Shue Boks shoebox56car...@gmail.com wrote: I tried to compile Python and Tcl/Tk on Linux using the following files: Python-3.1.1.tar.gz tcl8.5.7-src.tar.gz Cannot get tkinter to work after compiling installing Tcl/Tk. I get the following error after compiling Python: Python build finished, but the necessary bits to build these modules were not found: _tkinter To find the necessary bits, look in setup.py in detect_modules() for the module's name. Are the above files the correct versions to get tkinter to work? Thanks. The version should be ok. I just compiled python3.1 against tcl/tk 8.5, only I used the tcl/tk development packages coming with my distribution (Ubuntu). I used ./configure --with-tk, so if you did not, try that first. Did you run 'make install' during tcl/tk installation _before_ doing ./ configure in python source directory? If so, look where the library files ( e.g. libtk8.5.so ) and include files (e.g tk.h ) have been placed and check against the places where the function 'detect_tkinter' in 'setup.py' looks for them. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Hello, world?
On 28 Ott, 10:40, Gilles Ganault nos...@nospam.com wrote: Hello I'm reading O'Reily's Python Programming on Win32, but couldn't find a simple example on how to create a window with just a label and pushbutton. This is probably because maybe the book addresses how to use python to do windows-specific stuff (like using a COM interface) and presumes a basic knowledge of python in the reader (just guessing, never read the book ) If someone has such a basic example handy, I'm interested. Thank you. There are as many way to do it as many GUI toolkits for python you can find (and there are many) although they all share a similar structure. Here is the one for Tkinter, which is the default python GUI toolkit. The example is copied verbatim from the python on-line documentation ( section Graphical User Interfaces with Tk of The Python Standard Library). Ciao -- FB from Tkinter import * class Application(Frame): def say_hi(self): print hi there, everyone! def createWidgets(self): self.QUIT = Button(self) self.QUIT[text] = QUIT self.QUIT[fg] = red self.QUIT[command] = self.quit self.QUIT.pack({side: left}) self.hi_there = Button(self) self.hi_there[text] = Hello, self.hi_there[command] = self.say_hi self.hi_there.pack({side: left}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() root = Tk() app = Application(master=root) app.mainloop() root.destroy() -- http://mail.python.org/mailman/listinfo/python-list
Re: Feedback wanted on programming introduction (Python in Windows)
Just to fuel the flame war, consider a million line Python system. It's not uncommon with C++. :-) In python, with one-miliion lines of code, you can demonstrate the existence of God, and then demostrate its non-existance by changing a single line of code :-) Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Cpython optimization
Il Wed, 21 Oct 2009 10:28:55 -0700, Qrees ha scritto: Hello As my Master's dissertation I chose Cpython optimization. That's why i'd like to ask what are your suggestions what can be optimized. Well, I know that quite a lot. I've downloaded the source code (I plan to work on Cpython 2.6 and I've downloaded 2.6.3 release). By looking at the code I've found comment's like this can be optimized by... etc. but maybe you guide me what should I concentrate on in my work? I've 6-7 month for this and If I create something decent I can publish it. Thank you in advance for any help If you don't know yet, you could find interesting this project: http://code.google.com/p/unladen-swallow/ They too are trying to improve CPython speed. If you are thinking of language variations that trade some flexiblity for speed, you might be interested in Cython: http://www.cython.org/ As a simple and plain python user, I would value a version of cython that can be used to built faster executables out of almost-python code (that is python code with a few additional restructions). Maybe using typing inference to avoid declaring explicitely the variable types. Another interesting place to go is pypy : http://codespeak.net/pypy/dist/ pypy/doc/ . They too have developed a restriced version of python (RPython, I think) which should be faster than CPython. They don't work with CPython code base, but could give you ideas on what are the bottlenecks of python as a language. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Clear interface for mail class
On Oct 14, 2:39 pm, Benedict Verheyen benedict.verhe...@gmail.com wrote: Hi, I'm trying to come up with a decent interface for my email class. Basically, i have one email function but it has many (too many?) variables: send_mail(self, send_from, send_to, send_cc, subject, text, separate_emails = False, files=[], inline_files=[], server=localhost, charset=iso-8859-1) I'm thinking on how i could simplify it and make it look nicer and more easy to use. I can reduce the number of arguments by adding functions for the less common tasks like adding attachement, inline files and so on. Then i would end up with functions like this: def __init__(self): self._files=[] self._inline_files=[] ... def add_files(self, files=[]): assert type(files)==list self._files=files ... When sending an email, i could check if files where specified and if so, send them too. But it doesn't feel right to just have a bunch of small functions to set variables. Calling the function would change from: (where m is the mail class) m.send_mail( from...@work, t...@work, [], Test emailmodule , MSG, separate_emails = True, files=[attached_pic.png], inline_files=[inline_pic.png], server=mysmtpserver) to: m.add_files([attached_pic.png]) m.add_inline_files([inline_pic.png]) m.smtp_server(mysmtpserver) m.send_mail( from...@work, t...@work, [], Test emailmodule , MSG) It looks already better and i could set the smtp server as a class variable, but i'm not sure this will present me with the most natural interface to use. Or should i make 1 general function that sets vars according to a type? For instance: add_header(To,[list_of_recipients]) This kind of problems seems to happen sometimes: i need to fix something quickly, build a script for it, and then i realise that the code i've written is not the best in terms of reusability and has some not so great functions or classes. Speedy development eh. Any ideas are welcome. Thanks, Benedict I would add a server class, maybe subclassing something in standard library, and add to it the 'send' method, so that sending a mail would be something like: myserver = MyMailServer(mysmtpserver, localhost, ) # this only needs to be done once, not for each mail m = MyMail( subject, text, separate_emails = False, files=[], inline_files=[] ) # mail creation myserver.send( m, from= from...@work, # mail sending to = t...@work, cc_to= None ) Note that I put sender and destination senders in the send method, not as attributes of the mail object. It makes more sense to me, and yopu can reuse the same object if you want to send the same mail to many addresses ( and/or via different servers ). IN general, un case like yours I use a lot default parameters, as you did already. Having separate methods to setting specific part of an object only makes sens (to me) if you need first to create an object and later change some of the attributes. Also, if you are just going to change the attributes, you do not need a method: just use the object.attribute = value syntax. If you are going to need later to do more complex thing, you can always transform your attribute in a property. -- http://mail.python.org/mailman/listinfo/python-list
Re: Opinions, please, on PEP 8 and local, 3rd party imports
On Oct 2, 9:50 pm, Philip Semanchuk phi...@semanchuk.com wrote: Hi all, PEP 8 http://www.python.org/dev/peps/pep-0008/ says the following: Imports should be grouped in the following order: 1. standard library imports 2. related third party imports 3. local application/library specific imports I'm not sure in which category to place local, 3rd-party modules like configobj. ... Clearly, the best choice is category 2.5? Actually 2.5 is doable :-) I translate it as just after any of 2 and before any of 3 Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Want to call a method only once for unittest.TestCase--but not sure how?
On Sep 28, 12:45 pm, Oltmans rolf.oltm...@gmail.com wrote: Hello fellow python hackers, I'm not an expert when it comes to Python and I'm totally stuck in a situation. All of our unit tests are written using built-in 'unittest' module. We've a requirement where we want to run a method only once for our unit tests. Some background: all of our tests are sub-classes of unittest.TestCase module just like following (copy pasting from idle) class Calculator(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add(self): print 'adder' print '---' def test_multiply(self): print 'multiplier' print '---' def test_divide(self): print '===' print 'Divide test' print '===' Our requirement is that for every unit test class we want to run a method only once. Method setUp() won't help because it will be called before every test method. I've tried using the following def __init__(self): unittest.TestCase.__init__(self) but it throws the following error E:\PyPy\Practicepython runner.py Traceback (most recent call last): suite = unittest.defaultTestLoader.loadTestsFromNames (['Tests.Calculator.Te stCase']) File C:\Python25\lib\unittest.py, line 565, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File C:\Python25\lib\unittest.py, line 547, in loadTestsFromName return self.loadTestsFromTestCase(obj) File C:\Python25\lib\unittest.py, line 507, in loadTestsFromTestCase return self.suiteClass(map(testCaseClass, testCaseNames)) TypeError: __init__() takes exactly 1 argument (2 given) So I'm completely stumped as to how to create a method that will only be called only once for Calculator class. Can you please suggest any ideas? Any help will be highly appreciated. Thanks in advance. The constructor of unittest.TestCase takes an optional test name as argument, and in the failing code it is called with such an argument, so when you are subclassing you have to keep the same interface: class Calculator(unittest.TestCase): def __init__(self, name='runTest') : unittest.TestCase.__init__(self, name) # your staff here Note that __init__ gets called one time for test *instance*, not one time for test class. If you want the latest, you could define classmethods that you call explicitely at the beginning of your test code: class Calculator(unittets.TestCase): @classmethod def initialize(cls, ...): # your staff here def test(...): # or wherever your test code starts code Calculator.initialize() # other test class initializations # run your tests HTH Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - code is short simple
On Sep 28, 6:07 am, pylearner for_pyt...@yahoo.com wrote: System Specs: Python version = 2.6.1 IDLE Computer = Win-XP, SP2 (current with all windows updates) ---- Greetings: I have written code for two things: 1) simulate a coin toss, and 2) assign the toss result to a winner. Code for the simulated coin toss is in a file named coin_toss.py. Code for the assignment of the toss result is in a file named toss_winner.py. Each file has one simple function: 1) coin_toss(), and 2) toss_winner(), respectively. (The code for each file is listed below.) Problem: I am getting an error when I run toss_winner.py. Error Message: Traceback (most recent call last): File pyshell#2, line 1, in module toss_winner() File C:/Python26/toss_winner.py, line 7, in toss_winner coin_toss = coin_toss() UnboundLocalError: local variable 'coin_toss' referenced before assignment Question #1: After reviewing the code below, does anybody know why I am getting this error? Explanation: As I understand, the first statement of the toss_winner() function body -- i.e. coin_toss = coin_toss() -- causes four things to happen: 1) the coin_toss() function is called, 2) the coin_toss() function is executed, 3) the coin_toss() function returns the value of its local coin_toss variable, and 4) the returned value of the coin toss variable that is local to the coin_toss() function is assigned to the coin toss variable that is local to the toss_winner() function. Given this understanding, it seems I should NOT be getting a referenced before assignment error, involving the coin_toss local variable of toss_winner(). Note: I am new to programming and Python. I'm currently self-studying Python Programming: An Intro to Computer Science by Zelle. Thanks! --- # toss_winner.py from coin_toss import coin_toss def toss_winner(): coin_toss = coin_toss() if coin_toss == Heads: toss_winner = Player A print 'From toss_winner function ', print Toss Winner = + str(toss_winner) else: toss_winner = Player B print 'From toss_winner function ', print Toss Winner = + str(toss_winner) return toss_winner --- # coin_toss.py from random import random def coin_toss(): random_number = random() if random_number .5: coin_toss = Heads print 'From coin_toss function ', print Toss result = + str(coin_toss) else: coin_toss = Tails print 'From coin_toss function ', print Toss result = + str(coin_toss) return coin_toss You should not use the same name (e.g. coin_toss ) for the function and the variable. Change one of the two, and things will go better. Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: VTK install
On Sep 15, 6:29 am, Gib gib.bo...@gmail.com wrote: As part of the MayaVi install, I need to install VTK. ... Since VTK appears to be installed, I'm guessing that either the path setting is wrong, or python is not using PYTHONPATH. How can I check that PYTHONPATH is being used? The paths in PYTHONPATH should show un sys.path python variable. So just do from a python prompt import sys; sys.path and check if the VTK directories are listed. You colòud aslo tentatively append your path to sys.path and then try again import vtk to see if it is a path problem or something else ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: The future of Python immutability
On Sep 3, 9:07 pm, Nigel Rantor wig...@wiggly.org wrote: Right, this is where I would love to have had more experience with Haksell. Yes, as soon as you get to a situation where no thread can access shared state that is mutable your problems go away, you're also getting no work done becasue the threads, whilst they may be performing lots of interesting calculations have no way of allowing the rest of the program, or operating system, know about it. Threads could communicate only with channels, message queue, or equivalent. Is what I do that as much as I can, to avoid the headache of sharing data between threads. It is less efficient than the shared data model and adds latency, but ensure that each thread is self-contained, making for safer programming and opening the way to better parallelization. AFAIK erlang Processes and scala Actors implement a similar model at language level. In python, there is kamaelia that implements a similar paradigm, although it is more concerned with logical parallelization than with multitheading performance issue. I believe this kind of paradigms will bring us to the massive multicore world easier than FP. Consider that most FP languages have accepted a compromise and become 'unpure' (i.e. have constructs to change variable in place). Even haskell, the only pure FP language I know (sort of), has things like mutable arrays. All these features expose current FP languages at the same 'shared resource' risks of imperative one, although admittedly at a less level. And FP languages have their own crop of problems - e.g how to deal efficiently with deep recursion levels, parameters passed by copy, huge list built in memory (if you use eager evaluation) or build-up of thunks (if you use lazy evaluation). But then, I'm just a programmer, so I could be easily wrong :-) Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: list comprehension troubles..
On 24 Ago, 01:27, mm matta...@gmail.com wrote: Hi, I'm trying to replace this... # this works but there must be a more pythonic way, right? tlist = [] for obj in self.objs: t = obj.intersect(ray) if (t != None): tlist.append((obj,t)) with a list comprehension- can it be done? What I need to do is iterate over a list of graphics primitives and call their intersect method. If the returned t value is not None then I want to store the obj refernence and its t value in a list of tuples for further processing. I've tried stuff like ... tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray)) if (t != None)] tlist = [(obj,t) for obj in self.objs for t in obj.intersect (ray) ] print ,len(tlist), tlist but they don't work. Any help greatly appreciated. matt What about this: def intersections(objlist, ray): for obj in objlist: yield obj, obj.intersect(ray) tlist = [(obj, t) in intersections(self.objs, ray) if t != None ] It is still quite readable but a bit more compact. More efficient? Maybe. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: your favorite debugging tool?
On Aug 22, 4:25 pm, Esmail ebo...@hotmail.com wrote: Hi all, What is your favorite tool to help you debug your code? I've been getting along with 'print' statements but that is getting old and somewhat cumbersome. I'm primarily interested in utilities for Linux (but if you have recommendations for Windows, I'll take them too :) I use emacs as my primary development environment, FWIW. Someone mentioned winpdb .. anyone have experience/comments on this? Others? Thanks, Esmail Although like the others I mostly use print statements, in a few occasions I have found useful to resort to a full-blown debugger. Of the ones I have used, the one provided by eclipse+pydev is the one I liked most. The one in pywin32 IDE is basic but can be useful. With emacs, one should be able to use pydb, but I never used that, although emacs is my most used programming environment on most platforms. About print cumbersomeness, I agree. As I posted elsewhere, I'd like a 'trace mechanism' with the following characteristics: 1. Can be enabled/disabled easily, and when it is dsabled it has no runtime costs ( i.e. disabled 'trace' statements do not generate any code) 2. Can be enabled/disabled on a class/function/method base (e.g. enable only the trace in a method ), to only get the trace output from the code you are debugging 3. Make it easy to report the context (i.e. generate messages which starts with 'class.method:', without hanving to hardcode class name and method name). I know about the 'trace' and 'logging' modules, but neither seem to satisfy the above requirements. Probably using python introspection and metaprogramming features it is possible to do somethinmg that covers at least 2 and 3. Not sure about one (using if __debug__ you can reduce the runtime cost when compiling in optimized mode, but probably not nullify it). Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: conditional for-statement
On Aug 23, 10:09 am, seb sdemen...@gmail.com wrote: Hi, i was wondering if there is a syntax alike: for i in range(10) if i 5: print i equivalent to for i in (for i in range(10) if i5): print i sebastien AFAIK, no syntax fo that. But the standard syntax is not too different: for i in range(0): if i 5 : print i Or you can use itertools.ifilter: for i in itertools.ifilter( lambda x: x 5, range(10) ): print i Or, if you define a function corresponding to the loop body, you could do something like: map( print, (i for i in range(10) if i 5 )) # only works if print is a function Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create ones own lib
On 19 Ago, 11:00, Horst Jäger h.jae...@medienkonzepte.de wrote: Hi, I would like to create my own lib hotte.py which I can import like import string,hotte . How do I do that? I'm working on MacOS 10.5.6 . Thanks in advance Just create the file 'hotte.py' and place it somewhere python can find it, that is: - in the same directory of the code using it (which is most probablyt what you want to do ) - in a directory listed in sys.path variable (which you can extend using sys.path.append(full_path_of_my_library_directory) before doing import hotte There are other options, but these should cover your needs. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a list of list
On Aug 16, 1:25 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: ... Chris' suggestion using itertools seems pretty good: from timeit import Timer setup = \\ ... L = [ [None]*5000 for _ in xrange(%d) ] ... from itertools import chain ... Timer(list(chain.from_iterable(L)), setup % 4).repeat(number=1000) [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] Timer(list(chain.from_iterable(L)), setup % 8).repeat(number=1000) [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] Timer(list(chain.from_iterable(L)), setup % 16).repeat(number=1000) [3.1349358558654785, 4.8554730415344238, 5.431217987061] -- Steven I had a peek at itertools ( which is a C module btw) and realized that chain solves the problem by creating a chain object, which is a sort of generator. Both creating the chain object and converting the chain object to a list seem to be O(N), so the whole is O(N) too ... Then I tried this pure python version: # - CODE from timeit import Timer setup = \\ L = [ [None]*5000 for _ in range(%d) ] def pychain( list_of_list ): for l in list_of_list: for elem in l: yield elem print( Timer(list(pychain(L)), setup % 4).repeat(number=1000)) print( Timer(list(pychain(L)), setup % 8).repeat(number=1000)) print( Timer(list(pychain(L)), setup % 16).repeat(number=1000)) # - END CODE and got times that seem to confirm it : [2.818755865097046, 2.7880589962005615, 2.79232120513916] [5.588631868362427, 5.588244915008545, 5.587780952453613] [11.620548009872437, 11.39465618133545, 11.40834903717041] For reference, here are the times of the itertools.chain solution on my laptop: [0.6518809795379639, 0.6491332054138184, 0.6483590602874756] [1.3188841342926025, 1.3173959255218506, 1.3207998275756836] [2.7200729846954346, 2.5402050018310547, 2.543621063232422] All this with Python 3.1 compiled from source on Xubuntu 8.10. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does my ftp script quit after couple of hours?
On 14 Ago, 18:03, kk maymunbe...@gmail.com wrote: Hi This way the first time I did something with ftp stuff. I think that generally it works but it stops working(quits or disappears) after couple of hours of running. This was a personal test-trial script for my own needs which was to get my dynamic ip and broadcast to a client(I have a client script on another computer). I sure could use something like DynDns for the same purpose with easier management but I just wanted to give it a try to see if i could even make it work . Basically this script parses my ip from DynDns ip check page and uploads it to the given ftp site. It works fine initially, it does upload, it updates the Ip every hour but the problem is that after couple of hours the Python console window disappears, I assume it crashes. I know it does upload at least couple times(works for couple hours). it might be something to do with ftp connection. I will investigate that but I just wanted to see if I have any logic or some kind of contextual problem in the script. Here is the link to Pastie pagehttp://pastie.org/584152 Thanks Try catching the exception inside the main loop, to prevent your program to exit in case of failure: if __name__=='__main__': while True: try: writeExtFile(FILE_PATH,FILE_NAME) uploadFile (FTP_NAME,FTP_USER_NAME,FTP_PASSWD,FTP_FOLDER,FILE_NAME) time.sleep(TIME_DELAY) except: err, det, tb = sys.exc_info() print ERROR =, err, det # gives you a description of the occurred failure traceback.print_tb(tb) # this might be needed only for debug Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: variable scoping question.
On Aug 10, 5:12 pm, Diez B. Roggisch de...@nospam.web.de wrote: Cornelius Keller wrote: Hi, I'm a quite fresh python programmer, (6 Month python experience). Today I found something I absolotly don'nt understand: given the following function: def test_effect(class_id=None,class_ids=[]): if class_id is not None: if class_id not in class_ids: class_ids.append(int(class_id)) print class_ids I observe that the class_ids array is growing when it is called with different class id's. I expected class_ids to be [] if the keyword argument is not set, but it seems to beahve like a static variable if not set. http://effbot.org/zone/default-values.htm Diez Maybe on the first page of python.org there should be a 'python gotchas' link to a page listing these few non-intuituive peculiarities of our beloved snake ... same goes for the official python tutorial ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: socket send
On Jul 30, 10:16 pm, Jan Kaliszewski z...@chopin.edu.pl wrote: 30-07-2009 o 12:29:24 Francesco Bochicchio bieff...@gmail.com wrote: On Jul 30, 5:52 am, NighterNet darkne...@gmail.com wrote: I am trying to figure out how to send text or byte in python 3.1. I am trying to send data to flash socket to get there. I am not sure how to work it. buff= 'id=' , self.id , ':balive=False\n' clientSock.send(buff); Try putting a 'b' before the constant string that you want to send: type(b'123') class 'bytes' It's true. In python '...' literals are for strings ('str' type) and b'...' literals are for binary data (bytes type). Sockets' send() and recv() need binary data ('bytes' objects). or use something like this to convert non constant strings (with only ASCII characters) into bytes: s = A non-constant string : %d % n s 'A non-constant string : 12 ' type(s) class 'str' What??? 'str' type in Python 3.x IS NOT a type of non-constant strings and IS NOT a type of strings with only ASCII characters! 'str' type in Python 3.x *is* the type of immutable ('constant') and Unicode character (Unicode, not only ASCII) strings. It's the same what 'unicode' type in Python 2.x. ... unfortunate choice of words and not enough research on my part here. WHat I meant was: if you want to send via socket a constant string, use b...; if you want to send via socket a string that you made out of variables (the non-constant string ) then you have to convert it in bytes. Since I did not now of the encode method, I tried other solutions, like the one-liner using ord or using the struct module. Obviously, encode is better. My bad :-) Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: socket send
On Jul 30, 5:52 am, NighterNet darkne...@gmail.com wrote: I am trying to figure out how to send text or byte in python 3.1. I am trying to send data to flash socket to get there. I am not sure how to work it. buff= 'id=' , self.id , ':balive=False\n' clientSock.send(buff); Try putting a 'b' before the constant string that you want to send: type(b'123') class 'bytes' or use something like this to convert non constant strings (with only ASCII characters) into bytes: s = A non-constant string : %d % n s 'A non-constant string : 12 ' type(s) class 'str' b = bytes ( ord(c) for c in s ) b b'A non-constant string : 12 ' You could also use struct.pack , that in python 3.x returns bytes and not strings. In this case you need to specify the size of the string (extra bytes are zero-filled): import struct struct.pack( 30s, A non-constant string : %d % n ) b'A non-constant string : 12 \x00\x00\x00' Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Python processors? : WAS Re: Does python have the capability for driver development ?
On Jul 30, 11:10 am, Christian Heimes li...@cheimes.de wrote: Martin P. Hellwig wrote: Well the pyc, which I thought was the Python bytecode, is then interpreted by the VM. Python is often referred as byte-code interpreted language. Most modern languages are interpreted languages. The list [1] is rather long. Technically speaking even native code is interpreted by the micro code of most CPUs. [1]http://en.wikipedia.org/wiki/Interpreted_language [2]http://en.wikipedia.org/wiki/Microcode Once upon a time there where lisp machines, whith processors designed to fastly execute lisp code ... I worked with one of them for 2 years. I wonder: has anybody thought of making a python-machine, or at least a processor able to directly execute high-level bytecode (LLVM-like?). I think the main feature of such a machine should be hyper-fast hash lookup. Then dynamic memory management hardware ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: No PyPI search for 3.x compatible packages
On 30 Lug, 01:55, Neil Hodgson nyamatongwe+thun...@gmail.com wrote: There appears to be no way to search PyPI for packages that are compatible with Python 3.x. There are classifiers for 'Programming Language' including 'Programming Language :: Python :: 3' but that seems to be for implementation language since there are so many packages that specify C. There are a total of 109 packages classified with Python :: [3, 3.0, 3.1] out of a total of 4829 packages.http://pypi.python.org/pypi?:action=browseshow=allc=214c=533 The search box appears to search for any word entered so a search like xml 3.0 or xml AND 3.0 does not help. Some packages include version information in the Py Version column of their download lists or embedded in the download file names. Projects are often constrained to a particular set of Python versions so need to choose packages that will work with those versions. It would be helpful if PyPI made this information more visible and searchable. Neil Are you sure? I note that for example pygtk has as language tags both C and python. So maybe a C extension for python3 would have both C and python 3 as language tags. I suspect that the 109 packages you found are the only ones obf the 4829 which works with python3 (but I hope to be wrong ). Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: socket send
On 30 Lug, 18:06, NighterNet darkne...@gmail.com wrote: On Jul 30, 6:56 am, Mark Tolonen metolone+gm...@gmail.com wrote: NighterNet darkne...@gmail.com wrote in message news:55aba832-df6d-455f-bf34-04d37eb06...@i4g2000prm.googlegroups.com... I am trying to figure out how to send text or byte in python3.1. I am trying to send data to flashsocketto get there. I am not sure how to work it. buff= 'id=' , self.id , ':balive=False\n' clientSock.send(buff); -- http://mail.python.org/mailman/listinfo/python-list Python3.1strings are Unicode (think characters not bytes). When writing to files, sockets, etc. bytes must be used. Unicode strings have an encode() method, where you can specify an appropriate encoding (ascii, latin-1, windows-1252, utf-8, etc.): clientSock.send(buff.encode('ascii')) When reading from thesocket, you can decode() the byte strings back into Unicode strings. data = clientSock.recv(1024).decode('ascii') -Mark I am not sure how to use struct package. Here an example for the input: {id:1,playername:guest,x:100,y:50} {id:2,playername:tester,x:100,y:50} struct.pack(? ) If your messages are ASCII, like it seems, forget about struct, which is for 'binary' message format. Format the string as you would in 2.6 ( using % or string.format for instance ) and then use encode as instructed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Popen
On Jul 24, 6:24 pm, Tim timlee...@yahoo.com wrote: Thanks! Yes I mean subprocess.Popen. I was wondering the meaning of asynchronously Here is some code I am reading recently: result = Popen(cmdline,shell=True,stdout=PIPE).stdout for line in result.readlines(): if find(line,Cross) != -1: return float(split(line)[-1][0:-1]) The computation in the program cmdline takes a long time, at the end of which the results will be output to stdout. asynchronous seems to mean Popen returns to the parent process immediately and the parent and child processes continue to be executed. This is correct However, if Popen returns immediately to the parent process, then there will be nothing in result, not to mention extracting information from the output. Thus it seems to me the parent process has to wait till the child process finish. Calling result.readlines() the parent process attempts to read from stdout until end of file. For a pipe, end of file means that the other end is closing its connection, which - unless the child process closes stdout explicitely - means that the child process is terminated. So the end effect is the almost like using 'communicate' on the result of Popen, except that communicates returns both standard output and standard error contents at the same time. So how to understand the meaning of asynchronous? Thanks and regards! HTH Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: comments? storing a function in an object
On Jul 20, 6:22 pm, Esmail ebo...@hotmail.com wrote: Hello all, I am trying to store a function and some associated information in an object so that I can later have series of functions in a list that I can evaluate one at a time. Right now I am only storing the function itself, the number of arguments it expects and its string representation. I may add other information such as the acceptable range for the parameters or other characteristics such as maximum or minimum. I wonder if anyone could comment on my implementation and offer suggestions or constructive criticisms? The 'loading' of the functions is a bit tedious and of course care has to be taken to make sure the string representation corresponds to the actual function computed. It would be nice if there was an automatic way to convert the function to its string representation. Comments or problems with the approach I have taken? Thanks, Esmail -- #!/usr/bin/env python # # store and represent functions # import math class FunctionException(Exception): custom exception def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter) class Function(object): class to represent a function def __init__(self, fn, fn_str, num_vars): the function, its string representation, and the number of variables self.fn = fn self.fn_str = fn_str self.num_vars = num_vars def eval_fn(self, variables): size of variables should equal num_vars .. else problem if len(variables) == self.num_vars: result = self.fn(*variables) return result else: raise FunctionException('invalid number of args provided - '+ 'received %d, expected %d' %(len(variables), self.num_vars)) def str(self): return string representation of function return self.fn_str def funct1(x): ''' small test function ''' return x * x def funct2(x, y): ''' small test function ''' return x + y def funct3(x): ''' small test function ''' return 1000 + (x*x + x) * math.cos(x) def main(): main method print 'in main' fn1 = Function(funct1, 'x * x', 1) fn2 = Function(funct2, 'x + y', 2) fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1) for i in range(-10, 10): try: print 'f(', [i],') =', print fn3.str(), ' = ', print fn3.eval_fn([i]) except FunctionException, (ex): print ex.parameter if __name__ == '__main__': main() I can offer some small suggestions: it is up to you to evaluate if they make sense for your app: 1. use __doc__ function standard attribute for function description (your fn_str); this meanst that you do not need fm_str in the constructor and you have to do e.g. : def funct2(x, y): ''' x + y ''' return x + y then funct2.__doc__ becomes the string you want to associate to the function 2. Use __call__ instead of eval_fn : this way, the instance of your Function became a 'callable' and can be used everywhere a function is needed. You can do: f = Function(...) f( some_args ) 3. If you call a python function with wrong number of arguments, it already raises a TypeError exception which contains - with different wording - the same information of your FunctionException : consider removing the check and using the python error instead HTH Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: tough-to-explain Python
On Jul 7, 10:04 pm, kj no.em...@please.post wrote: I'm having a hard time coming up with a reasonable way to explain certain things to programming novices. Consider the following interaction sequence: def eggs(some_int, some_list, some_tuple): ... some_int += 2 ... some_list += [2] ... some_tuple += (2,) ... x = 42 y = (42,) z = [42] eggs(x, y, z) x 42 y (42,) z [42, 2] How do I explain to rank beginners (no programming experience at all) why x and y remain unchanged above, but not z? Or consider this one: ham = [1, 2, 3, 4] spam = (ham,) spam ([1, 2, 3, 4],) spam[0] is ham True spam[0] += [5] Traceback (most recent call last): File stdin, line 1, in module TypeError: 'tuple' object does not support item assignment ham += [5] spam ([1, 2, 3, 4, 5, 5],) What do you say to that? I can come up with much mumbling about pointers and stacks and heaps and much hand-waving about the underlying this-and-that, but nothing that sounds even remotely illuminating. Your suggestions would be much appreciated! TIA! kj I would go with something like this: In object oriented programming, the same function or operator can be used to represent different things. This is called overloading. To understand what the operator/function do, we have to look at the kind of object it is applied to. In this case, the operator += means two different things: - for strings and numbers it means : create a new object by merging the two operands. This is why the original object is left the same. - for lists, it means : increase the left operand with the contents of the right operand. This is why the original object is changed You couuld also add: You see, in python everithing is an object. Some object can be changed (mutable objects), others cannot. but this is another story. P:S : Sometime I think they should not have allowed += on immutables and forced everybody to write s = s + some more. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Is code duplication allowed in this instance?
On Jul 3, 12:46 pm, Klone hkm...@gmail.com wrote: Hi all. I believe in programming there is a common consensus to avoid code duplication, I suppose such terms like 'DRY' are meant to back this idea. Anyways, I'm working on a little project and I'm using TDD (still trying to get a hang of the process) and am trying to test the functionality within a method. Whoever it so happens to verify the output from the method I have to employ the same algorithm within the method to do the verification since there is no way I can determine the output before hand. So in this scenario is it OK to duplicate the algorithm to be tested within the test codes or refactor the method such that it can be used within test codes to verify itself(??). If the purpose of the test is to verify the algorithm, you obviously should not use the algorithm to verify itself ... you should use a set of pairs (input data, exoected output data) data that you know is well representative of the data your algorithm will process. Possibly to prepare the test data set you might need a different - and already proven - implementation of the algorithm. Another thing I sometime do when testing mathematics function is use counter-proof: for instance, if my function computes the roots of a quadratic equation, the test verifies that the roots applied to the equation actually give (almost) zero as result. This kind of test might not be as rigorous as preparing the data set with the known answers, but it is easier to setup and could give you a first idea if your code is correct enough to stand more formal proof. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Unexpected behaviour of inner functions/ decorators
Hi all, I found a strange (for me) behaviour of inner function. If I execute the following code: # file in_f.py --- def dec_f(f): def inner_f(): if f.enabled: f() return inner_f @dec_f def funct(): print Ciao funct.enabled = True funct() # end of file - I get the following exception: File /Users/fb/Documents/Prove python/in_f.py, line 15, in module funct() File /Users/fb/Documents/Prove python/in_f.py, line 5, in inner_f if f.enabled: AttributeError: 'function' object has no attribute 'enabled' The same happens when I rebind explicitely the function name instead of using the decorator: def funct(): print Ciao funct = dec_f(funct) It looks like the decorator uses an older instance of 'funct', which does not yet have the attribute dinamically attached to it. This seem to be confirmed by the fact that adding the attribute before rebinding the function name, the problem disappear: def funct(): print Ciao funct.enabled = False # this fixes the problem funct = dec_f(funct) So I have a workaround, but still don't understant why the original code does not work. Anyone can point me to an explanation? Thanks in advance Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: fork, threads and proper closing
On 29 Giu, 07:10, OdarR olivier.da...@gmail.com wrote: On 28 juin, 23:26, Tomasz Pajor ni...@puffy.pl wrote: Hello, Configuration is as follows. I have a starter process which creates 3 sub processes (forks) and each of this processes creates a number of threads. Threads in that processes have semaphore so on KeyboardInterrupt without sending a sigterm to the subprocess i'm not able to close threads. Is there any work around? Can I somehow run join for the thread on keyboard interrupt? When creating a thread you can add a Queue parameter to communicate with threads:http://docs.python.org/library/queue.html easy and reliable. give them a poison pill in the queue: a recognizable object placed on the queue that means when you get this, stop. This is the way I usually go, but it has one important limitation: if the thread is waiting for a blocking I/O operation to complete, like reading from a socket with no data or waiting for a locked resource (i.e. semaphore) to be unlocked, it will not service the queue and will not read the 'quit command' (the poison pill), and therefore will not quit until the blocking I/O terminates (and it could be never). ASAIK, there is no way - in python - to solve this. Olivier Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: file transfer in python
On 26 Giu, 13:38, jayesh bhardwaj bhardwajjay...@gmail.com wrote: i am trying to find something useful in python to transfer html files from one terminal to other. Can this be done with some module or shall i start coding my own module using low level socket interface. If u know about some books on this topic or any online help then plz help. In the standard library there is ftplib, which allows your program to act as a FTP client. Of course the receiver end should have an FTP server installing and running. I don't tink it can handle SFTP protocol, so if you are concerned with security you should opt for someting else, or protect your connection somehow (e.g. SSH tunneling). Or, if you have ssh (client and server) installed, you could simply spawn a subprocess ( see the subprocess module for that ) which execute one or more 'scp' commands. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Recipes for trace statements inside python programs?
Hi all, as many - I think - python programmers, I find muself debugging my scripts by placing print statements in strategic places rather than using the python debugger, and commenting/uncommenting them according to myy deugging needs. After a time, these prints staements start to evolving in some ad-hoc half-baked framework ... so I wonder if there is somewhere there is a full-baked trace statement support framework which I can use. I'm aware of the logging module, but for me it its more geared toward application logging rather than toward trace for debugging purpose. Having googlet and found nothing (or too much but nothing relefìvant), I'm now asking The List. Here is what I have in mind: Each module, function, class and method should have an attribute, say trace_flag, which can be set to true or false value. there should be a function TRACE which does something like this: if __debug__ : def TRACE(*args): if trace_enabled(): print TRACE(%s) : %s % ( context(), .join( str(x) for x in args ) ) where trace_enabled() should return the value of the innermost trace_flag (checking current function/method then current class (if any) then current module) and context() shoud return a string like module.function or module.class.method ). At this point I could in my test code enable the trace in the function/class that gives me trouble and disable it after I fixed it, without having to touch the actual code under test. I guess it should not be too hard do using python introspection modules, but of couse I first would like to know if something like this already exists. I'm aware that this imposes a performance penalty, but my scripts are not operformance-critical. And if I put an if __debug__ switch -- http://mail.python.org/mailman/listinfo/python-list
Re: Recipes for trace statements inside python programs?
Sorry, hit the send button by mistake ... The definition of the trace function should be like: if __debug__ : def TRACE(*args): if trace_enabled(): print TRACE(%s) : %s % ( context(), .join( str(x) for x in args ) ) else : # optimazed code, only a function call performance penalty def TRACE(*args): pass If I don't find anything suitable, maybe I will bake my own again, this time aiming to something that I can reuse ... Ciao and thanks for any tip/suggestion -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Recipes for trace statements inside python programs?
On 25 Giu, 13:15, koranthala koranth...@gmail.com wrote: On Jun 25, 1:40 pm, Francesco Bochicchio bieff...@gmail.com wrote: Is assert what you are looking for? No. Assert raises exception if some condition is met. I just want to be able to enable/disable the printout of intermediate data, on a per function/method/class/module basis, without altering the execution flow. Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
How to find info about python 3.x extension module availability?
Hi all, is there any site that reports the current porting (to Python 3.x) status of the main non-standard extension modules (such as pygtk, pywin32, wxpython, ...) ? I think such information would be very useful for people - like me - which are tryiing to decide how/when/if to port existing scripts/ applications to the new python, or also which python to use to start a new program. I searched and googled for this information but without finding anything. It looks to me that also the single extension module sites are quite shy at announcing plans for the porting (I understand that in part this is for the is ready when is ready philosophy of many non-large open software projects). Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find info about python 3.x extension module availability?
On 23 Giu, 12:59, Francesco Bochicchio bieff...@gmail.com wrote: Hi all, is there any site that reports the current porting (to Python 3.x) status of the main non-standard extension modules (such as pygtk, pywin32, wxpython, ...) ? I think such information would be very useful for people - like me - which are tryiing to decide how/when/if to port existing scripts/ applications to the new python, or also which python to use to start a new program. I searched and googled for this information but without finding anything. It looks to me that also the single extension module sites are quite shy at announcing plans for the porting (I understand that in part this is for the is ready when is ready philosophy of many non-large open software projects). Ciao - FB Well, I kept searching and found this at least : http://www.daniweb.com/forums/thread165340.html It lists Qt , BeautfulSoup (with problems) and pywin32 (which I use a lot :-) Another (less famous) module that I use, ply, also supports python3.x Maybe in the near future I can start porting some of my scripts ... Still believe that a central point to keep track of most of extension porting effort would be very useful ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find info about python 3.x extension module availability?
On 23 Giu, 17:12, Jeff McNeil j...@jmcneil.net wrote: On Jun 23, 6:59 am, Francesco Bochicchio bieff...@gmail.com wrote: Hi all, is there any site that reports the current porting (to Python 3.x) status of the main non-standard extension modules (such as pygtk, pywin32, wxpython, ...) ? You can pull a list of what works with 3.0 via PyPi, there's a link which points you tohttp://pypi.python.org/pypi?:action=browsec=533show=all. If the package isn't listed on PyPi, I believe you'll have to check out the vendor/distribution site. I posted something like this on my blog a few months back. Finding what's available isn't too terribly difficult. I thought it would be nice to have a port status page that lets the community know where certain package stand so volunteers can step in and help. I guess it would be rather difficult to keep such a page updated, though - Mostra testo citato - Thanks. I thought of pypy, and even tried to search for Python 3 using its search button, but somehow missed the handy python 3 link on the sidebar :-0 I agree that keeping a complete list would be very difficult, although useful ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Input problem
On 16 Giu, 11:32, Prasoon prasoonthegr...@gmail.com wrote: I am new to pythonand using python 2.6 I want to know when to use raw_input( ) and when to use input( )??? According to my interpretation one should use input( ) when entering numbers etc and raw_input( ) when a string is too be entered. Correct me if I am wrong You should almost always use raw_input and write your own code to validate the input and convert it. input (wich is roughly equivalent of veval (raw:_input()) is officially considered a Bad Choice and as such has been changed in Python 3.x ( that is, python 3.x 'input' is equivalent to python 2.x raw_input ). P.S : if you are new to python and don't expect to use external libraries for the next months (one year?) you might consider to start directly with python 3.x. Also if I want to enter two numbers 'a' and b such that while entering them through the keyboard there is a space between the two... For example:Enter two numbers: .12 15 Can I use input( ) such that 12 gets accepted in 'a' and 15 in 'b' I mean how to handle spaces???/ For instance: map( int, raw_input.split() ) splits the input string using blanks as separator, then try to convert each piece in an integer and returns a list of integer. Of course if the input string is not a list of integer you get an exception. You could also do: a, b = map( int, raw_input.split() ) but in this case you get an exception also if the input strings cobntains less or more than two integers. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: EOF problem with ENTER
On 12 Giu, 08:49, Prasoon prasoonthegr...@gmail.com wrote: On Jun 12, 11:28 am, Chris Rebert c...@rebertia.com wrote: On Thu, Jun 11, 2009 at 11:17 PM, Prasoonprasoonthegr...@gmail.com wrote: I am new to python I have written the following program in python.It is the solution of problem ETF in SPOJ. #Euler Totient Function from math import sqrt def etf(n): i,res =2,n while(i*i=n): if(n%i==0): res-=res/i while(n%i==0): n/=i i+=1 if(n1): res-=res/n return res def main(): t=input() while(t): x=input() print str(etf(x)) t-=1 if __name__ == __main__: main() The problem with my code is that whenever I press an extra Enter button instead of getting the cursor moved to the next line.I get an error _SyntaxError- EOF while parsing and the program terminates.._ How should the code be modified so that even after pressing an extra Enter button the cursor get moved to the next line instead to throwing an exception.. Use raw_input() instead of input() [at least until you switch to Python 3.x]. input() does an implicit eval() of the keyboard input, which is (in part) causing your problem. Note that you'll need to explicitly convert the string raw_input() reads in using either int() or float() as appropriate. Still, you can't just enter extra lines and expect the program to automatically ignore them. You'll have to write the extra code yourself to handle empty input from the user. Cheers, Chris --http://blog.rebertia.com I am using Python 2.6 I have modified that code def main(): t=int(raw_input()) while(t): x=int(raw_input()) print str(etf(x)) t-=1 what should i do to handle new line and space.. We used to get spaces and newline in C using their ASCII values ...can similar things be done here??? Please write the code snippet(by modifying my code) from which i can understand something..! - Mostra testo citato - You could do: while True: x = raw_input(Enter x=) if x != : break # if you just press enter, raw_input returns an empty string Note that this still leaves out the case when you type something which is not a number. To cover this case, supposing that you need a float, you could do like this (NOT TESTED): while True: x_str = raw_input(Enter x=) if x_str != : # to prevent having the error message on empty imput try: x = float(x_str) break # if it gets here the conversion in float was succesful except ValueError : print The input '%s' cannot be converted in float % x_str This code exits from the loop only when you supply a string that represents a floating number Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Definition of Pythonic?
John Yeung ha scritto: On Apr 11, 10:08 am, Emmanuel Surleau emmanuel.surl...@gmail.com wrote: Having written a few trivial scripts in Python, I'm curious as to how you would sum up the Pythonic philosophy of development. A couple of others have already mentioned the Zen of Python, available at the Python command prompt. I would agree with that, but also add the caveat that none of the principles expressed there are hard-and- fast rules. Hopefully that is clear from the quasi-contradictory nature of the principles, but inevitably there will be some people who complain that Python breaks this or that rule from the Zen. I believe the almost-contraddictory nature of the various listed principles is on-purpose. My anecdotal knowledge of the Zen tells me that is based on the balance of two 'opposing forces', the Yin and the Yang. So the 'zen of python' attempts to enunciate the various yins and yangs of software development, leaving to the developers the task of finding the right equilibrium among them. Which is pretty sensible, since good engineering is often based more on choosing the right trade-off rather than choosing the One Right Thing to do. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6/3.0 packages for Ubuntu?
s...@pobox.com ha scritto: Does Ubuntu really not have Python 2.6 or 3.0 packages or do I just have my package list misconfigured? I'm setting up a fresh machine and am not too Ubuntu-aware. Is there a list of package repositories around somewhere? Thx, In current 8.10, the default python is 2.5, but there is a set of packages python3-... which gives you the 3.0. The upcoming 09.04 will have 2.6 as standard, I think ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading 3 objects at a time from list
Chris Rebert ha scritto: On Sat, Apr 11, 2009 at 1:44 AM, Matteo tadweles...@gmail.com wrote: Hi all, let's see if there is a more pythonic way of doing what I'm trying to do. I have a lot of strings with numbers like this one: string = -1 1.3 100.136 1 2.6 100.726 1 3.9 101.464 -1 5.2 102.105 I need to pass the numbers to a function, but three at a time, until the string ends. The strings are of variable length, but always a multiple of three. That's what I did: num = string.split() for triple in zip(num[::3], num[1::3], num[2::3]): func(*triple) it works and I like slices, but I was wondering if there was another way of doing the same thing, maybe reading the numbers in groups of arbitrary length n... See the grouper() recipe in the `itertools` module -- http://docs.python.org/library/itertools.html Cheers, Chris I would do that with a generator: def groups(l,n) : ... while l: yield l[:n]; l=l[n:] ... list(groups(range(14),4)) [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13]] list(groups(range(18),3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17]] Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing threads
On Sat, 04 Apr 2009 22:45:23 -0700, ericwoodworth wrote: On Apr 5, 12:22 am, a...@pythoncraft.com (Aahz) wrote: In article 4b52f7d7-81d5-4141-9385-ee8cfb90a...@l1g2000yqk.googlegroups.com, ericwoodwo...@gmail.com wrote: I'm using queues to talk between these threads so I could certainly put some kind of message on the queue that causes the threads to commit suicide but I'm thinking there's a more built in way to do what I want. I'm just not sure what it is. There isn't, you have the right idea about using queues. -- Ok good to know. I was letting the search for a really cool solution stop me from rolling out what I think I already know how to do. Thanks. If yor threads are not set as 'deamons' using Thread.setDaemon method, then your main program at its termination should call Thread.join for each of the thread spawned, otherwise the whole process will not quit. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing dynamic languages
On Sat, 04 Apr 2009 07:37:44 -0700, grkuntzmd wrote: I am a Java developer. There, I said it :-). When I am writing code, I can rely on the compiler to confirm that any methods I write will be called with parameters of the right type. I do not need to test that parameter #1 really is a String before I call some method on it that only works on Strings. If I am writing in Python, since it is dynamically, but strongly typed, I really should check that each parameter is of the expected type, or at least can respond to the method I plan on calling (duck typing). Every call should be wrapped in a try/except statement to prevent the method (and program) from crashing when my method is called with an integer instead of the expected string. Is this the experience that Python programmer (of large projects) see? Do you also write unit tests to confirm that the methods actually check for and catch bad parameter types? If I am writing small one- off scripts, I wouldn't worry about it, but if I am writing a large system that must have 99+% uptime without constant monitoring, this really should be verified. Up for discussion... Uhm. I write large bodies of code for living ... not in Python, unfortunately. I usually divide my code in two classes wrt sanity checks : inner code and boundary code. Boundary code gets paranoic checks on everything: arguments, consistency etc ... also with static typing : an 'int' parameter declaration in C/C++ make sure that your function gets an integer, but ensure nothing in the way of minimum and maximum value, so before using it - say - as an array index, it is better to check that. Inner code gets less checks, based on the assumptions that inputs have been properly checked by the boundary functions. This method is not without risks - an architectural change can move a function from an inner zone to a boundary zone, and I may forget to 'fortify' the function. However, this is a guideline that served me well. Beside that there is another guideline I apply to languages like java and python - programs in these languages do not 'crash' ... they throw exceptions. Now, supposing to add an input check : what are you going to do if you find bad data? In the answer is - as often the case - throw an exception, then maybe the check is not worth much ... There are exceptions to this guideline, as always, like if you want to generate a more meaningful exception, but this is another guideline I tend to follow. And this means that my level of checking in python is much lower than in - say - C++. And I don't worry too much about argument types, more about external inputs with the right 'semantic'. The one coding behaviour that dynamic types forced me to change, is that now I tend to build programs more incrementally, because catching typos error and logic errors at the same time on a large body of code can be frustrating and not very productive ... but I find myself to use now the same approach also when I code in statically typed languages : a bit slower at beginning, but tend to procuce more reliable results . Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter questions: behavior of StringVar, etc
Alan G Isaac ha scritto: On Mar 28, 2:15 pm, Alan G Isaac alan.is...@gmail.com wrote: I'm a complete newbie to GUI. I have a couple questions about tkinter. 1. Where is the list of changes in Python 3's tkinter? 2. What exactly is the role of the root object, traditionally created as ``root=tk.Tk()``? What is an example where one should create this before creating a Frame instance (which will otherwise implicitly create one as its master)? 2'. Suppose I ``import tkinter as tk`` and then try ``s1=tk.StringVar()``. This fails because no master is set. Why does a Variable need a master? 3. Now suppose I set ``root = tk.TK()`` and then try ``s1=tk.StringVar()``. This works fine but now seems a bit magical: how has the value of the master been set? 4. Another bit of magic: Suppose I ``import tkinter as tk`` and then try ``f1=tk.Frame()``. This works fine: apparently calling Frame also leads to implicit creation of a master. Why is what is good for the gander (i.e., implicit master creation for a Frame) not good for the goose (i.e., a Variable)? (Here I assume that there has been an answer to 2. above.) 5. Reading around a bit, it seems common to recommend setting the values of Variables rather than initializing them. Why? I cannot see the reason to avoid ``s1=tk.StringVar(value=this works fine)`` and it looks like ``tk.StringVar(()`` is in any case initialized (to an empty string). 6. Why is str(s1) not its value? More generally, why does a StringVar not behave more like a string? On 3/28/2009 6:19 PM Mike Driscoll apparently wrote: Try Google and the Python website. There is tons of info on the Python wiki: http://wiki.python.org/moin/TkInter There are also some books that walk you through Tkinter application creation, for example,Lutz's Programming Python. Sorry, but I do not see the answers to any of the above questions, not even the first one. Do you? (One might believe question 2 is answered, but if you read it, I think you will see why I do not.) Cheers, Alan Isaac I think you need a bit of background (if not, just ignore this post): 1. Tkinter is only a thin wrapper over Tk, a GUI library initially developed for Tcl language, so many of the answer to the design choices you question (e.g. what is the master) cannot between answered within the python documentation but should be searched in the Tcl/Tk documentation. So google for tcl/tk. Anyway, all GUI libraries I know of build the GUI as a hierarchical structure. The master (often called root) ia the root of this hierarchy, and you have to build it before building the rest. 2. Another good source of information is the source of Tkinter itself, which is mostly in the Tkinter.py file. This is available in your python installation, so dig into it: if you for instance look at the __init__ method of the Variable class (which is the basic class of StringVar), you will easily find the 'magic' to which you refer to. If you don't like the choices which have been made there (e.g not automagically creatinga a master for variables but doing it for frames ), you could try and submit a patch :-) 3. Usually the changes between one version of python and the next are documented (but not in all gory details) in What is new documents you can find in python.org site. I'm not aware of any change for Tkinter, in Python 3.0 but go read it yourself. If you want more details you could always fetch the Tkinter.py file (or others) of bot versions and make a diff. Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: python contextmanagers and ruby blocks
On Sat, 21 Feb 2009 09:42:02 -0800, Aahz wrote: In article aac004f8-2077-4e53-a865-47c24f7f5...@t3g2000yqa.googlegroups.com, Alia K alia_kho...@yahoo.com wrote: Nevertheless, I remain curious about whether once can use the contextmanager in python to achieve the full power of ruby's blocks... Short answer: no Longer answer: the way in Python to achieve the full power of Ruby blocks is to write a function. Which was where I was aiming to with my very long-winded post :-) Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: python contextmanagers and ruby blocks
On Sat, 21 Feb 2009 00:46:08 -0800, Alia Khouri wrote: As an exercise, I recently translated one of my python scripts (http:// code.activestate.com/recipes/576643/) to haskell (a penultimate version exists at http://groups.google.com/group/comp.lang.haskell/browse_thread/thread/fb1ebd986b44244e# in case anyone is interested) with the result that haskell has now become my second favourite language (after python of course :-) Just to change mental gears a bit, I'd now like to do the same and create a ruby version. As I've progressed on the latter, I've been struck by how pervasive the use of blocks is in ruby. For example: ... ruby code that shows the most twisted 'Hellow world' example I have ever seen :-) ... Now, python's relatively new contextmanagers seem to provide something similar such that one can write: ... python code doing the same thing - apparently - of prevous ruby code, using context managers in a way that I believe the authors of contextlib module never thought of. Which brings me to my questions: 1. To what extent are python's contextmanagers similar or equivalent to ruby's blocks? ASAIK, context managers are nothing like ruby blocks. Context managers have a very specific purpose : to make people able to abstract the code that one writes to 'enter a context' (i.e. open a file, start a transaction, ... ) and 'leave a context' (i.e. close a file, commit or rollback the transaction ... ). So that you can separate context handling code from the code that performs actions insed that context, factoring out the first for reuse and better code maintenance. Ruby blocks are blocks of code which can be passed as objects for a number of different usage - for instance to make context management stuff. If I have to compare them to something in Python, I would say they are 'lambda on steroids' or 'nameless functions'. And - personally - I don't like them just as I don't like lambdas in python for anything but one-liners and I don't like anonymous functions in haskell (which I am painfully trying to learn ). They may be cool to write, but they look not very readable to me - but maybe this is just me. Ciao FB Ruby blocks - for the little I know of ruby - are anonymous block of codes 2. If there is a gap in power or expressiveness in python's context managers relative to ruby's blocks, what are possible (syntactic and non-syntactic) proposals to bridge this gap? Thank you for your responses. AK -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter
Luke ha scritto: Hello, I'm an inexperienced programmer and I'm trying to make a Tkinter window and have so far been unsuccessful in being able to delete widgets from the main window and then add new ones back into the window without closing the main window. The coding looks similar to this: ... It may just be bad coding but either way I could use some help. Thanks I fixed your code to do what you want, although I have no idea why you want it... The main change is that you need to place the code to be executed when the button is clicked in a different function, and use the name of that function as value of the on_command property of the button. Then you need to give back the control to Tkinter, calling the mainloop function and when the button is clicked, your function is called. This sort of ping-pong is called event-driven programming, and it is how most GUI toolkit work. The functions called when a GUI event occurs are called callbacks. A secondary thing is that since both the main function and the callback read and change some 'variable' pointing to the widgets, you need to share them using python 'global' statement. Now, a better way to do it would be incapsulate all in a class, but I wanted to stay as much as possible close to your code. Finally, if you plan to to something that requires to dynamically create and destroy - or move arounds - graphical objects (not widgets), you might want to have a look to the 'Canvas' widget. Code follows after signature. Since the frame and the button are recreated just after having been destroyed, you just see them flicker. Ciao FB # # Module-level variables referring to widgets # used/changed by more than one function # back_ground = None frame1 = None def make_frame_and_button(): global frame1, back_ground print 'background', back_ground frame1=Frame(back_ground,width=213,height=480,bg='white') print 'Frame1', frame1 frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) close_frame1=Button(frame1,text='close', bg='blue', command=on_close_button ) print 'close_frame1', close_frame1 close_frame1.pack_propagate(0) close_frame1.pack(side=TOP, anchor=N,pady=25) def on_close_button(): global frame1 frame1.destroy() make_frame_and_button() def MainWin(): global back_ground, frame1 main=Tk() main.geometry('640x480') back_ground=Frame(main,width=640,height=480,bg='black') back_ground.pack_propagate(0) back_ground.pack(side=TOP,anchor=N) make_frame_and_button() main.mainloop() MainWin() -- http://mail.python.org/mailman/listinfo/python-list
Re: file write collision consideration
On Tue, 20 Jan 2009 11:08:46 -0500, D'Arcy J.M. Cain wrote: On Tue, 20 Jan 2009 10:57:52 -0500 RGK bl...@empty.blank wrote: I have a thread that is off reading things some of which will get written into a file while another UI thread manages input from a user. The reader-thread and the UI-thread will both want to write stuff to the same output file. What first comes to mind is that there may be write collisions, ie both trying to write at the same time. Why not create a third thread that handles the write? The other threads can simply add objects to a queue. You will still need collision handling in the queue adder but it only needs to block for a small time as opposed to the much longer disk write time. IIRC, Queue.Queue objects handle by themselves multi-thread access, that is there is no need to additional locking mechanism ... Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: pep 8 constants
On Wed, 14 Jan 2009 08:13:30 +, Steven D'Aprano wrote: Absolutely. It's rather sad that I can do this: import math math.pi = 3.0 I like the ability to shoot myself in the foot, thank you very much, but I should at least get a warning when I'm about to do so: math.PI = 3.0 # use God-like powers to change a constant Constants would be a nice addition in python, sure enough. But I'm not sure that this can be done without a run-time check every time the constant is used, and python is already slow enough. Maybe a check that is disabled when running with optimizing flags ? But I'm sure this discussion has been already made and the FINAL WORD has been already spoken. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Implementing file reading in C/Python
On Fri, 09 Jan 2009 15:34:17 +, MRAB wrote: Marc 'BlackJack' Rintsch wrote: On Fri, 09 Jan 2009 04:04:41 +0100, Johannes Bauer wrote: As this was horribly slow (20 Minutes for a 2GB file) I coded the whole thing in C also: Yours took ~37 minutes for 2 GiB here. This just ~15 minutes: #!/usr/bin/env python from __future__ import division, with_statement import os import sys from collections import defaultdict from functools import partial from itertools import imap def iter_max_values(blocks, block_count): for i, block in enumerate(blocks): histogram = defaultdict(int) for byte in block: histogram[byte] += 1 yield max((count, byte) for value, count in histogram.iteritems())[1] [snip] Would it be faster if histogram was a list initialised to [0] * 256? I tried it on my computer, also getting character codes with struct.unpack, like this: histogram = [0,]*256 for byte in struct.unpack( '%dB'%len(block), block ): histogram[byte] +=1 yield max(( count, byte ) for idx, count in enumerate(histogram))[1] and I also removed the map( ord ... ) statement in main program, since iter_max_values mow returns character codes directly. The result is 10 minutes against the 13 of the original 'BlackJack's code on my PC (iMac Intel python 2.6.1). Strangely, using histogram = array.array( 'i', [0,]*256 ) gives again 13 minutes, even if I create the array outside the loop and then use histogram[:] = zero_array to reset the values. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Using PythonPath under Windows Vista.
On Sun, 04 Jan 2009 04:56:51 -0800, Morgul Banner Bearer wrote: Hi Everybody, ... The behaviour of the program is as follows : In a Dos Box, the program executes nicely when i type : c\python26python c:\python26\work\brian.py. Now i understand that- because I set the Pythonpath- the program should also run if i type: c\python26python brian.py (under these conditions Python should look for the file brian.py in the folders specified in the Pythonpath). However, this does not work, but gives : Can't open file... No such file or directory. I have not found further info availlable on bulletin boards on the internet, so if anybody can post the solution here, that would help me out. AFAIK, PYTHONPATH only works for the imported modules. For the main module, you have to do give the full path. OR you could try out the new flag -m, which allows to run directly a module from the standard library and - I guess - also user modules if PYTHONPATH is set correcltly. So try from a DOS Box the command: c\python26python -m brian.py Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: yacc statement recognition [PLY]
Slafs ha scritto: Hi ALL! I have to write in yacc an acceptor of files with lines matching this regexp: '[0-9],[0-9]' and I don't know what I am doing wrong beacuse this: tokens = ( 'NUMBER', ) literals = [','] t_NUMBER = r'\d' ... def p_statement_exp(p): '''statement : NUMBER ',' NUMBER ''' print OK! sys.exit() --- also accepts lines like 2,abcdef3 which of could someone please tell me what's wrong in my code? full source on http://paste-it.net/public/vba22d5/ Your code works for me (Python 2.5 and ply 2.3 on ubuntu 8.10), except that, from the rest of your code, I see that you parse separately each line of file. Since you put a sys.exit() in the parsing rule, it means that at the first line successfully parsed your program will quit. Try putting a simple print in it and instead putting the sys.exit in your p_error function (if you want to exit at the first 'wrong' line line). BTW, are you aware that exists a specific google group for ply users? Specific ply questions could be answered here : http://groups.google.com/group/ply-hack?pli=1 Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a better algorithm?
Kottiyath ha scritto: I have the following list of tuples: L = [(1, 2), (3, 4, 5), (6, 7)] I want to loop through the list and extract the values. The only algorithm I could think of is: for i in l: ... u = None ... try: ... (k, v) = i ... except ValueError: ... (k, u, v) = i ... print k, u, v - 1 None 2 3 4 5 6 None 7 - But, this algorithm doesnt look very beautiful - like say - for k, u, v in L: Can anyone suggest a better algorithm to get the values? One way to avoid explicit checks on tuple size (but making the code a bit less clear and probably slower): for i in l: k, v, u = (i[:3]+(None,))[:3] ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse order of bit in repeating seqence of byte string
imageguy ha scritto: I am looking for the most efficient method of replacing a repeating sequence in a byte string returned from a imaging .dll, connected via I receive the byte string with the following sequence 'bgrbgrbgrbgr' and I would like to convert this to 'rbgrbgrbgrbg' FWIW, the string is created using ctypes.create_string_buffer function The following code works but feels a bit clunk and is rather slow too. blist = list(buffer) for start in xrange(0,len(blist), 3): try: blue = blist[start] red = blist[start+2] blist[start] = red blist[start+2] = blue except IndexError: pass new_buffer = ''.join(blist) new_buffer is then passed to a wx program to create and image. Any thoughts comments would be appreciated. geoff. PS: I started this post earlier, but I think I hit the send button too soon. My apologies to the group for sloppy typing. You could try the same algorithm on an array.array object : it might be faster. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Can you post an example program that exhibits the behavior you describe? I was forgetting about the MSG_WAITALL flag ... When I started programming with sockets, it was on a platform (IIRC Solaris) that by default behaved like MSG_WAITALL was set by default (actually, I don't remember it being mentioned at all in the man pages). This sort of biased my understanding of the matter. I actually used that flag recently - on Linux - to get the same behavior I was used to, but forgot about that. My bad :-) Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: MemoryError when list append... plz help
[BON] ha scritto: == s=[] for i in range(11000-1): for j in range(i+1, 11000): s.append(((i,j),sim)) == above sim is floating type. s.append is totally coducted 60,494,500 times. but this code raise MemoryError. My computer has 4G RAM. i think it's enough. but it doesn't... So, i've tested below code. == a=[] i=0 while i60494500 : a.append(i) i+=1 == but this code raise also MemoryError. How can i resolve this problem? please, help... Regards, If you _really_ have to store so many numbers in memory (hint: if you are processing them sequentially, you don't need to store all them - use generators instead) then you may have better luck using mmap module to create a huge file-memory object, that you can access both as a file and as a list, and put numbers in it after packing/unpacking with struct. Something like this (only marginally tested ): memory = mmap.mmap(-1, 60494500*4) def memory_put(offset, f): ... memory[offset*4:(offset+1)*4] = struct.pack( %f, f ) def memory_get(offset): ... return struct.unpack( f, memory[offset*4:(offset+1)*4] )[0] memory_put(12, 3.14 ) memory_get(12) 3.141049041748 Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Grant Edwards ha scritto: On 2008-12-30, Francesco Bochicchio bock...@virgilio.it wrote: 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in select between blocking and non-blocking mode. The difference is in the recv (again, assuming that you use TCP as protocol, that is AF_INET, SOCK_STREAM), which in the blocking case would wait to receive all the bytes that you requested, No, in blocking mode it will wait to receive _some_ data (1 or more bytes). The requested amount is strictly an upper limit: recv won't return more than the requested number of bytes, but it might return less. Uhm. In my experience, with TCP protocol recv only returned less than the required bytes if the remote end disconnects. I always check the returned value of recv and signal an error if the read bytes are less than the expected ones, but this error is never occurred (and its about 20 years that I use sockets in various languages and various flavor of unix and occasionally on windows. Maybe have always been lucky ? :-) And, on some unices system call recv also returns when a signal interrupts the syscall, but I half-remember reading that python recv in such a case repeat the system call by itself ... although this might be only my desire ... In non-blocking mode, it will always return immediately, either with some data, no data (other end closed), or an EAGAIN or EWOULDBLOCK error (I forget which). [...] I myself tend to avoid using non-blocking sockets, since blocking sockets are much easier to handle... That depends on whether you can tolerate blocking or not. In an event-loop, blocking is generally not allowed. What I usually do, when I cannot block is: - use socket in blocking mode - do a select with a very small timeout and do a recv only if the select returns with input events - (with TCP) do a recv for the exact amount of bytes that I expect ( this mean having a user protocol that carries the message size in the header, but this is usually the case ). This usually worked for me. If my process (or thread) has only to deal with socket I/O, I make a blocking select, and then make an 'exact' recv on whichever socket the select signals. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Jean-Paul Calderone ha scritto: On Tue, 30 Dec 2008 19:19:08 +0100, Francesco Bochicchio bock...@virgilio.it wrote: [snip] If you are interested in socket errors, you should also fill the third 'fd-set' in the select call, and after select returns check that fd is not in it anymore: ready = select.select( [fd],[], [fd] ) if fd in ready[2]: # raise your error here The third argument to select() isn't for monitoring sockets for errors. Its behavior is also rather platform sensitive. In general, you don't need it at all on POSIX, but on Windows you should pass the same list for it as you pass for the write-set, merge the results, and treat them all as writeable. Or use a higher-level library that deals with all the asinine details for you. ;) Jean-Paul Yes, now that you mention it I remember having to do something like that on a socket library I wrote on windows ... IIRC, the send could not complete and then signal the readyness of the socket through the third argument of the select ... My experience is mostly on unices, and I usually don't use the third argument (and not often the second) but I remember having read on select manual page that it was for errors. Now both python manuals than select manual page say it is for 'exceptional conditions', without going into details ... Tx for the clarification, anyway ... Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Francesco Bochicchio ha scritto: No, in blocking mode it will wait to receive _some_ data (1 or more bytes). The requested amount is strictly an upper limit: recv won't return more than the requested number of bytes, but it might return less. Uhm. In my experience, with TCP protocol recv only returned less than the required bytes if the remote end disconnects. I always check the returned value of recv and signal an error if the read bytes are less than the expected ones, but this error is never occurred (and its about 20 years that I use sockets in various languages and various flavor of unix and occasionally on windows. Maybe have always been lucky ? :-) BTW, this is not a rethorical or ironic question... my applications mostly run on LANs or dedicated WANs so maybe they never experienced the kind of network congestion that could cause recv to return less than the expected amount of bytes ... but then, IIRC TCP guarantees that the packet is fully received by hand-shaking at transport level between sender and receiver. Ad once the packet is fully in the receiver buffer, why should recv choose to give back to the application only a piece of it? Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
... Uhm. In my experience, with TCP protocol recv only returned less than the required bytes if the remote end disconnects. I always check the What if the sending end actually sent less than you asked for ? -srp In blocking mode and with TCP protocol, the recv waits until more bytes are received - mixing up the next message with the previous one and then loosing the 'sync' and being unable to interpretate the received data - or the remote end disconnects. Yes this is bad, and is a good reason why socket receive should be handled in non-blocking mode if you receive data from untrusted sources. But luckily for me, as I said in the other post, I used socket mostly to communicate between specific applications on a private LAN or WAN, so I could afford to ignore the problem. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Saju Pillai ha scritto: On Dec 31, 7:48 pm, Francesco Bochicchio bock...@virgilio.it wrote: Is this correct ? IIRC even in blocking mode recv() can return with less bytes than requested, unless the MSG_WAITALL flag is supplied. Blocking mode only guarantees that recv() will wait for a message if none is available - but not that it *will* return the number of bytes requested. -srp You are right ... most of my socket experience predates MSG_WAITALL, and I forgot that now the default behaviour is different ... oops ... Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select and socket.setblocking
Laszlo Nagy ha scritto: I'm using this method to read from a socket: def read_data(self,size): Read data from connection until a given size. res = fd = self.socket.fileno() while not self.stop_requested.isSet(): remaining = size - len(res) if remaining=0: break # Give one second for an incoming connection so we can stop the # server in seconds when needed ready = select.select([fd], [], [], 1) if fd in ready[0]: data = self.socket.recv(min(remaining,8192)) # 8192 is recommended by socket.socket manual. if not data: # select returns the fd but there is no data to read - connection closed! raise TransportError(Connection closed.) else: res += data else: pass if self.stop_requested.isSet(): raise SystemExit(0) return res This works: if I close the socket on the other side, then I see this in the traceback: File /usr/home/gandalf/Python/Projects/OrbToy/orb/endpoint.py, line 233, in read_data raise TransportError(Connection closed.) TransportError: Connection closed. Also when I call stop_requested.set() then the thread stops within one seconds. Then I switch to non blocking mode, my code works exactly the same way, or at least I see no difference. I have read the socket programming howto ( http://docs.python.org/howto/sockets.html#sockets ) but it does not explain how a blocking socket + select is different from a non blocking socket + select. Is there any difference? Thanks Couple of remarks: 1. AFAIK, select in python accepts also socket objects, or anything which has a fileno() method returning an integer. So you don't need to extract the fileno from the socket (python will do for you) although it does no harm. 2. IMO, the behaviour of your code is correct: with TCP protocol, when the remote ends disconnects, your end receives a 'read event' without data; you should just handle the fact that recv returns nothing as normal, not as error, and close your end of the connection. If you are interested in socket errors, you should also fill the third 'fd-set' in the select call, and after select returns check that fd is not in it anymore: ready = select.select( [fd],[], [fd] ) if fd in ready[2]: # raise your error here 3. AFAIK (sorry, I feel acronym-ly today ;), there is no difference in select between blocking and non-blocking mode. The difference is in the recv (again, assuming that you use TCP as protocol, that is AF_INET, SOCK_STREAM), which in the blocking case would wait to receive all the bytes that you requested, or the disconnection, in the other case would return immediately (and you should check the number of returned bytes, and when you read the remaining bytes of the message put the pieces together). I myself tend to avoid using non-blocking sockets, since blocking sockets are much easier to handle... HTH Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Emacs vs. Eclipse vs. Vim
On Sat, 29 Nov 2008 12:44:14 -0800, Josh wrote: If you were a beginning programmer and willing to make an investment in steep learning curve for best returns down the road, which would you pick? Honestly, I would invest my time and energy in someting more significant than editor skills. In twenty+ years of programming I have used all three environments and many others, and I never found them critically important for my job. Sure a good editor and/or IDE can make your life easier. And a bad one can make you suffer - but then you just switch ... But at the end of the day they are just tools, and IMO not the most important ones in the toolchain that you have to use to do your job. Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting VB apps to Python for Window / Linux use
Il Sun, 19 Oct 2008 10:34:23 +0200, Stef Mientki ha scritto: ... I'm very satisfied with Python, and must say it's much more beautiful language than Delphi, seen over the full width of programming. Although both languages are Object Oriented, for some (unknown) reason it's 10 times easier to maintain and extend libraries in Python than in Delphi. I WOULD BE MUCH OBLIGED, IF SOMEONE CAN EXPLAIN THAT DIFFERENCE ! And with wxPython and some tools I made, I almost have the same environment as Delphi. IMO: - dynamic typing - powerful built-in types like lists, sets and dictionaries - very rich function definition syntax, with multiple returns, yield, values passed by position and by name, automatic grouping of parameters in list/dictionaries - rich standard library, which becomes impressive if you accound for all the non standard modules that you find in internet. And, unlike another language wich shall remain unnamed (starts with J), most of python library modules have the same pratical approach of C standard library. Never used seriously delphi, but played a little with it: IIRC, under the nice IDE and GUI toolkit, the language itself is a kind of object-pascal. This would place it more or less at the same level of abstraction of Java, way below languages like python and ruby, Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows / Tkinter - problem with grid - not able to place widgets at desired places
Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: Hi, I'm learning Python and Tkinter. I've started programming in Eclipse with PyDev. I'm intending to create a GUI. I'm not able to understand the Grid manager perhaps because there is quite a less documentation available for it on the net. My desired GUI is attached in the mail. Although I've tried writing a class module for this GUI but I'm not able to set all things right in the GUI. The Biggest problem seems to be with the Grid Manager in terms how it divides a window in Rows / columns. etc. I'm not able to place none of the widgets correctly in the GUI. For your convenience, I'm attaching this code also as myModule1.py . Please some one review it and help create me this GUI. Uhm, I don't think you should use the grid manager to obtain a window like that. The grid manager is for equally distributing widgets both horizontally and vertically. And I'm not sure that you can realize that window look with Tkinter. You could get close by horizontally packing each widget row in a frame and then vertically packing the frames in the window. But the look will be quite different than your target. If you are not satisfied with that I suggest you move to other toolkits which have more complex geometry managers than .pack and .grid. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: translating create Semaphore to Linux
On 29 Ago, 13:28, GHUM [EMAIL PROTECTED] wrote: hello, in my application I am using hSem = win32event.CreateSemaphore (None, 1, 1,stringincludinginterfaceandport) rt=win32event.WaitForSingleObject (hSem, 0) if rt != win32event.WAIT_TIMEOUT: really_do_start_my_app() else: print application allready running to make sure that only ONE instance of the application is running at a time. (as it implements a local webserver, that is necessary. Two webservers listening on one port is bad) Now I am going to make this application run on Linux. How can I get similiar behaviour on Linux? I know of the .pid files that get written by some server processes ... BUT they do not get cleaned up on unclean shutdown of the application. is there some better method? Or some module which wraps the details of .pid-files quite nicely? (like trying to remove to check if other instance is still running, failing properly on missing write privs etc.) best wishes, Harald The best way I know to do it is to use fnctl.flock or fcntl.lockf functions. I never used it, so can just point you to the official documentation. The idea is that your applications should take exclusive access to one of the application files, so that if it is started a second time, the second run will find the file locked and understand that there is an instance started. AFAIK, if the process locking a files dies, the OS releases the lock, so there is no possibility of stale locks (check this!). Anyway, you could simply use your server socket as lock. It is not possible to have two processes accepting connections on the same port, the second process would receive an error 'Address already in use'. You could use it as signal that there is already an instance of the application running. This method should be available in both Windows and Linux (and various Unix flavours too), so your code would be more portable. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python sockets UDP broadcast multicast question??
On 28 Ago, 08:09, inorlando [EMAIL PROTECTED] wrote: Hi all, I have a question about python and sockets , UDP datagram in particular. I'm new to socket programming so please bare with me. I am trying to write a simple application that broadcast files to another computer on the same network/subnet but I do not want the receiver computer to have to respond, I only want it to receive the packet. So this was simple enough, but my problem is this when I send a file that is say larger then 100K the receiver is not able to keep up with the packets as they arrive. I get say 60 or so then the rest are ignored. I have tried a couple of different approaches like threading and queuing, but all ultimately have the same problem. So my question is how can I receive a continuous stream of UDP packets to some kind of buffer for processing with out losing packets? Thank you for any help or guidance that you provide. - InOrlando The UDP protocol is defined 'unreliable' because it cannot guarantee in all conditions the delivery of all packets in the correct sequence. This means than in specific conditions, e.g. when the network or one of the communicating computers is overloaded, you can loose packets or receive them in the wrong order. So, first of all, if you cannon tolerate packet loss, consider switching the protocol to TCP. If you cannot change protocol (maybe because TCP has no multicast), then try to reduce the load on the computer and the network, e.g. by inserting a delay between two packet transmissions. But remember that this only reduce, does not cancel, the possibility of packet loss or packet mis-ordering. Of course, it could be a bug in your program, in which case none of the above matters ;) Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange problem ....
Il Wed, 23 Jul 2008 01:19:48 -0700, karthikbalaguru ha scritto: Hi, I am new to python, Kindly suggest to resolve a problem with a python file. What does the below error refer to ? I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and db4-4.0.14-20. [EMAIL PROTECTED] processor]# Analyzer processorcycle /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield' will become a reserved keyword in the future Traceback (most recent call last): File /usr/local/SDK/bin/Analyzer, line 48, in ? from debuglib import ProcessorInfo File /usr/local/SDK/bin/../core/bin/processorlib.py, line 88 yield ProcessorObjectInfo(child, self.pt) ^ SyntaxError: invalid syntax Is this error related with the version of python / python-devel that i use . Yes. Generators (and thus the yield keyword) are not available in python 2.2. Any ideas / tips ? First try doing: from __future__ import generators. In __future__ package you can find the features which are to become standard in the next releases. I don't remember when the generators have been introduced but maybe you will be lucky. Otherwhise install a newer version of python. You can probably do it without replacing the one you have, but I'm not using RH and I can't thell you how. Thx in advans, Karthik Balaguru Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Threads - stopped vs. gone vs. Alive
On Wed, 28 May 2008 11:38:53 -0700, RossGK wrote: I've answered my own question about the None state - an event was setting the thread to None where I didn't expect it. However, my question slightly repositioned is if a Thread is Stopped it still seems to exist. Is there someway to make it go away, send it to garbage collection etc? You have to call the join() method of the thread object from another thread. This will terminate the thread and free its resources. This is usually the task of the parent thread which usually does something like: t = MyTread(...) t.start() # do your own stuff, then before quitting t.join() # Note that this waits until t is terminated Other part of the original Q - I assume a Stopped thread gets a false from isAlive and a Running thread gets a true? Yes. You can try yourself: import threading class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def stop(self): self._stop = True def run(self): self._stop= False while self._stop == False: import time time.sleep(0.1) t = MyThread() t.start() t.isAlive() True t.isAlive() False t.join() t.isAlive() False Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading virtual method of widget without inheriting (PyQt)
On Tue, 27 May 2008 01:31:35 -0700, Alex Gusarov wrote: Hello, I have strong .NET background with C# and want to do some familiar things from it with Python, but don't know how. For example, I created form in qt designer with QCalendarWidget, translated it into Python module and want to overload virtual method paintCell of QCalendarWidget. In C# I can write following (abstract) code: this.calendar.PaintCell += new PaintEventHandler(myPaintCellHandler); void myPaintCellHandler(object sender, PaintEventArgs e) { // some work here } I can't find how I can do similar thing in Python without inheriting QCalendarWidget and overloading this method in inherited class (it's long and I must create additional class). The only thing I done its full replacement of handler: calendar.paintCell = myPaintCell def myPaintCell(self): pass It is more a matter of the GUI toolkit you are using rather than the language. In Python, they are many, but they are not as tighty integrated with the language as in C#. Also, Python has a no standard support for event handling, but again several non-standard library (e.g. twisted ) and plus you can relatively easily cook your own recipe, has other posters have shown you. Anyway, IIRC (it's a long time since I used Qt), QT allows to connect more than one slot with the same signal, so you should not need to subclass or to create your own multi-dispatcher. Just doing: calendar.paintCell.signal( SOME_SIGNAL_NAME, my_paint_method ) should work. I don't know which signal you should connect to, however. This link gives you some detail on signal/slots in PyQT: http://www.commandprompt.com/community/pyqt/x1408 Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: finding icons for Apps
On Sat, 24 May 2008 21:42:57 -0700, Sanoski wrote: This might be a dumb question. I don't know. I'm new to all this. How do you find icons for your programs? All GUI applications have cool icons that represent various things. For instance, to save is often represented as a disk, etc. You know, the small little picture references that give meaning to the phrase 'Graphical User Interface'. But I'm not a graphics artist! Drawing is simply one talent that skipped me completely. Where can I find icons to use with my programs? Many GUI toolkit ( like wx and gtk ) have a standard stock of icons for common tasks ( load, save, ok, cancel, ...). Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib returns EOFError
On Mon, 19 May 2008 13:27:23 +0100, Jon Bowlas wrote: Hi All, I've written a little method to connect to an ftpserver which works well, however when I send a file using this ftp connection oddly I _sometimes_ get returned an EOFError from ftplib.getline even though my file is actually transferred. Here's my script: def uploadViaFtp(self, file, filename): '''A method to upload a file via ftp''' ftpserverloc = self.getItunesUftpServer() ftpserverusername = self.getItunesUftpUser() ftpserverpassword = self.getItunesUftpPsswd() ftp = ftplib.FTP(ftpserverloc) ftp.login(ftpserverusername, ftpserverpassword) try: ftp.storbinary(STOR + filename, file, 1024) finally: file.close() ftp.quit() And here's the traceback: Traceback (innermost last): Module ZPublisher.Publish, line 114, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 40, in call_object Module Products.FileSystemSite.FSPythonScript, line 108, in __call__ Module Shared.DC.Scripts.Bindings, line 311, in __call__ Module Shared.DC.Scripts.Bindings, line 348, in _bindAndExec Module Products.FileSystemSite.FSPythonScript, line 164, in _exec Module None, line 28, in upload_submit - FSPythonScript at /silva/service_views/UCLItunesUPodcast/edit/Asset/UCLItunesUTrack/upload_sub mit - Line 28 Module Products.UCLItunesUPodcast.UCLItunesUService, line 138, in uploadViaFtp Module ftplib, line 523, in quit Module ftplib, line 246, in voidcmd Module ftplib, line 221, in voidresp Module ftplib, line 207, in getresp Module ftplib, line 193, in getmultiline Module ftplib, line 183, in getline EOFError Any help in catching and ignoring this error would be greatly appreciated. Regards Jon ftp.quit() attempts to send a quit command and wait for the response before closing. Apparently, sometime the connection is already closed (don't know why) and you get the exception. I guess you could do something like this: try: ftp.quit() except EOFError: ftp.close() Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Initializing a subclass with a super object?
On Sat, 10 May 2008 18:09:02 -0700, frankdmartinez wrote: Hi, Terry. Yeah, no. If we think of the inherited B as an object nested within a1, I'm attempting to initialize that B with b1 by accessing the B, say, via a function call. I don't see how using a python factory achieves this. But there is not such a thing, in Python. What you have is that A has the same attributes/methods of B plus its own. What you could do is adding in class A a method like this: class A(B): ... def set_b_attributes(self, instance_of_b): for k, value in instance_of_b.__dict__: setattr(self, k, value ) and the use it like this: a1.set_b_attributes(b1) Of course, if b attributes are few and always the same it is more readable assigning them explicitely: def set_b_attributes(self, instance_of_b): self.attr1 = instance_of_b.attr1 self.attr2 = instance_of_b.attr2 Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: config files in python
On Mon, 05 May 2008 00:35:51 -0700, sandipm wrote: Hi, In my application, I have some configurable information which is used by different processes. currently I have stored configration in a conf.py file as name=value pairs, and I am importing conf.py file to use this variable. it works well import conf print conf.SomeVariable but if I need to change some configuration parameteres, it would need me to restart processes. I want to store this data in some conf file (txt) and would like to use it same way as I am using these variables as defined in py files. one solution I can think of is writing data as a dictionary into conf file. and then by reading data, apply eval on that data. and update local dict? but this is not a good solution any pointers? Sandip The 'simple but relatively dangerous way', already suggested, is to reload() the module. A safer way - but requiring more work - could be to build something around the Configparser module in the standard library ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine socket family at runtime
On Sun, 04 May 2008 08:49:55 -0700, Giampaolo Rodola' wrote: Hi there, since the socket.socket.family attribute has been introduced only in Python 2.5 and I need to have my application to be backward compatible with Python 2.3 and 2.4 I'd like to know how could I determine the family of a socket.socket instance which may be AF_INET or AF_INET6. Is there some kind of getsockopt() directive I could use? For now I've been able to determine the family by using: # self.socket = a connected socket.socket instance ip, port = self.socket.getsockname()[0:2] af = socket.getaddrinfo(ip, port)[0][0] ...but I'd like to know if some other solution is preferable. Thanks. --- Giampaolo http://code.google.com/p/pyftpdlib Ciao, what about wrapping the socket type and adding a 'family' attribute to the base socket class? Something like: class SocketWrapper(socket.socket): def __init__(self, family, type, proto=0): socket.socket.__init__(self, family, type, proto) self.family = family then you have just to create the sockets with SocketWrapper insetead of socket.socket. For the rest of your code it would not matter, and then you are sure to always have a .family attribute. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with listdir
On Sat, 26 Apr 2008 01:24:23 -0700, jimgardener wrote: hi i have a directory containing .pgm files of P5 type.i wanted to read the pixel values of these files ,so as a firststep i wrote code to make a list of filenames using listdir pgmdir=f:\code\python\pgmgallery # where i have pgm files g2=listdir(pgmdir) i get the following error WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'f:\\code\\python\pgmgallery/*.*' i am running python on winXP ..can anyone tell me why i get this error? Did you try using a raw string as pathname pgmdir=rf:\code\python\pgmgallery ? AFAIK, the character '\' in interpreted in Python as the beginning of an escape sequence (such as '\n') and it should be doubled ( as in the error message) or a raw string should be used, telling Python that there are no escape sequences inside. However, from the message it looks like the path as been understood as such, so this might not be the case. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: display monochromatic images wxPython
On Fri, 25 Apr 2008 14:42:17 -0700, [EMAIL PROTECTED] wrote: Dear All, I want to write a GUI program with wxPython displaying an image. But the image I have is monochromatic. When I retrieve the data from the image I end up with a list of integer. Starting from a list of integer and knowing the width and height of the image, how do I display such an image on a wx panel or frame ? I have had a look at the wxPython demo but there I see only images where the data is a list of tuple consisting of r,g ,b values. Is there are function where I directly can input the list of array and let it display the image ? Thanks in advance RR I think that RGB colors with the same amount of R,G, and B levels always result in some shade of gray. If so, you could try building your image data by convering each numver in a triplet of equal numbers. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list