Re: Attribute reference design
Le Wednesday 02 July 2008 01:17:21 Gary Herron, vous avez écrit : chamalulu wrote: On Jul 1, 11:24 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: chamalulu schrieb: Hello. I think I'm aware of how attribute access is resolved in python. When referencing a class instance attribute which is not defined in the scope of the instance, Python looks for a class attribute with the same name. (For assignment or deletion this is not the case, thankfully.) I've been trying to understand why? What is the reason behind, or practical purpose of, this design decision? Anyone, please enlighten me. How else would you resolve methods which are of course defined on the class but invoked through the instance? Yes, of course... You're right. Didn't think of that. Thank you. I'll go stand in the corner. :) No need. Also, you can define a class attribute (C++ might call it a static attribute) and access it transparently through an instance. class C: aClassAttribute = 123 def __init__(self, ...): ... c = C() ... do something with c.aClassAttribute ... Be very careful with that, as it looks like C++ or similar other OO languages, but python handles it in a strange way if you assign a value to such an attribute. It took me a long time to understand what happens here: class Foo (object) : bar = 0 foo = Foo() print '(1) Foo.bar: %d' % Foo.bar print '(1) foo.bar: %d' % foo.bar Foo.bar += 1 print '(2) Foo.bar: %d' % Foo.bar print '(2) foo.bar: %d' % foo.bar foo.bar += 1 print '(3) Foo.bar: %d' % Foo.bar print '(3) foo.bar: %d' % foo.bar here's the output: (1) Foo.bar: 0 (1) foo.bar: 0 (2) Foo.bar: 1 (2) foo.bar: 1 (3) Foo.bar: 1 # hey dude, where is my bar ? (3) foo.bar: 2 In the third case, you might expect foo.bar += 1 to just increment Foo.bar, but actually it doesn't. I first thought it was a bug, but it's not. When you write foo.bar += 1 (equivalent to foo.bar = foo.bar + 1), python first looks for a bar attribute, finds it in the class members, and then creates an instance member with the result. Things would be different with a mutable type implementing the += operator. I discovered this in a middle of a project and it was hard to track all these assignments in my code to correct them, so I'd suggest to always access class members through the class instead of the instance, unless you have no choice or know exactly what you are doing. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner's questions - manipulating text files
Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez écrit : Hi, I am a very beginner Python programmer with limited programming experience overall. I am trying to write a script that will search for the second and third appearance of the symbol '@' in a file, will read a random line between them, and write the line into a new file. So far I was only able to open the file using 'open', but I am not sure how to proceed. I tried to read it line by line using 'readline' but was not sure how to manipulate the text the way I need to. If the file you're reading is not too big, you can use file.readlines() which read all the files and returns its content as a list of lines. Could anyone please give me |a basic guidance as for what functions may be useful for my purpose? (e.g how to search for a string '@' in a text? how to identify its location? text.find('@') will return the position of the first occurence of '@', or a negative value if not found. how to choose a random number in a defined range? random.randrange(start, stop) how to read that line number from a text file? etc.)| if you read the file with readlines(), just lines[lineno] you'll find more infos in the following sections: http://docs.python.org/lib/bltin-file-objects.html http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/module-random.html -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to modify the data in a binary file?
Le Wednesday 02 July 2008 14:05:39 Jim Brown, vous avez écrit : Hi all, I'm a Python newbie, so please pardon me if my question may look a little silly. :) I want to modify a binary file p.data (which has some C-style short integers -- 16-bit integers) in such a way: The bit m and bit n of every short int si in the file are set to 1, and the left bits in si are not affected. I.e, for the first short int in the file, I think the code would be: import os f = os.open(/root/p.data, os.O_RDWR) str = os.read(f, 2) #assume the short int in str is 0x0102, and I want to change it to 0x8182 (changing bit7 and bit15 to 1). #how to change the str into a short int variable si?? ??? si = (si ~0x8080) | 0x8080 You can either do it by hand by splitting your string in chars and getting the bytes values with ord (described here: http://docs.python.org/lib/built-in-funcs.html) : byte0 = ord(s[0]) byte1 = ord(s[1]) si = (byte0 8) | byte1 # or maybe the inverse ? or use the struct module: http://docs.python.org/lib/module-struct.html -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: simple UnZip
Le Wednesday 02 July 2008 15:39:51 noydb, vous avez écrit : Can someone help me with this script, which I found posted elsewhere? I'm trying to figure out what is going on here so that I can alter it for my needs, but the lack of descriptive names is making it difficult. And, the script doesn't quite do anything worthwhile -- it unzips one file from a zipfile, not all files in a zipfile. *** import zipfile, os, sys, glob os.chdir(C:\\Temp) zips = glob.glob('*.zip') for fzip in zips: if zipfile.is_zipfile(fzip): print fzip, is a zip z = zipfile.ZipFile(fzip,'r') lstName = z.namelist() sHgt = lstName[0] print Unpacking,sHgt hgt = z.read(sHgt) fHgt = open(sHgt,'wb') fHgt.write(hgt) # fHgt.flush fHgt.close print Finished *** I changed it somewhat to import zipfile, os, sys event_zip = (C:\\Temp\\data4event.zip) z = zipfile.ZipFile(event_zip, 'r') zList = z.namelist() for zItem in zList: print Unpacking,zItem zRead = z.read(zItem) z1File = open(zItem,'wb') z1File.write(zRead) z1File.close namelist() returns a list of relative file names, so you can just put them anywhere you want with: zlFile = open(os.path.join(DESTDIR, zItem), 'wb') or change the current directory, but the first way should be preferred. print Finished This works, but I want to be able to specify a different output location. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble using pinckle
Le Wednesday 02 July 2008 16:09:07 Pierre-Alain Dorange, vous avez écrit : Hello, I'm new to python and i'm deelopping a small game with pygame. I got lot of fun with python. Trying to implement a config file to save user score and config. Reading doc and some tutorial about file handling i read about pickle, and yes it's very easy to implement. But i thought i miss something with the roots of python. I implement a Prefs class to handle config data and add it a load and save method. It works but when reading self, it OK inside the load function but outside the pref instance return to it's previus state... I don't really understand. Here's the test code : #!/usr/bin/env python import os, pickle kFileName='test.ini' class Prefs(): note that using new-style classes is recommended today: class Prefs (object) : def __init__(self): self.test=1 self.zorglub='bonjour' def load(self): if os.path.exists(kFileName): try: print 'test %d (before)' % self.test f=open(kFileName,'r') self=pickle.load(f) f.close() print 'test %d (after)' % self.test except IOError: return 1 return 0 Here self is only a local variable and its meaning is only a convention. So assigning it to a new value won't change the object itself (and is not a good idea as it may be confusing for the reader). You should either use a static method which returns a new object: class Prefs (object) : def save (self, f) : pickle.dump(self, f) @staticmethod def load (f) : return pickle.load(f) and load it with prefs = Prefs.load(filename) or store all the values in a dictionary and only pickle this object: class Prefs (object) : def __init__ (self) : self.values = { 'test': 1, ... } def save (self, f) : pickle.dump(self.values, f) def load (self, f) : self.values = pickle.load(f) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble using pinckle
I'll also try the dictionnary method. My final idea was that a dictionnary would be perhaps simple in the future to save/load as XML and a parser. XML ? What a strange idea ? Why is it so strange ? Many softs have their config in xml, and the xml.* modules are not that hard to use. It makes sense if you have a lot of config entries with nested sections. On a more global perspective, what are the best method to implement a simple config file with pyhton. Well... Python does have a couple of config-related packages, starting with the one in the stdlib. You may want to find out if any of these packages fits your needs before reinventing the wheel ? Right, ConfigParser should do the trick for simpler things. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: List Performance
Le Monday 30 June 2008 15:13:30 Larry Bates, vous avez écrit : Peter Otten wrote: Ampedesign wrote: If I happen to have a list that contains over 50,000 items, will the size of the list severely impact the performance of appending to the list? No. $ python -m timeit -n2 -sitems = [] items.append(42) 2 loops, best of 3: 0.554 usec per loop $ python -m timeit -n2 -sitems = [42]*10**6 items.append(42) 2 loops, best of 3: 0.529 usec per loop http://wiki.python.org/moin/TimeComplexity Peter Peter, So its actually faster to append to a long list than an empty one? That certainly would not have been intuitively obvious now would it? That test only demonstrates that it's faster to append to a 1 million items list than an empty one (and this on a particular platform with a particular python version). Different sizes may give different result. I guess this is because of some internal optimisations (items are probably allocated by chunks, so sometimes append() involves a realloc, sometimes not). So the only thing you should remember is that list.append() has a complexity of O(1), and thus should be considered a constant time operation for any length. Just be aware of the note: [1] = These operations rely on the Amortized part of Amortized Worst Case. Individual actions may take surprisingly long, depending on the history of the container. Also note that 5 items is a lot for a human being, not for a modern computer. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: regex help
Le Monday 30 June 2008 16:53:54 Support Desk, vous avez écrit : Hello, I am working on a web-app, that querys long distance numbers from a database of call logs. I am trying to put together a regex that matches any number that does not start with the following. Basically any number that does'nt start with: 281 713 832 or 1281 1713 1832 is long distance any, help would be appreciated. sounds like str.startswith() is enough for your needs: if not number.startswith(('281', '713', '832', ...)) : ... -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Function to import module to namespace
Le Sunday 29 June 2008 21:08:36 bvdp, vous avez écrit : Is it possible to do this from a function: import a module and append the defs in that module to an existing module/namesapce. So, in my code I have something like: # main code import mods def loadmore(n): import_module(n, mods) # end of main this will permit the addition of the the stuff in file 'n.py' to 'mods'. Assuming that foo1() is defined in newmod, I should now be able to do something like mods.foo1(). You can dynamically add objects to a module: import os os.foo = 'bar' os.foo 'bar' setattr(os, 'foo2', 'bar2') os.foo2 'bar2' and for the loading part you can use the __import__ builtin or maybe execfile (see the 'built-in functions' chapter of the library reference for more about these). -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: 2D online multiplayer framework?
Le Saturday 28 June 2008 09:49:42 George Oliver, vous avez écrit : I'm looking for a framework to support a 2D online real-time multiplayer game (rugby league football with a lo-fi pixel look). The GameProgramming page at the Python wiki had some suggestions but so far nothing looks that promising, does anyone have some recommendations? It would be ideal to play this through a web browser but I don't know if that's practical. This aspect of programming is pretty new to me so I'm not sure if I should start with something general like Twisted or if there's a different path I should take. There is Allegro, a (very good and easy to use) game development library which has some python bindings (afaik it is not finished but usable): http://pyallegro.sourceforge.net/ (the allegro website is here: http://alleg.sourceforge.net/ ) or SDL, another good one with the same purpose: http://www.libsdl.org/ http://www.pygame.org/news.html both are (imho) very good and easy to learn, but they are C libraries so some knowledge of this language might help you to understand them. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Use of the is statement
Le Friday 27 June 2008 16:51:07 Joel Corbin, vous avez écrit : Hello, I'm trying to clarify what exactly the behaviour of the is statement is (or should be). Naturally, this has been nearly impossible to google for, even using quotations... try this one: http://www.google.com/search?hl=enq=python+identitybtnG=Google+Searchaq=-1oq= or this one if you still don't get it :) http://en.wikipedia.org/wiki/Image:MagrittePipe.jpg This became a problem when I was using file.tell() and again when using a custom function. If I am using is in the wrong context, what is the right one? What problems did you have exactly ? -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: extend getattr()
Le Thursday 26 June 2008 13:06:53 Rotlaus, vous avez écrit : Hello, lets assume i have some classes: class A(object): def __init__(self): b = B() class B(object): def __init__(self): c = C() note you're just defining some local variables here, should be self.b = B() and self.c = C(). class C(object): def __init__(self): pass and now i wanna do something like this: a=A() c=getattr(a, 'b.c') I know this doesn't work, but what can i do to get this or a similar functionality to get it work for this sample and for even more nested classes? You could do it manually: c = getattr(getattr(a, 'b'), 'c') or make it automatic: def get_dotted_attr (obj, dotted_attr) : for attr in dotted_attr.split('.') : obj = getattr(obj, attr) return obj a = A() print 'a.b.c = %s' % get_dotted_attr(a, 'b.c') -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Making code more efficient and effective
Le Thursday 26 June 2008 14:11:35 [EMAIL PROTECTED], vous avez écrit : I've written up a little piece of code that isn't that foolproof to scan through a file (java presently) to find functions and then look for them throughout the document and output the name of the function, followed by how many times it appears and the lines it appears on. What I was looking for was ways to improve, simplfy and beautify the code. More to aid my learning of Python than produce a perfect way to scan for this (netbeans was annoying me...which is why I did this) Anyway, the source code: I would use some regexp instead (assuming that the function prototype is on a single line and that the return type of the function is a single identifier, I don't remember if it's always the case in Java) PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+) [ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$') for line in source_file : if PAT.match(line) : func_vis = PAT.sub(r'\1', line) func_type = PAT.sub(r'\2', line) func_name = PAT.sub(r'\3', line) func_args = PAT.sub(r'\4', line) print '%s' - '%s' '%s' '%s' '%s' % (line, func_vis, func_type, func_name, func_args) It might be hard to read but will avoid a lot of obscure parsing code. I can't tell if it makes the code more efficient but you don't care about that unless you're parsing several million lines of code. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: ask for a RE pattern to match TABLE in html
Le Thursday 26 June 2008 15:53:06 oyster, vous avez écrit : that is, there is no TABLE tag between a TABLE, for example table something with out table tag/table what is the RE pattern? thanks the following is not right table.*?[^table]*?/table The construct [abc] does not match a whole word but only one char, so [^table] means any char which is not t, a, b, l or e. Anyway the inside table word won't match your pattern, as there are '' and '' in it, and these chars have to be escaped when used as simple text. So this should work: re.compile(r'table(|[ ].*).*/table') ^ this is to avoid matching a tag name starting with table (like table_ext) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: ConfigParser: Can I read(ConfigParser.get()) a configuration file and use it to call a funciton?
Le Thursday 26 June 2008 16:41:27 [EMAIL PROTECTED], vous avez écrit : Hello. I am a novice programmer and have a question I have a configuration file(configuration.cfg) I read this from reading.py using ConfigParser When I use ConfigParser.get() function, it returns a string. I want to call a function that has the same name as the string from the configuration file. You can find the function in the global dictionary (returned by globals()): globs = globals() func_name = config.read('1234', 'function') func = globs[func_name] # and then call it func() But a safer way would be to use a class with some static methods: class Functions (object) : @staticmethod def efgh () : blah blah... and then find the function in the class dict: func = getattr(Functions, func_name) func() this way you can restrict the set of functions the user can give, excluding those which are not supposed to be called this way. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: newb question on strings
Le Tuesday 24 June 2008 22:27:33 regex_jedi, vous avez écrit : ok, I have looked a lot of places, and can't seem to get a clear answer... I have a string called each_theme Some values of the string may contain a single quote as in - Happy Sad Nice Frank's Laundry Explosion Notice that the 4th value has a single quote in it. Well, I need to make sure that the single quote is escaped before handing it off for further processing to a class I later call for some other processing. So I thought, no big deal, I should be able to find a way to escape the single quote on the string. I am a perl and PHP guy, so I do a lot of regex stuff. I did a quick search and found someone had said to use this re.sub function, so I tried. But the following doesn't work. To be honest, I am a little lost with all the modules and classes required to do simple math or string functions in Python. None of it seems built it in.. its all import modules... Here is what I am trying... # escape single quotes in theme name re.sub('''(['])''', r'\\\1', each_theme) No python has no builtin support for regexp like perl. There's nothing wrong with your code, you just need to import the 're' module. Add this at the beginning of your script: import re But imho escaping the quote in the first part would be more readable than using triple quotes: name = Frank's Laundry re.sub(r([\']), r\\\1, name) Frank\\'s Laundry You'll find a list of all the standard modules in the python docs, including this one: http://docs.python.org/modindex.html http://docs.python.org/lib/module-re.html -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from list with paths
Le Wednesday 25 June 2008 20:59:38 antar2, vous avez écrit : Hello, I would like to read and print files, of which the complete filepaths are mentioned in another textfile. In this textfile (list.txt) are for example the following paths: /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_1LG_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/ S01C001M1_1LGPseudo_f01.TextGrid /data/chorec/chorec-nieuw/s01/S01C001M1/S01C001M1_AVI1_f01.TextGrid I know how to open and read one file in my current directory, but after trying to find this out my self, I give up... I already got one answer for this question, but it did not work What's the problem exactly ? If you already know how to read a file you have all what you need: f_list = open('list.txt') for filename in f_list : f = open(filename) print f.read() f.close() f_list.close() If you get an error, please post the full error message with the backtrace. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two dates
Le Tuesday 24 June 2008 12:11:03 [EMAIL PROTECTED], vous avez écrit : Hi! I am new in Python, so I count for your help. I need to get difference in months between two dates. How to do it in python? I am substracting two dates, for example date1 - date2 and I got result in days, how to change it? Maybe the datetime and calendar modules may help too, but a simple solution is to get your dates in number of months (tm1 and tm2 being struct_time objects returned by time.localtime/gmtime) : m1 = tm1.tm_year * 12 + (tm1.tm_mon - 1) m2 = tm2.tm_year * 12 + (tm2.tm_mon - 1) then (m1 - m2) gives the difference in months (see the time modules docs for more infos) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: sending executable data over network..
Le Tuesday 24 June 2008 08:59:40 Piyush Anonymous, vous avez écrit : hi, i wish to change the way the function definition at run time in a running server. new function code which is to be executed is provided by a client at different location. i am getting it by reading a file and sending it using makefile() with server/client connected using sockets. how can make the lines received in a string array as new function definition? or should i receive it in a different way? is there any better way to do the entire thing? One way is to transmit the code as a string and compile it on server-side with the 'compile' builtin function. Another is to compile it on client-side and transmit the resulting code object with the marshal module but there are many restrictions on it (specially the fact that the client and server will have to run the same python version) so carefully read the docs first. I'd choose the first solution, eventually using the pickle module to avoid encoding problems. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Distutils and unit test files
Le Monday 23 June 2008 15:38:40 Joe Riopel, vous avez écrit : Hi, I am using Distutils to build and distribute some packages. I do write unit tests, but I am confused as to where to put them and how to run them prior to the package being installed (The modules being tested would not be in my sys.path). I would rather not put the test cases in the same files as the modules being tested, I want keep them in a sub directory of the module, or in a separate test directory. What are some of the strategies for dealing with this? Yes a checksuite should be kept separate from the 'real' code. You can run it locally by setting the PYTHONPATH environment variable : PYTHONPATH=/path/to/your/modules python checksuite.py -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Distutils and unit test files
On Mon, Jun 23, 2008 at 9:59 AM, Cédric Lucantis [EMAIL PROTECTED] wrote: Yes a checksuite should be kept separate from the 'real' code. You can run it locally by setting the PYTHONPATH environment variable : PYTHONPATH=/path/to/your/modules python checksuite.py So I could also just append the path to sys.path in checksuite.py file and use checksuite to run all my unit tests? (woops, sorry for the private post :) Yes this is equivalent, as sys.path is initialized from PYTHONPATH at startup. But I'd suggest to insert your path at the beginning of sys.path rather than appending it, so you'll be sure to use the local modules even if they are already installed (I use 1 instead of 0 because sys.path[0] has a special meaning) : sys.path.insert(1, '/path/...') But I prefer to use PYTHONPATH, so the user keeps control on it (and can eventually check installed modules too). If you don't want to have to set it at each run, you can still write a simple wrapper script for your own needs. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Find class attributes creation order
Le Monday 23 June 2008 17:53:07 Marcob, vous avez écrit : Let's see these simple classes: class base_foo() pass class foo(base_foo): a=1 b={} c=zz I would like to find class foo attributes creation order. Using __metaclass__ is not of help because special method __new__ receive attrs as a dictionary and so the order isn't preserved. Any other idea? I don't really understand what you want, but __new__ may accept any kind of attributes, this is your choice. You can use named params or a vararg list (which will preserve params order). But in your example you're only using class attributes, so __new__ is not involved and they are just created once for all in the order you write them: a, b, c. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to Learn Packages
Le Sunday 22 June 2008 16:07:37 Saul Spatz, vous avez écrit : Hi, I'm making a project into my first package, mainly for organization, but also to learn how to do it. I have a number of data files, both experimental results and PNG files. My project is organized as a root directory, with two subdirectories, src and data, and directory trees below them. I put the root directory in my pythonpath, and I've no trouble accessing the modules, but for the data, I'm giving relative paths, that depend on the current working directory. This has obvious drawbacks, and hard-coding a directory path is worse. Where the data files are numbers, I can simply incorporate them in python scripts that initialize data structures , but what can I do with the image files? For a small project you can do the same with images or any kind of data, for instance by serializing your objects with pickle in ascii mode and putting the result in a string constant (well, I never did it and can't guarantee it will work, this is only an example of what people do in many situations) What is the usual way of dealing with this? A more conventional way is to provide a configure script to run before compiling/installing. That script should let the user choose where to install datafiles with a command line option such as --datadir=/path or provide a reasonable default value. Then it will auto-generate some code defining this value as a global variable, to make it accessible to the rest of your own code. Ideally, your app would also provide a command line option or an environment variable to override this hard-coded setting at runtime. But maybe the distutils tools have some features for this, I don't know enough of them to tell that. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Way to unblock sys.stdin.readline() call
Le Saturday 21 June 2008 15:26:53 joamag, vous avez écrit : HI, Is there any possible way to unblock the sys.stdin.readline() call from a different thread. Something like sys.stdin.write() but that would actually work ... something to put characters in the stdin... Do you mean setting stdin in non-blocking mode ? On unix you can do it with the fcntl module (you'll find more infos in the libc docs) : fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK) and catch IOErrors with errno = EAGAIN. But I don't know how to do it in a portable way, suggestions welcome :) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple wxPython SetLabel question
Le Thursday 19 June 2008 11:48:54 dp_pearce, vous avez écrit : Hi All, Apologies if this should be seriously obvious. But I am quite new to Python and it is not quite so obvious yet. I have a GUI which will eventually load and display database information. I want the user to be able to browse for a database and then load it. My problem relates to how I set the value of a TextCtrl once the user has selected the database they wish to load. Here is a snip of my code: import wx import os class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, Code Snip) panel = wx.Panel(self) databaseLbl = wx.StaticText(panel, -1, Database:) database= wx.TextCtrl(panel, -1, ) databaseBtn = wx.Button(panel, -1, Browse) self.Bind(wx.EVT_BUTTON, self.OnBrowse, databaseBtn) fetchSizer = wx.BoxSizer(wx.HORIZONTAL) fetchSizer.Add(databaseLbl) fetchSizer.Add(database, -1, wx.LEFT |wx.RIGHT, 5) fetchSizer.Add(databaseBtn) panel.SetSizer(fetchSizer) def OnBrowse(self, event): wildcard = Access Database (*.mdb) | *.mdb | Access Database (*.MDB) | *.MDB | All Files (*.*) | *.* dialog = wx.FileDialog(None, Choose an database, os.getcwd(), , wildcard, wx.OPEN) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() # # NOW SET TEXTCTRL database TO path panel.database.SetLabel(path) # dialog.Destroy() app = wx.PySimpleApp() TestFrame().Show() app.MainLoop() The current code returns that global name 'panel' is not defined 'panel' is local to your __init__ function, so it's not available elsewhere. You should store it as an instance attribute instead : # in __init__: self.panel = wx.Panel(self) # in OnBrowse self.panel.database.SetLabel(patrh) note that unlike some other languages, panel and self.panel are two distinct variables, so you should replace _all_ references to panel by self.panel. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe application add-ons
Le Thursday 19 June 2008 13:00:32 Alex Gusarov, vous avez écrit : Hello, I've met a problem - I want my program working without Python installation but I have some add-on mechanism (add-ons represented by separate .py files, and application auto-recognize such files on start). So, if I will using py2exe for main program and separate .py files for add-ons, will I need Python installation on client machine? Maybe other ways exist for such tasks? I guess you're reading these addons with the exec or execfile builtins ? I don't really know py2exe but I bet it can handle it without problem. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python class questions
Le Thursday 19 June 2008 13:54:03 John Dann, vous avez écrit : A Python newbie, but some basic understanding of how classes, objects etc work in eg VB.Net. However, I'm struggling a little to translate this knowledge into the Python context. Maybe I could provide some outline code as an illustration: Let's say I define the class in a module called comms.py. The class isn't really going to inherit from any other class (except presumably in the most primitive base-class sense, which is presumably automatic and implicit in using the class keyword). No it's not :) It is recommended to always use new-style classes, and thus to give the object base explicitely : class serial_link (object) : ... see http://docs.python.org/ref/node33.html print serlink.openPort You just forgot the (), so you're printing the method object itself without calling it : print serlink.openPort() -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python class questions
Le Thursday 19 June 2008 15:13:39 John Dann, vous avez écrit : Many thanks for the speedy replies. On Thu, 19 Jun 2008 14:14:02 +0200, Cédric Lucantis [EMAIL PROTECTED] wrote: Le Thursday 19 June 2008 13:54:03 John Dann, vous avez écrit : Let's say I define the class in a module called comms.py. The class isn't really going to inherit from any other class (except presumably in the most primitive base-class sense, which is presumably automatic and implicit in using the class keyword). No it's not :) It is recommended to always use new-style classes, and thus to give the object base explicitely : class serial_link (object) : ... Can I just confirm: between the parentheses should be the literal 'object' - ie (object) - you're not just using 'object' as a placeholder where there should be a more specific class name or object? Right. 'object' is a builtin python class, used as a base for all classes as in many OO languages. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert string to array of floats
Le Thursday 19 June 2008 17:12:08 Jonno, vous avez écrit : Hi, I'm very new to programming and python. I need to convert a string like this: ' 0.906366 2.276152 0.01336980.773141 0.002836 -107.335197 0.01146286.846290\n' to an array of floats. string = '0.906366 2.276152 0.01336980.773141' array = [float(s) for s in string.split()] -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing Python 3.0 no probs running 2.5 at the same time?
Le Thursday 19 June 2008 17:32:10 cirfu, vous avez écrit : Can I install 3.0 without breaking 2.5? Meaning does it overwrite some bindings or something or it just installs 3.0 in a different folder as a completely separate program? It's OK for any version having different major/minor version numbers (so 2.4 + 2.5 is OK, but _not_ 2.4.2 + 2.4.4). Everything go in different directories, and a version specific executable is also installed (python2.5, python3.0...). The main one (python) is just a link to one of them. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Python to run Python Scripts in cygwin
Le Thursday 19 June 2008 18:14:03 Calvin Cheng, vous avez écrit : Hi guys, This may be a cygwin issue but I was hoping to get some answers here as well if someone has fixed this problem before. Basically, I am able to run python scriptname.py python files in command prompt. Unfortunately, I can't seem to get it to work in cygwin. I always get an error that says: python: can't open file 'scriptname.py': [Errno 2] No such file or directory I don't think this is a python problem. Unlike dos, unix (and cygwin) dont look for executables in the current dir by default. Do you correctly type './yourscript.py' rather than 'yourcript.py' ? If it doesn't help it might be an end-line problem : python doesn't care about them, but the shebang line is parsed by cygwin and should match the end-line style you've chosen at cygwin installation time. (See http://en.wikipedia.org/wiki/Newline#Common_problems) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to split a string containing nested commas-separated substrings
Hi, Le Wednesday 18 June 2008 19:19:57 Robert Dodier, vous avez écrit : Hello, I'd like to split a string by commas, but only at the top level so to speak. An element can be a comma-less substring, or a quoted string, or a substring which looks like a function call. If some element contains commas, I don't want to split it. Examples: 'foo, bar, baz' = 'foo' 'bar' 'baz' 'foo, bar, baz, blurf' = 'foo' 'bar, baz' 'blurf' 'foo, bar(baz, blurf), mumble' = 'foo' 'bar(baz, blurf)' 'mumble' Can someone suggest a suitable regular expression or other method to split such strings? I'd do something like this (note that it doesn't check for quote/parenthesis mismatch and removes _all_ the quotes) : def mysplit (string) : pardepth = 0 quote = False ret = [''] for car in string : if car == '(' : pardepth += 1 elif car == ')' : pardepth -= 1 elif car in ('', ') : quote = not quote car = '' # just if you don't want to keep the quotes if car in ', ' and not (pardepth or quote) : if ret[-1] != '' : ret.append('') else : ret[-1] += car return ret # test for s in ('foo, bar, baz', 'foo, bar, baz, blurf', 'foo, bar(baz, blurf), mumble') : print '%s' = '%s' % (s, mysplit(s)) # result 'foo, bar, baz' = '['foo', 'bar', 'baz']' 'foo, bar, baz, blurf' = '['foo', 'bar, baz', 'blurf']' 'foo, bar(baz, blurf), mumble' = '['foo', 'bar(baz, blurf)', 'mumble']' -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
Hi, Le Wednesday 18 June 2008 20:19:12 [EMAIL PROTECTED], vous avez écrit : Hi. I am looking for a way to check if some given set of (*args, **kwds) conforms to the argument specification of a given function, without calling that function. For example, given the function foo: def foo(a, b, c): pass and some tuple args and some dict kwds, is there a way to tell if i _could_ call foo(*args, **kwds) without getting an exception for those arguments? I am hoping there is a way to do this without actually writing out the argument logic python uses. Each function object is associated to a code object which you can get with foo.func_code. Two of this object's attributes will help you: co_argcount and co_varnames. The first is the number of arguments of the function, and the second a list of all the local variables names, including the arguments (which are always the first items of the list). When some arguments have default values, they are stored in foo.func_defaults (and these arguments are always after non-default args in the co_argnames list). Finally, it seems that some flags are set in code.co_flags if the function accepts varargs like *args, **kwargs, but I don't know where these are defined. Note that I never found any doc about that and merely guessed it by playing with func objects, so consider all this possibly wrong or subject to change. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Hi, Greetings. The strip() method of strings works from both ends towards the middle. Is there a simple, built-in way to remove several characters from a string no matter their location? (besides .replace() ;) For example: .strip -- 'www.example.com'.strip('cmowz.') 'example' .??? -- --- 'www.example.com'.strip('cmowz.') 'exaple' -- I don't see any string method to do that, but you can use a regexp : re.sub('[cmowz.]', '', 'www.example.com') 'exaple' -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: NoneType Error
Hi, Le Sunday 15 June 2008 10:35:18 Maryam Saeedi, vous avez écrit : I am using a python program on a lot of different documents and for few of them I will get NoneType error. I just want to skip those files and continue for others, I do this without a problem for IndexError,TypeError,ValueError,NameError : try: except (IndexError,TypeError,ValueError,NameError): but when I add NoneType it gives the following error: except (NoneType,IndexError,TypeError,ValueError,NameError): NameError: name 'NoneType' is not defined and if I do not use the NoneType then it does not go through either and stops the program when I get to such a file. Is there another name that captures this error? Thanks for your help, Maryam you can get the none type with None.__class__ or with the 'types' module, but it won't work as the except handler only accepts Exception classes. It sounds like you're confusing with some other error, what is the exact message of your 'NoneType error' ? The exception type you want to catch should be at the beginning of it (as in 'TypeError: blah blah...') -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with Py_BuildValue
Hi, Hi, currently I have a problem understanding Py_BuildValue. I have this code: static PyObject *function(PyObject *self, PyObject *args) { PyObject * python_return_value = NULL; PyObject * dummy = NULL; double * internal_list; snip and forget the rest /* converting to python representation */ for (i=0; i limit; i++) { dummy = Py_BuildValue(d, internal_list[i]); if (!dummy) return NULL; PyList_Append(python_return_value, dummy); Py_DECREF(dummy); dummy = NULL; } return python_return_value } This doesn't work. What I see, when invoking the function function() in Python is a list of refcounts, like: [refcnt 0 at 0x94a29d4, refcnt 0 at 0x94a29e4, ...]. However, if I change the Py_BuildValue-line to be dummy = Py_BuildValue(i, (int)internal_list[i]); I do get the 'right' integer return values. Point is that I really would like to work with Python-floats afterwards. Any idea where a pitfall might be here? I see nothing wrong with your code so I'd say it is somewhere else (did you snip any code between the end of the loop and the return?). I've never seen those 'refcnt' objects but a refcount of 0 sounds like you unrefed your objects one extra time by mistake. This would produce a segfault on unix, but maybe not on all platforms ? You should check the return value of PyList_Append() and if it doesn't help trace the content of your list after each iteration to see when the bad things happen (you can check the reference count of an object with obj-ob_refcnt). Finally note that in your case it would be much simpler and more efficient to use the float constructor directly: dummy = PyFloat_FromDouble(internal_list([i])) PS: always use Py_CLEAR(dummy) instead of Py_DECREF(dummy); dummy=NULL; (though it doesn't really matter in this simple case - see http://docs.python.org/api/countingRefs.html) -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with Py_BuildValue
Thank you. At least I can exclude another few error sources, now. I see nothing wrong with your code so I'd say it is somewhere else (did you snip any code between the end of the loop and the return?). No. (Apart from freeing allocated memory.) I'm pretty sure we'll find something interesting here :) and if it doesn't help trace the content of your list after each iteration to see when the bad things happen (you can check the reference count of an object with obj-ob_refcnt). Seems ok. What I did to check this was placing this after building the list: for (i=0; i limit; i++) { dummy = PyList_GetItem(python_return_value, i); printf(%f\n, PyFloat_AsDouble(dummy)); Py_CLEAR(dummy); } PyList_GetItem returns a borrowed reference so you shoud _not_ unref it (this explains the refcnt -1 I think) Here's the code producing your message (from Objects/object.c in the python sources) : /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { snip if (op-ob_refcnt = 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ fprintf(fp, refcnt %ld at %p, (long)op-ob_refcnt, op); } snip } I don't really understand its purpose, but it confirms that it's a ref count problem. Maybe the full source of your function could help ? -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: randrange loops
Le Sunday 15 June 2008 20:23:56 [EMAIL PROTECTED], vous avez écrit : Hi, I've created a method where the script defines twenty variables and several of them should be random having a maximum and a minimum value. What I did was this: from random import randrange as rr, random self.tr2_vezes = self.rr(self.d_tr2_vezes[0],self.d_tr2_vezes[-1], 1) # just an example, others are similar self.rr ? is it a typo or some method you defined yourself ? The minimum and maximum limits are never lower than -50 and higher than 250 and are integer. Many times, not always, the problem is that the script just loops forever and no value is chosen for the variable. What's happening here? What am I doing wrong? as it's very unlikely to be a bug in the randrange function I'd say something is wrong with your script but we'll need more infos to help. Can you post the whole function ? -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError with date class
Hi, Le Friday 13 June 2008 15:24:31 Dummy Pythonese Luser, vous avez écrit : Greetings *.*: The following program caused an error and puzzled me to no end. Any help immensely appreciated. class Second(First): def __init__(self, datestr): y = int(datestr[0:4]) m = int(datestr[4:6]) d = int(datestr[6:8]) First.__init__(self, y, m, d) # a = Second(20060201) # TypeError: function takes exactly 3 arguments (1 given) # Why? probably because date is an immutable type, so the init stuff is done in __new__ and not __init__ (and thus __new__ expects the same args as __init__). So you should replace First and Second __init__ methods by something like this : def __new__ (cls, datestr): y = int(datestr[0:4]) m = int(datestr[4:6]) d = int(datestr[6:8]) self = date.__new__(cls, y, m, d) return self The general rule is to do your initialization in __new__ for immutable types and in __init__ for mutable ones. See the chapter 3 of the reference manual (data model) for more infos. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Socket programming
Hi, Le Friday 13 June 2008 18:29:06 srinivasan srinivas, vous avez écrit : Hi, I am going to do some socket related programming in Python. Before that, I wish to know the Gotchas of Python Scoket Programming. Can anyone send me any link that satisfies my needs?? Yes, the friendly manual :) http://docs.python.org/lib/module-socket.html and if you want to know more about socket themselves, the gnu libc info page is a good starting point as the python module is basically an interface to it: http://www.gnu.org/software/libc/manual/html_node/Sockets.html#Sockets -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Problem with Tkinter.PhotoImage
Hi, I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. I tried png, jpg, bmp and xpm and always got this errors : img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm') Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/lib-tk/Tkinter.py, line 3206, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File /usr/lib/python2.4/lib-tk/Tkinter.py, line 3162, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize data in image file /home/omer/fgfs/fgsync/map.xpm (or _tkinter.TclError: format error in bitmap data with BitmapImage) I also tried the imageview demo with the bitmaps in Demo/tix/bitmaps and same result (only works with tix.gif). Sounds weird that tkinter only supports a non-free format... Am I lacking some packages or config ? I'm on a debian sid and have the following python packages installed : libboost-python1.34.1 python python-central python-doc python-imaging python-imaging-tk python-minimal python-mode python-newt python-selinux python-semanage python-support python-tk python2.4 python2.4-doc python2.4-minimal thanks, -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list