[ANN] BleachBit 0.3.1
BleachBit is a Internet history, locale, registry, privacy, and temporary file cleaner for Linux on Python v2.4 - v2.6. Notable changes for 0.3.1: * Clean the cache and temporary files of Acrobat Reader, GIMP, Google Earth, Second Life Viewer, and winetricks. * Clean Firefox version 3's URL history without deleting the entire places.sqlite file (which also contains bookmarks). * Clean more localizations. * Vacuum the Firefox databases (which becomes fragmented). * Fixed bug that blocked cleaning of some localizations for some using Ubuntu 8.04. * Fixed bug that prevented starting BleachBit when the language was not set. * Fixed bug that prevented cleaning of the clipboard. Release notes http://bleachbit.blogspot.com/2009/02/bleachbit-031-released.html Download http://bleachbit.sourceforge.net/download.php -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Good or bad use of __repr__?
Alaric Haag a écrit : Hello, Is the use of __repr__ below a really bad idea? I'd probably do the same as Stephen Hansen (Dimension(size=50)) or at least something quite similar. Now on a totally unrelated point (micro optimization anyone ?): class Dimension(): def __init__(self, setp, name): ptr = setp.contents.dim while ptr.contents.name != name: ptr = ptr.contents.next self.name = ptr.contents.name self.size = ptr.contents.size self.unlimited = bool(ptr.contents.unlimited) self.coord = ptr.contents.coord In the above code, you're constantly refering to ptr.contents, and never use ptr directly. Attribute lookup is not free, so it's better to avoid them. Local bindings lookup, OTHO, is quite fast. IOW, this would better be written as: def __init__(self, setp, name): contents = setp.contents.dim while contents.name != name: contents = contents.next self.name = contents.name self.size = contents.size self.unlimited = bool(contents.unlimited) self.coord = contents.coord -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Gabriel Genellina a écrit : En Mon, 02 Feb 2009 19:51:11 -0200, Russ P. russ.paie...@gmail.com escribió: Suppose a library developer (or a module developer on a large team) uses leading underscores. Now suppose that, for whatever reason (pressure from the users, perhaps), the library developer decides to change a private attribute to public. Now all occurrences of the identifier need to be changed. If an assignment to the previously private attribute is missed, no warning will be issued (because Python allows new attributes to be added anywhere, even completely outside the class definition itself). And if the library is widely used, the probability of such bugs occurring is very high. So _foo becomes foo. Then: class X(object): def get_foo(self): return self._foo def set_foo(self, value): self._foo = value foo = property(get_foo, set_foo) FWIW, if there's no other need for the property, I'd do it the other way round : directly make foo a plain attribute, and add a _foo property whose accessors would raise a deprecation warning. Then there's no chance I miss a an assignement to _foo !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
thmpsn@gmail.com a écrit : On Feb 3, 1:14 am, David Cournapeau courn...@gmail.com wrote: (snip) after all, we have used FILE* for years and I have no idea about the FILE structure. Your lack of knowledge about it doesn't mean that it has somehow magically private members. The only reason that most of us don't know what a FILE is is that it's definition is implementation-defined (i.e., every compiler may define it differently). That doesn't have anything to do with private members. For example, on my system, stdio.h defines FILE as: struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; }; Didn't you notice kind of a pattern here ? typedef struct _iobuf FILE; Given this information, nothing prevents me from writing things like: FILE* fp = fopen(file.txt, r); if (!fp) { /* do something */ } printf(fp-_cnt = %d\n, fp-cnt); printf(fp-_flag = %d\n, fp-_flag); printf(fp-_file = %d\n, fp-_file); fp-_flag = 0x20; // OOPS!! Indeed - and that's exactly the point : nothing prevents you from accessing the implementation, *and yet, you don't* - unless of course you have a very strong reason to do so for a very specific corner case *and* you pretty well know what you're doing *and* you accept the implications. -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Russ P. a écrit : On Feb 3, 4:14 pm, Rhodri James rho...@wildebst.demon.co.uk wrote: On Tue, 03 Feb 2009 05:37:57 -, Russ P. russ.paie...@gmail.com wrote: (snip) If a library developer releases the source code of a library, any user can trivially defeat the access restrictions. But if a team of developers is checking in code for a project, the leader(s) of the project can insist that the access restrictions be respected to simplify the management of interfaces. The larger the team, the more useful that can be. That's why Java, C++, Ada, Scala, and other languages have a private keyword. Indeed he can. He can even do that in Python; it just requires a little self-discipline from the team, or a validation script on the code repository if he really doesn't trust them. Not only can this be done without forcing the rest of the world to play, it makes things a little less daunting when those nice clean interfaces turn out to be incomplete/too slow/not what you thought. This has already been refuted several times on this thread alone, s/refuted/debated/ -- http://mail.python.org/mailman/listinfo/python-list
subprocess.Popen - file like object from stdout=PIPE
Hi, using e.g. import subprocess Package='app-arch/lzma-utils' EQ=subprocess.Popen(['/usr/bin/equery','depends',Package],stdout=subprocess.PIPE) EQ_output= EQ.communicate()[0] EQ_output is a string containing multiple lines. I'd prefer a file-like object, e.g. EQ_OUT so that I can loop over the lines of it like for line in EQ_OUT : ... I could use StringIO.StringIO applied to EQ_output but this reads all of the command's output into a big string first. On Unix/Linux a pipe is a file-like object after all, so how to get hold of it. Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i add body to 'email.mime.multipart.MIMEMultipart' instance?
On Feb 4, 2:50 pm, srinivasan srinivas sri_anna...@yahoo.co.in wrote: Hi, Could someone tell me the way to add body content to 'email.mime.multipart.MIMEMultipart' instance? Thanks, Srini excerpt from one of the modules I use: def build_body(html, text=''): text = text.strip() and text or html2text(html).encode('ascii', 'xmlcharrefreplace') body = MIMEMultipart('alternative') body.attach(MIMEText(text)) body.attach(MIMEText(html, 'html')) return body HTH Justin -- http://mail.python.org/mailman/listinfo/python-list
Load / Reload module
Hi, First I must state that I'm a beginner in Python, so all help would be more than welcomed. I want do declare some classes (classes.py) in an external editor, than import the file and use the classes. After I change the file, I want to reload the definitions w/o leaving the interactive interpreter. So far I have tried - import classes # doesn't import my classes - from classes import * # imports, but I can't reload - reload(classes) # I have the same class definition after this I've tried the documentation but I got lost, so please help. Thanks, Marius -- http://mail.python.org/mailman/listinfo/python-list
Re: Code critique xmlrpclib
flagg ianand0...@gmail.com wrote: On Feb 3, 7:32?am, Nick Craig-Wood n...@craig-wood.com wrote: flagg ianand0...@gmail.com wrote: ?This xmlrpc server is designed to parse dns zone files and then ?perform various actions on said files. \ ?It uses dnspython, and xmlrpclib ? I'd like to know what some of the more experienced python users ?think. Where I could improve code, make it more efficient, whatever. ?All suggestions are welcome. ?This is my first functional python ?program, ?and I have tons of questions to go along with whatever ?suggestions. ? How could I do sanity checking; right now nothing ?checks the input to these functions, error-handling in this program is ?almost non-existant how do you integrate decent error handling into a ?piece of software..ill shut up now. I made a few comments, some about error handling! ?See below ?import dns.zone ?from time import localtime, strftime, time ?import os, sys ?from dns.rdataclass import * ?from dns.rdatatype import * ?from string import Template ?import xmlrpclib ?from SimpleXMLRPCServer import SimpleXMLRPCServer ?from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler ?zoneDir = /dns ?def openZoneFile(zoneFile): ? ? ? ? ? ?Opens a zone file. ?Then reads in zone file to dnspython zone ?object. ? ? ? ? ? ?global zone ? ? ?global host ? ? ?global domain ? ? ?domain = ..join(zoneFile.split('.')[1:]) ? ? ?host = ..join(zoneFile.split('.')[:1]) ? ? ?try: ? ? ? ? ? ? ?zone = dns.zone.from_file(zoneDir + domain + '.zone', ?domain) ? ? ?except dns.exception, e: ? ? ? ? ? ? ?print e.__class__, e Don't use global variables! This function should probably return 3 things ? ? return zone, host, domain And whenever you use it, say ? ? zone, host, domain = openZoneFile(xxx) It should probably be a method of DNSFunctions. ?I'd avoid setting self.zone etc as that is making a different sort of global data which I'd avoid too. Also if the dns.zone.from_file didn't work (raises dns.exception) you set the host and domain but the zone is left at its previous value which probably isn't what you wanted. ?I'd let the error propagate which I think will do something sensible for the xmlrpc. ?class DNSFunctions: ? ? ? # Not exposed to xml-rpc calls, used internally only. ? ? ?def _writeToZoneFile(self, record): ? ? ? ? ? ? ? ? ? ?Checks if zone file exists, if it does it write values to zone ?file ? ? ? ? ? ? ? ? ? ?for (name, ttl, rdata) in zone.iterate_rdatas(SOA): ? ? ? ? ? ? ?new_serial = int(strftime('%Y%m%d00', localtime(time( ? ? ? ? ? ? ?if new_serial = rdata.serial: ? ? ? ? ? ? ? ? ?new_serial = rdata.serial + 1 ? ? ? ? ? ? ?rdata.serial = new_serial ? ? ? ? ?if os.path.exists(zoneDir + str(zone.origin) + zone): ? ? ? ? ? ? ?f = open(zoneDir + str(zone.origin) + zone, w) ? ? ? ? ? ? ?zone.to_file(f) ? ? ? ? ? ? ?f.close() ? ? ? ? ?else: ? ? ? ? ? ? ?print Zone: + zone.origin + does not exist, please ?add first This should probably be raising an exception to be caught or propagated back to the client via xmlrpc. ? ? ?def showRecord(self, record): ? ? ? ? ? ? ? ? ? ?Shows a record for a given zone. Prints out ? ? ? ? ?TTL, IN, Record Type, IP ? ? ? ? ? ? ? ? ? ?openZoneFile(record) ? ? ? ? ?try: ? ? ? ? ? ? ?rdataset = zone.get_node(host) ? ? ? ? ? ? ?for rdata in rdataset: ? ? ? ? ? ? ? ? ?return str(rdata) ? ? ? ? ?except: ? ? ? ? ? ? ?raise Exception(Record not found) ? ? ?def changeRecord(self, record, type, target): ? ? ? ? ? ? ? ? ? ?Changes a dns entry. ? ? ? ? ?...@param record: which record to chance ? ? ? ? ?...@param type: ?what type of record, A, MX, NS, CNAME ? ? ? ? ?...@target: if CNAME target points to HOSTNAME, if A record ?points to IP ? ? ? ? ? ? ? ? ? ?openZoneFile(record) ? ? ? ? ?try: ? ? ? ? ? ? ?rdataset = zone.find_rdataset(host, rdtype=type) ? ? ? ? ?except: ? ? ? ? ? ? ?raise Exception(You must enter a valid record and type. ?See --usage for examples) Don't catch all exceptions - find out which exceptions are thrown. Consider just letting it propagate - hopefully the find_rdataset error is descriptive enough. Thanks for taking the time to reply I appreciate it. No problems. Are global variables bad? Or just inefficient? They make code a lot more difficult to follow because you have to wonder where the variable has been set. If you create multiple instances of DNSFunctions (more than likely in a multi-user server) you'll find that global variables will cause your program to go wrong quite badly! In general only ever use global variables in quick and dirty scripts. For static configuration which you might think globals are good for you can easily do that in a module namespace or in a
Re: Cross platform compilation?
Christian Heimes li...@cheimes.de wrote: John Harper schrieb: I am trying to build Python to use in an embedded system which uses a ppc_440 CPU. The only information I've found is something written by Klaus Reimer a few years ago, which was based on Python 2.2. So far I seem to have successfully built Python itself, but building the extensions fails miserably with complaints about library format. It insists on referring to i686 which is indeed the platform it is actually running on. Before I try to reverse engineer completely setup.py, is there something obvious that needs to be done to get it to use the right tool chain? I spent some time mucking about trying to do this for ARM. I almost got it to work using qemu but not quite! What I did in the end was to use a pre-compiled python (from debian) then copy the headers and library files into the cross compiling environment so we could embed python into our code and build our extensions. More generally, it seems like this would be something that lots of people would want to do. I'm surprised there isn't support for it built into the distributed version of Python, without having to hack all the setup files...? I'm sorry to inform you that Python doesn't support cross platform compilation. Python eats its own dog food and uses Python to compile optional extension modules. It isn't an impossible problem... If you've ever cross compiled gcc you'll find that it first uses the host compiler (possibly not gcc) to compile itself to make a gcc which runs on the host but makes code for the target. It then uses that new compiler to compile a gcc for the target architecture. I could imagine a similar scheme for python, but it would involve lots of fiddling about and some commitment from the python maintainers. -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
On Wed, Feb 4, 2009 at 1:22 AM, Helmut Jarausch jarau...@skynet.be wrote: Hi, using e.g. import subprocess Package='app-arch/lzma-utils' EQ=subprocess.Popen(['/usr/bin/equery','depends',Package],stdout=subprocess.PIPE) EQ_output= EQ.communicate()[0] EQ_output is a string containing multiple lines. I'd prefer a file-like object, e.g. EQ_OUT so that I can loop over the lines of it like for line in EQ_OUT : ... Is there some reason that: for line in EQ_OUT.splitlines(): #... Does not meet your needs? Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Locating python
On Feb 3, 7:35 pm, David Sevilla sevil...@gmail.com wrote: I am quite new to Linux, and thought that by using yast2 there would be no user problems (I am asked for the root password). I will sudo it to see if it solves the problem. yast asked you for the password so that easy_install could be installed correctly. you are now using sudo easy_install to install mnemosyne and sudo is asking for the root password. each time you install something you need to change public files on the system, and so each time you need to use root in some way. yast does this by logging in as root for you, but needs the password to do it. sudo does the same thing, but again needs the password to do it. hope that makes senses (and that this worked). andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: x64 speed
Martin v. Löwis wrote: I follow David's guess that Linux does better IO than Windows (not knowing anything about the benchmark, of course) I originally thought it must be the vmware host stuff offloading IO to the second core, but watching with sysinternals didn't show a lot of extra stuff going on with the vm compared to just running on the host. I'm not talking about vmware. I'm suggesting that Linux ext3, and the Linux buffer handling, is just more efficient than NTFS, and the Windows buffer handling. If you split the total runtime into system time and user time, how do the 30s split up? ... so here is one for the vm clock is bad theorists :) [rpt...@localhost tests]$ time python25 runAll.py . . -- Ran 193 tests in 27.841s OK real0m28.150s user0m26.606s sys 0m0.917s [rpt...@localhost tests]$ magical how the total python time is less than the real time. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Steven D'Aprano a écrit : On Tue, 03 Feb 2009 12:09:46 +0100, Bruno Desthuilliers wrote: I love Python, and I'm greedy and want it all: I want a dynamic, easy-to- use language *and* a compiler that can protect me from myself That's not what compilers are for. So you say. While it's quite clear that a compiler for a statically typed language can catch at least some type errors, this is still not what a compiler is for. A compiler is here to compile you source code into a suitable representation for the execution environment. And FWIW, some compilers are rather weaker than Python when it comes to protecting you from yourself. and bad data. I definitly fail to see how a compiler could protect you from *runtime* issues ??? I'm surprised you can't. Any time a compiler prevents an error by detecting it at compile-time (say, attempting to store a 96-bit float into the memory space allocated for a 32-bit int), Oh, you meant type error. But this is a programming error, not bad data. bad data is something you get (usually from the outside world) at runtime only. Well, the way I understand it, at least. Perhaps what you are thinking is that I meant compilers can protect you from all runtime issues. That would be silly. Although, in principle, we can get close, for some definition of close. Here's a toy function, and a specification: def inverse(x): return 1.0/x Specification: input must be a float, output must be a float. Is that function correct? No, because it will raise an exception if x==0.0. Python's compiler is dumb and will allow you to write incorrect functions, but a smart compiler could look at that function and see that it was incorrect. The fix would then be to change the code, or the specification, or both. Ok, let's see. What happens if you pass 0.0 to the function as-is ? Yes, indeed, you get a runtime error. Now what happens if you add error handling to the function itself ? What will the error handler do ? Yes, raise a runtime error. So far, I don't see any gain here. No, no, don't answer yet. Sure, what you need here is a compiler that can inspect the whole code source using this function to make sure it is always properly invoked. Mmm, wait - will this work with shared libs ? I'm afraid not. Ok, so you have to change the specification to : input must be a non-zero-float, and use the type system to define non-zero-float type. Smart compilers turn some runtime errors into compile-time errors. Indeed. The earlier you catch the error, the easier it is to fix it. Indeed. Now, that's a toy example. Languages like Ada make correctness proofs, well, perhaps not easy, but merely difficult compared to impossible for languages like Python. Indeed. And that's fine : if we want maximum type safety and as-possibly-proved code, we know which tool to use. Now good luck doing web development, system admin, app scripting and quite a lot of other things (well, perhaps more that 80% of ordinary application programming) in Ada. Can you understand that not everybody needs maximum type safety / correctness proof etc for all his code ? That all this security stuff comes with a price that may not be worth paying ? To bring it back to private/public attributes, side-effects make correctness proofs difficult. Modifications of attributes are side- effects. Then use a functional language !-) When attributes are subject to being modified by arbitrary code, it is harder to reason about the correctness of the code: Indeed. Not the right tool, obviously. OTHO, it makes it way easier to use as glue between different, sometimes not highly compatible components. (snip) There are two usual approaches to dealing with that problem which are available to Python programmers: (1) Paranoia. Make the developer responsible for checking everything all the time: Paranoiacs (also known as control-freaks) are not happy using Python. They usually prefer Ada or, at least, Java. def invert(self): x = self.x if isinstance(x, float) and x: return 1.0/self.x else: raise MyError('post-condition x a non-zero float violated') The correct solution is indeed to make x a property with a sanity check in the setter - in which case you'll have a useful traceback - or as a read-only property, or even better to just declare it as implementation (naming it _x). (2) Hope the error never occurs, and if it does, let the caller deal with it. If the attribute is either a read-only property or an implementation attribute, then the guy that messed with it is responsible for the possible consequences. That's the contract, yes. Hopefully you aren't your own caller. I'm usually the first user of my own libs, and my coworkers comes immediatly after. IOW, I eat my own dogfood, thanks. That's often the Python approach. As I explained above, the Python approach is actually a bit different. In
Re: How to call python from a foreign language thread (C++)
On 4/02/2009 4:51 AM, Victor Lin wrote: It may looks like this. void operator() (double time, const AudioDatadata) { // acquire lock m_Function(time, data); // release lock } You want something like: void operator() (double time, const AudioDatadata) { PyGILState_STATE old = PyGILState_Acquire(); m_Function(time, data); PyGILState_Release(old); Note that Phillip is also correct; you will need to initialize threading if this is an app which embeds Python... HTH, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Load / Reload module
Marius Butuc wrote: I want do declare some classes (classes.py) in an external editor, than import the file and use the classes. After I change the file, I want to reload the definitions w/o leaving the interactive interpreter. So far I have tried - import classes # doesn't import my classes Use this and refer to the class from the imported module. import classes instance = classes.SomeClass() ... reload(classes) instance = classes.SomeClass() This is by far the best way, but if you _must_, from classes import * instance = SomeClass() ... reload(classes) from classes import * instance = SomeClass() --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
Chris Rebert wrote: On Wed, Feb 4, 2009 at 1:22 AM, Helmut Jarausch jarau...@skynet.be wrote: Hi, using e.g. import subprocess Package='app-arch/lzma-utils' EQ=subprocess.Popen(['/usr/bin/equery','depends',Package],stdout=subprocess.PIPE) EQ_output= EQ.communicate()[0] EQ_output is a string containing multiple lines. I'd prefer a file-like object, e.g. EQ_OUT so that I can loop over the lines of it like for line in EQ_OUT : ... Is there some reason that: for line in EQ_OUT.splitlines(): #... Does not meet your needs? It works, but it still reads the complete output of the command executed by Popen at once. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Locating python
andrew cooke wrote: On Feb 3, 7:35 pm, David Sevilla sevil...@gmail.com wrote: I am quite new to Linux, and thought that by using yast2 there would be no user problems (I am asked for the root password). I will sudo it to see if it solves the problem. yast asked you for the password so that easy_install could be installed correctly. you are now using sudo easy_install to install mnemosyne and sudo is asking for the root password. each time you install something you need to change public files on the system, and so each time you need to use root in some way. yast does this by logging in as root for you, but needs the password to do it. sudo does the same thing, but again needs the password to do it. hope that makes senses (and that this worked). actually su needs the root (or the target users') password and sudo needs _your_ (the current users) password. HTH Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Kill a function while it's being executed
Hi All, I have a script in which I receive a list of functions. I iterate over the list and run each function. This functions are created by some other user who is using the lib I wrote. Now, there are some cases in which the function I receive will never finish (stuck in infinite loop). Suppose I use a thread which times the amount of time passed since the function has started, Is there some way I can kill the function after a certain amount of time has passed (without asking the user who's giving me the list of functions to make them all have some way of notifying them to finish)? Thanks, Noam -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
Clovis Fabricio wrote: 2009/2/4 Helmut Jarausch jarau...@skynet.be: using e.g. import subprocess Package='app-arch/lzma-utils' EQ=subprocess.Popen(['/usr/bin/equery','depends',Package],stdout=subprocess.PIPE) EQ_output= EQ.communicate()[0] EQ_output is a string containing multiple lines. I'd prefer a file-like object, e.g. EQ_OUT so that I can loop over the lines of it like EQ.stdout is the filelike object you're looking for. communicate() grabs entire output at once so don't use it. import subprocess Package = 'app-arch/lzma-utils' EQ = subprocess.Popen(['/usr/bin/equery', 'depends', Package], stdout=subprocess.PIPE) for line in EQ.stdout: do_stuff_with(line) Thanks a lot, I haven't found that in the official documentation. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: python libpcap equivalent
Gabriel schrieb: Hello I need to write a software router [yes, software equivalent to a hardware box that is routing packets .)]. It's a school work.. Question is: is possible write this kind of application in python? and if it's, what module should i use? I tried search for some libpcap equivalent in python and found pylibpcap, but can't find documentation and tutorial. Hello Gabriel, you might look into scapy: http://www.secdev.org/projects/scapy/ which easily allows you to fetch, manipulate and send network packages. Jürgen -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
2009/2/4 Helmut Jarausch jarau...@skynet.be: using e.g. import subprocess Package='app-arch/lzma-utils' EQ=subprocess.Popen(['/usr/bin/equery','depends',Package],stdout=subprocess.PIPE) EQ_output= EQ.communicate()[0] EQ_output is a string containing multiple lines. I'd prefer a file-like object, e.g. EQ_OUT so that I can loop over the lines of it like EQ.stdout is the filelike object you're looking for. communicate() grabs entire output at once so don't use it. import subprocess Package = 'app-arch/lzma-utils' EQ = subprocess.Popen(['/usr/bin/equery', 'depends', Package], stdout=subprocess.PIPE) for line in EQ.stdout: do_stuff_with(line) -- http://mail.python.org/mailman/listinfo/python-list
Re: Locating python
On Feb 4, 9:16 am, andrew cooke and...@acooke.org wrote: actually su needs the root (or the target users') password and sudo needs _your_ (the current users) password. argh, sorry for the confusion. actually, no. sudo requires the root password. at least on opensuse 11.1 default config. i just tried it: Python-2.5.4: sudo make install root's password: this is explained in the sudoers file: # In the default (unconfigured) configuration, sudo asks for the root password. # This allows use of an ordinary user account for administration of a freshly # installed system. When configuring sudo, delete the two # following lines: Defaults targetpw # ask for the password of the target user i.e. root ALL ALL=(ALL) ALL # WARNING! Only use this together with 'Defaults targetpw'! andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting Russ P. russ.paie...@gmail.com: Indeed he can. He can even do that in Python; it just requires a little self-discipline from the team, or a validation script on the code repository if he really doesn't trust them. Not only can this be done without forcing the rest of the world to play, it makes things a little less daunting when those nice clean interfaces turn out to be incomplete/too slow/not what you thought. This has already been refuted several times on this thread alone, so I will not bother doing it again. Please, point out where, because I don't recall you explaining why is not enough to use a validation script on the code if you wish to. I _do_ recall you saying that you didn't want the validation script unless it is integrated with python, but I'm yet to see the difference. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Quoting Russ P. russ.paie...@gmail.com: Imagine you own a company, and you decide to lease an office building. Would you expect the office doors to have locks on them? Oh, you would? Why? You mean you don't trust your co-workers? What are locks but enforced access restriction? This analogy is nonsense. There is no way you will execute code on my system if I don't authorize it, regardless of how public are the variables declared in my code. No one will execute code on _your_ system either, without your authorization. That puts you in a different position: you can easily _check_ that everything is alright before executing, whereas in the office example, it cannot be done. Of course, if the analogy is flawed in such an essential aspect, I won't even humor it. I worry, though, that you obviously believe that it is not flawed. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: v 3.0 mpkg
2009/2/4 John Forse johnfo...@talktalk.net: Does anyone know if Python v3.0 is available as an .mpkg installer for Mac 10.5.6. I have used 2.5 updated to 2.6.1 this way, but can't find any reference to one on the Python.org download site. I've downloaded the Python 3.0 folder but can't follow how to install it without a .mpkg file. Any help would be really appreciated. AFAIK there's no Python 3.0 installer for the Mac. You'll have to build it yourself - see http://tinyurl.com/6zkem7. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
Andreas Waldenburger wrote: On Sat, 31 Jan 2009 13:27:02 -0500 Pat p...@junk.net wrote: Tobiah wrote: Just out of curiosity, why was len() made to be it's own function? I often find myself typing things like my_list.len before I catch myself. Thanks, Toby I'm surprised that no one responded to that question. Huh? Gabriel Genellina replied about 46 minutes after it was posted. Might it be that your newsserver is a bit laggy? regards /W Might be laggy. Who knows. Why didn't you answer the len() question? -- http://mail.python.org/mailman/listinfo/python-list
Re: kinterbasdb + firebird 1.5 with python 2.6 ?
Laszlo Nagy wrote: Does anyone know how to get firebird 1.5 driver (kinterbasdb) for FireBird 1.5? My problem: * python 2.6 already installed on a server * there is a firebird 1.5 database on the same server * I need to access it from python 2.6 Any thoughts? Get it from here: http://www.firebirdsql.org/index.php?op=develsub=python You should have mentioned your OS to get better answers. Uwe -- http://mail.python.org/mailman/listinfo/python-list
Tkinter
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: from Tkinter import * def MainWin(): 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) frame1=Frame(back_ground,width=213,height=480,bg='light gray') frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) close_frame1=Button(frame1,text='close',bg='light gray', command=frame1.destroy) close_frame1.pack_propagate(0) close_frame1.pack(side=TOP, anchor=N,pady=25) if frame1.destroy==True: frame1=Frame(back_ground,width=213,height=480,bg='white') frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) main.mainloop() MainWin() It may just be bad coding but either way I could use some help. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
Pat wrote: Why didn't you answer the len() question? It's a bit of a FAQ: len() cannot be a method of list objects because it works on any sequence or iterable. -- http://mail.python.org/mailman/listinfo/python-list
Re: x64 speed
On Feb 4, 10:14 am, Robin Becker ro...@reportlab.com wrote: [rpt...@localhost tests]$ time python25 runAll.py . . -- Ran 193 tests in 27.841s OK real 0m28.150s user 0m26.606s sys 0m0.917s [rpt...@localhost tests]$ magical how the total python time is less than the real time. Not really. Python was still running at the time that it prints the time of the tests. So it's only natural that the wall time Python prints on just the tests is going to be smaller then the wall time time prints for the entire python process. Same for when it starts, some stuff is done in Python before it starts its timer. Regards Floris -- http://mail.python.org/mailman/listinfo/python-list
Re: Locating python
andrew cooke wrote: On Feb 4, 9:16 am, andrew cooke and...@acooke.org wrote: actually su needs the root (or the target users') password and sudo needs _your_ (the current users) password. argh, sorry for the confusion. actually, no. sudo requires the root password. at least on opensuse 11.1 default config. i just tried it: argh. This Nürnberg Windows ;-) But this shows that a sensible configuration of the system is usefull before you start installing services on it :-) Cheers Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
tkSimpleDialog window focus problem
Hi all, As part of the program I've created and am maintaining, the user has to type in his/her username and password into tkinter simple dialog windows. What you'll see below is that I've nested an askstring dialog window within a call to use the ftp module to login to an FTP server. result = self.ftp.login(self.userid, tkSimpleDialog.askstring (Password Entry, Password:, show=*)) Annoyingly, every time this password entry window pops up, the focus does not go on it automatically. Anyone know what I can do to put the focus on it automatically, while *not* storing the user's password in my script for the remainder of its runtime? Thanks, Matt Dubins -- http://mail.python.org/mailman/listinfo/python-list
Re: Kill a function while it's being executed
On Wed, 2009-02-04 at 13:40 +0200, Noam Aigerman wrote: Hi All, I have a script in which I receive a list of functions. I iterate over the list and run each function. This functions are created by some other user who is using the lib I wrote. Now, there are some cases in which the function I receive will never finish (stuck in infinite loop). Suppose I use a thread which times the amount of time passed since the function has started, Is there some way I can kill the function after a certain amount of time has passed (without asking the user who's giving me the list of functions to make them all have some way of notifying them to finish)? Thanks, Noam Noam, did you hijack a thread? You could decorate the functions with a timeout function. Here's one that I either wrote or copied from a recipe (can't recall): class FunctionTimeOut(Exception): pass def function_timeout(seconds): Function decorator to raise a timeout on a function call import signal def decorate(f): def timeout(signum, frame): raise FunctionTimeOut() def funct(*args, **kwargs): old = signal.signal(signal.SIGALRM, timeout) signal.alarm(seconds) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return funct return decorate Then func_dec = function_timeout(TIMEOUT_SECS) for func in function_list: timeout_function = func_dec(func) try: timeout_function(...) except FunctionTimeout: ... -a -- http://mail.python.org/mailman/listinfo/python-list
RE: Kill a function while it's being executed
About the hijacking - I *might* have done it without understanding what I did (replied to a previous message and then changed the subject), if that's what you mean... Sorry -Original Message- From: python-list-bounces+noama=answers@python.org [mailto:python-list-bounces+noama=answers@python.org] On Behalf Of Albert Hopkins Sent: Wednesday, February 04, 2009 5:26 PM To: python-list@python.org Subject: Re: Kill a function while it's being executed On Wed, 2009-02-04 at 13:40 +0200, Noam Aigerman wrote: Hi All, I have a script in which I receive a list of functions. I iterate over the list and run each function. This functions are created by some other user who is using the lib I wrote. Now, there are some cases in which the function I receive will never finish (stuck in infinite loop). Suppose I use a thread which times the amount of time passed since the function has started, Is there some way I can kill the function after a certain amount of time has passed (without asking the user who's giving me the list of functions to make them all have some way of notifying them to finish)? Thanks, Noam Noam, did you hijack a thread? You could decorate the functions with a timeout function. Here's one that I either wrote or copied from a recipe (can't recall): class FunctionTimeOut(Exception): pass def function_timeout(seconds): Function decorator to raise a timeout on a function call import signal def decorate(f): def timeout(signum, frame): raise FunctionTimeOut() def funct(*args, **kwargs): old = signal.signal(signal.SIGALRM, timeout) signal.alarm(seconds) try: result = f(*args, **kwargs) finally: signal.signal(signal.SIGALRM, old) signal.alarm(0) return result return funct return decorate Then func_dec = function_timeout(TIMEOUT_SECS) for func in function_list: timeout_function = func_dec(func) try: timeout_function(...) except FunctionTimeout: ... -a -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
On Feb 4, 5:35 am, Luis Zarrabeitia ky...@uh.cu wrote: Quoting Russ P. russ.paie...@gmail.com: Imagine you own a company, and you decide to lease an office building. Would you expect the office doors to have locks on them? Oh, you would? Why? You mean you don't trust your co-workers? What are locks but enforced access restriction? This analogy is nonsense. There is no way you will execute code on my system if I don't authorize it, regardless of how public are the variables declared in my code. No one will execute code on _your_ system either, without your authorization. That puts you in a different position: you can easily _check_ that everything is alright before executing, whereas in the office example, it cannot be done. I don't follow your point, but I think you are reading too much into the analogy. Obviously, an office building cannot be copied in a few seconds as a software library can, so the analogy obviously cannot be taken too far. The locks on the doors are analogous to enforced access restrictions. When you lease the building, you are presumably given a complete set of keys, including master keys. The keys are analogous to the source code, which allows you to trivially disable the access restrictions. People like you are saying that keys are not enough. You don't want to be bothered with keys. You want the office doors to come with no locks on them at all, because you don't intend to lock them anyway, and someone could possibly get locked out someday. You are saying that locks are unnecessary because you trust your co-workers (aren't you lucky!), and you can just put keep-out signs on the doors (leading underscores). Well, that may be reasonable for a small group of developers working on a small, cool project. It is inappropriate, however, for a large, safety-critical project with dozens or hundreds of developers that are hired off the street in accordance with current labor laws. Now, if you concede that Python is just not intended for such projects, then fine, but please don't claim that access restrictions are useless for all applications and domains. That's just ridiculous. -- http://mail.python.org/mailman/listinfo/python-list
wsdl2py/ZSI and complex types with arrays
Hello all, I have been trying to write a web service using ZSI with wsdl2py. I have read 'The Zolera Soap Infrastructure User’s Guide Release 2.0.0' and some older guides (a guide by Nortel called Using ZSI with wsdl2py) and am unable to find any working examples of how to use arrays in complex types. I have a Request method which takes an array as an argument and responds with an array. Assume I am just trying to write a client at this point. I have tried a lot of variations on this and can get a call made but using a tracefile the element SOIID is always empty no matter what I do. Please excuse me if the code is not fantastic. I am very new to python. #--- from GraphingReporter_services import * from GraphingReporter_services_types import * loc = GraphingReporterLocator() fp = file(/tmp/PYTHON-TRACE,w) port = loc.getGraphingReporterPort(tracefile=fp) request = GraphRequestSOIID() graphRequest = request.new_soiid() graphRequest.Soiid = [123456,123457] request.set_element_soiid(graphRequest) response = port.GetGraphsForSOIID(request) fp.close() #--- The outgoing call in the trace shows #--- SOAP-ENV:Body xmlns:ns1=urn:GraphingReporter ns1:GetGraphsForSOIID soiid/soiid /ns1:GetGraphsForSOIID /SOAP-ENV:Body #--- Can anyone provide me an example (or a link to an example) of how to populate the arrays in complex types? Even pointing me in the right direction would be wonderful. -- EvilJonny -- http://mail.python.org/mailman/listinfo/python-list
[Web 2.0] Added-value of frameworks?
Hello If I wanted to build some social web site such as Facebook, what do frameworks like Django or TurboGears provide over writing a site from scratch using Python? Thank you for your feedback. -- http://mail.python.org/mailman/listinfo/python-list
Re: [2.5.1] Comparing dates?
On Mon, 2 Feb 2009 22:00:53 +0100, Martin mar...@marcher.name wrote: as suggested, the DBA should seriously think about defining the correct type of the column here, for intermediate use and getting stuff to work you could use a view and define some stored procedures on it so that inserting properly works... Right, but SQLite only has two types: Numeric or text, so I figured it'd be better to turn dates into the usual -MM-DD before saving data into an SQLite file. Thanks for the feedback. -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
Marco Mariani wrote: Pat wrote: Why didn't you answer the len() question? It's a bit of a FAQ: len() cannot be a method of list objects because it works on any sequence or iterable. Thats only half of the truth :-) len() can use some internal optimizations on certain objects where sequences indeed have a len() method called __len__() Regards Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Locating python
actually su needs the root (or the target users') password and sudo needs _your_ (the current users) password. argh, sorry for the confusion. -- http://mail.python.org/mailman/listinfo/python-list
Use list name as string
Do to laking knowledge my google searches have not turned up an answer for me. I know this is wrong it uses the items in the list as the filename, how do I refer to the dataname and not the items in it. def savedata(dataname): filename = str(dataname) # this does not do what I would like it to ext1 = '\.csv' flex = filename + ext1 datawrite = csv.writer(open(flex, wb)) datawrite.writerows(dataname) Thanks Vincent Davis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to call python from a foreign language thread (C++)
On 4/02/2009 8:43 PM, I wrote: PyGILState_STATE old = PyGILState_Acquire(); Make that PyGILState_Ensure(); Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
2009/2/4 Helmut Jarausch jarau...@skynet.be: EQ.stdout is the filelike object you're looking for. communicate() grabs entire output at once so don't use it. Thanks a lot, I haven't found that in the official documentation. Helmut. That would be a documentation bug. Fortunately it is not true. Here is it in the documentation: http://docs.python.org/library/subprocess.html#subprocess.Popen.stdout -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen - file like object from stdout=PIPE
Clovis Fabricio wrote: 2009/2/4 Helmut Jarausch jarau...@skynet.be: EQ.stdout is the filelike object you're looking for. communicate() grabs entire output at once so don't use it. Thanks a lot, I haven't found that in the official documentation. Helmut. That would be a documentation bug. Fortunately it is not true. Here is it in the documentation: http://docs.python.org/library/subprocess.html#subprocess.Popen.stdout Thanks! For people like me which don't always read until the end of a document it would be nice if just after the paragraph stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. there would some lines like These pipes are exposed as file-like objects which can be accessed via the stdin, stdout or stderr (resp.) attributes of an object of class subprocess.Popen . Please be indulgent to people like me. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Added-value of frameworks?
On Feb 4, 8:08 am, Gilles Ganault nos...@nospam.com wrote: Hello If I wanted to build some social web site such as Facebook, what do frameworks like Django or TurboGears provide over writing a site from scratch using Python? Thank you for your feedback. Why not just look at the frameworks themselves and see what they have to offer. Django and Turbogears both have pretty good tutorials. You can be up and running in 20 minutes with each one. You be the judge. The frameworks provide a lot of boilerplate code that I would rather not write. They are probably more secure and scalable than something I would come up with. You also get many extras for free. I think in both of the frameworks you mention you get an administrative back end for free. Other people have created apps/plugins that you can use with those frameworks. So, for example, you might be able to borrow the code to help you add a forum to your site. I'm not sure I know the advantage of not using a framework. Unless I get to write more code is an advantage. Creating your own framework might be fun, but if you really just want a website don't do more work than you need to. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
Vincent Davis wrote: Do to laking knowledge my google searches have not turned up an answer for me. I know this is wrong it uses the items in the list as the filename, how do I refer to the dataname and not the items in it. def savedata(dataname): filename = str(dataname) # this does not do what I would like it to ext1 = '\.csv' flex = filename + ext1 datawrite = csv.writer(open(flex, wb)) datawrite.writerows(dataname) I need more information to answer this question -- because I have no idea what the question means. SO: What is dataname? What would you like filename to be after that line. One example of dataname and the desired filename is probably enough to answer your question. Thanks Vincent Davis -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
I know this is wrong it uses the items in the list as the filename, how do I refer to the dataname and not the items in it. Without a sample value for dataname, it's hard to tell what you're trying to do. Do you mean dataname = ['path', 'to', 'file'] ... filename = os.sep.join(dataname) Or you have a list of one value, and just want its first item? filename = dataname[0] def savedata(dataname): filename = str(dataname) # this does not do what I would like it to It would help if you detailed what you *would* like it to do... from MindReading import answer Traceback (most recent call last): File stdin, line 6, in comp.lang.python ImportError: No module named MindReading Similar failure attempting import dwim -tkc -- http://mail.python.org/mailman/listinfo/python-list
Couple of noobish question
Firstly hi, I don't know any of you yet but am picking up Python and will be lurking here a lot lol. I am a hobbiest coder (did 3 out of 4 years of a comp tech degree, long story) and am learning Python, 'cos I saw some code and it just looks a really nice language to work with. I come from C++, so I am bound to trip up trying to do things the wrong way! I have been working with Project Euler to get the hang of Python, and all goes well. I have an idea for a small project, an overly simplistic interactive fiction engine (well more like those old choose your own adventure books, used to love those!) that uses XML for its map files. The main issues I see so far is the XML parsing (I should pick that up ok, I have a blackbelt in google-foo), but more importantly splitting code files. In C++ I would obviously split .cpp and .h files, pairing them up and using #include. How do I do this in Python? I see that you don't tend to split logic from defenition, but how do I keep different classes in different files? My google-fu fails me so far. -- http://mail.python.org/mailman/listinfo/python-list
Re: Load / Reload module
Scott David Daniels wrote: Marius Butuc wrote: I want do declare some classes (classes.py) in an external editor, than import the file and use the classes. After I change the file, I want to reload the definitions w/o leaving the interactive interpreter. So far I have tried - import classes # doesn't import my classes Use this and refer to the class from the imported module. import classes instance = classes.SomeClass() ... reload(classes) instance = classes.SomeClass() This is by far the best way, but if you _must_, from classes import * instance = SomeClass() ... reload(classes) from classes import * instance = SomeClass() Also note that only instances created after the reload will have the new layout: import classes a = classes.SomeClass() print a old open(classes.py, w).write(class SomeClass: ... def __str__(self): return 'new' ... ) reload(classes) module 'classes' from 'classes.py' b = classes.SomeClass() print b new print a old Sometimes you may be able to fix this manually by assigning to the __class__: a.__class__ = classes.SomeClass print a new but I recommend that you put all your code into a another script rather than resorting to such tricks $ cat main.py import classes a = classes.SomeClass() If you want to experiment with a in the interactive interpreter you can invoke main with the -i option: $ python -i main.py print a new Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Kill a function while it's being executed
Noam Aigerman wrote: About the hijacking - I *might* have done it without understanding what I did (replied to a previous message and then changed the subject), if that's what you mean... Sorry That's what he meant. A lot of news reading and email software uses In-Reply-To and various other message headers to determine how messages are threaded, so (for example) in my Thunderbird Window this appears to be a part of the thread that started out as Locating Python. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
re.sub and named groups
Hi everybody, I'm having a ball with the power of regular expression but I stumbled on something I don't quite understand: theOriginalString = spam:(?Pfirst.*) ham:(?Psecond.*) aReplacementPattern = \(\?Pfirst.*\) aReplacementString= foo re.sub(aReplacementPattern , aReplacementString, theOriginalString) results in : spam:foo instead, I was expecting: spam:foo ham: Why is that? Thanks for your help! Manu -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
Sorry for not being clearI would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem, getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works Thanks Vincent Davis 720-301-3003 On Wed, Feb 4, 2009 at 9:48 AM, Tim Chase python.l...@tim.thechases.comwrote: I know this is wrong it uses the items in the list as the filename, how do I refer to the dataname and not the items in it. Without a sample value for dataname, it's hard to tell what you're trying to do. Do you mean dataname = ['path', 'to', 'file'] ... filename = os.sep.join(dataname) Or you have a list of one value, and just want its first item? filename = dataname[0] def savedata(dataname): filename = str(dataname) # this does not do what I would like it to It would help if you detailed what you *would* like it to do... from MindReading import answer Traceback (most recent call last): File stdin, line 6, in comp.lang.python ImportError: No module named MindReading Similar failure attempting import dwim -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb and MySQL stored functions
kurt.forrester@googlemail.com kurt.forrester@googlemail.com wrote: Any ideas on how to suppress the warning output: __main__:1: Warning: No data - zero rows fetched, selected, or processed You can use the warnings module to suppress these I would have thought. -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
Vincent Davis wrote: Sorry for not being clear I would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem, getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works The list itself doesn't have a name. You need to pass in both the name and the list: def savedata(name, data): .. savedata(x, x) -- http://mail.python.org/mailman/listinfo/python-list
Re: Couple of noobish question
On Feb 4, 10:47 am, Catherine Heathcote catherine.heathc...@gmail.com wrote: Firstly hi, I don't know any of you yet but am picking up Python and will be lurking here a lot lol. I am a hobbiest coder (did 3 out of 4 years of a comp tech degree, long story) and am learning Python, 'cos I saw some code and it just looks a really nice language to work with. I come from C++, so I am bound to trip up trying to do things the wrong way! I have been working with Project Euler to get the hang of Python, and all goes well. I have an idea for a small project, an overly simplistic interactive fiction engine (well more like those old choose your own adventure books, used to love those!) that uses XML for its map files. The main issues I see so far is the XML parsing (I should pick that up ok, I have a blackbelt in google-foo), but more importantly splitting code files. In C++ I would obviously split .cpp and .h files, pairing them up and using #include. How do I do this in Python? I see that you don't tend to split logic from defenition, but how do I keep different classes in different files? My google-fu fails me so far. You just use the keyword import. Here's a goofy example: 1) foo.py contains a class called Foo 2) bar.py contains a script that imports Foo: import foo # create an instance of the Foo class myFoo = foo.Foo() I hope that was clear. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Couple of noobish question
Mike Driscoll wrote: On Feb 4, 10:47 am, Catherine Heathcote catherine.heathc...@gmail.com wrote: Firstly hi, I don't know any of you yet but am picking up Python and will be lurking here a lot lol. I am a hobbiest coder (did 3 out of 4 years of a comp tech degree, long story) and am learning Python, 'cos I saw some code and it just looks a really nice language to work with. I come from C++, so I am bound to trip up trying to do things the wrong way! I have been working with Project Euler to get the hang of Python, and all goes well. I have an idea for a small project, an overly simplistic interactive fiction engine (well more like those old choose your own adventure books, used to love those!) that uses XML for its map files. The main issues I see so far is the XML parsing (I should pick that up ok, I have a blackbelt in google-foo), but more importantly splitting code files. In C++ I would obviously split .cpp and .h files, pairing them up and using #include. How do I do this in Python? I see that you don't tend to split logic from defenition, but how do I keep different classes in different files? My google-fu fails me so far. You just use the keyword import. Here's a goofy example: 1) foo.py contains a class called Foo 2) bar.py contains a script that imports Foo: import foo # create an instance of the Foo class myFoo = foo.Foo() I hope that was clear. Mike Perfect, thanks ^^ -- http://mail.python.org/mailman/listinfo/python-list
Re: re.sub and named groups
Emanuele D'Arrigo wrote: Hi everybody, I'm having a ball with the power of regular expression but I stumbled on something I don't quite understand: theOriginalString = spam:(?Pfirst.*) ham:(?Psecond.*) aReplacementPattern = \(\?Pfirst.*\) aReplacementString= foo re.sub(aReplacementPattern , aReplacementString, theOriginalString) results in : spam:foo instead, I was expecting: spam:foo ham: Why is that? Thanks for your help! The quantifiers eg * are normally greedy; they try to match as much as possible. Therefore .* matches: spam:(?Pfirst.*) ham:(?Psecond.*) ^ You could use the lazy form *? which tries to match as little as possible, eg \(\?Pfirst.*?\) where the .*? matches: spam:(?Pfirst.*) ham:(?Psecond.*) ^^ giving spam:foo ham:(?Psecond.*). -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
I know nothing but that sucks. I can think of a lot of times I would like to do something similar. There really is no way to do this, it seems like there would be some simple way kind of like str(listname) but backwards or different. Thanks Vincent Davis On Wed, Feb 4, 2009 at 10:07 AM, MRAB goo...@mrabarnett.plus.com wrote: Vincent Davis wrote: Sorry for not being clear I would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem, getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works The list itself doesn't have a name. You need to pass in both the name and the list: def savedata(name, data): .. savedata(x, x) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
I guess what I am saying is that it does not seem like I am adding any information that is not already there when I have to enter that list and list name after all they are the same. Thanks Vincent Davis On Wed, Feb 4, 2009 at 10:18 AM, Vincent Davis vinc...@vincentdavis.netwrote: I know nothing but that sucks. I can think of a lot of times I would like to do something similar. There really is no way to do this, it seems like there would be some simple way kind of like str(listname) but backwards or different. Thanks Vincent Davis On Wed, Feb 4, 2009 at 10:07 AM, MRAB goo...@mrabarnett.plus.com wrote: Vincent Davis wrote: Sorry for not being clear I would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem, getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works The list itself doesn't have a name. You need to pass in both the name and the list: def savedata(name, data): .. savedata(x, x) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: re.sub and named groups
On Feb 4, 5:17 pm, MRAB goo...@mrabarnett.plus.com wrote: You could use the lazy form *? which tries to match as little as possible, eg \(\?Pfirst.*?\) where the .*? matches: spam:(?Pfirst.*) ham:(?Psecond.*) giving spam:foo ham:(?Psecond.*). A-ha! Of course! That makes perfect sense! Thank you! Problem solved! Ciao! Manu -- http://mail.python.org/mailman/listinfo/python-list
Re: Couple of noobish question
Catherine Heathcote wrote: Firstly hi, I don't know any of you yet but am picking up Python and will be lurking here a lot lol. I am a hobbiest coder (did 3 out of 4 years of a comp tech degree, long story) and am learning Python, 'cos I saw some code and it just looks a really nice language to work with. I come from C++, so I am bound to trip up trying to do things the wrong way! Welcome. I suspect you'll enjoy Python. (Far more than C++ ). I have been working with Project Euler to get the hang of Python, and all goes well. I have an idea for a small project, an overly simplistic interactive fiction engine (well more like those old choose your own adventure books, used to love those!) that uses XML for its map files. The main issues I see so far is the XML parsing (I should pick that up ok, I have a blackbelt in google-foo), but more importantly splitting code files. Several modules exits to do the parsing of XML: elementtree, xml, and beautifulsoup come to mind immediately. In C++ I would obviously split .cpp and .h files, pairing them up and using #include. How do I do this in Python? I see that you don't tend to split logic from defenition, but how do I keep different classes in different files? My google-fu fails me so far. Use the import statement for this. If file a.py defines some classes or functions a.py: class UsefulClass: ... def UsefulFn(...): ... Then your main Python file imports it and uses the things define in a.py like this: import a ob = UsefulClass(...) a.UsefulFn() Good luck, Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
can I do it the otherway, that issavedata('nameoflist') Thanks Vincent Davis 720-301-3003 On Wed, Feb 4, 2009 at 10:23 AM, Vincent Davis vinc...@vincentdavis.netwrote: I guess what I am saying is that it does not seem like I am adding any information that is not already there when I have to enter that list and list name after all they are the same. Thanks Vincent Davis On Wed, Feb 4, 2009 at 10:18 AM, Vincent Davis vinc...@vincentdavis.netwrote: I know nothing but that sucks. I can think of a lot of times I would like to do something similar. There really is no way to do this, it seems like there would be some simple way kind of like str(listname) but backwards or different. Thanks Vincent Davis On Wed, Feb 4, 2009 at 10:07 AM, MRAB goo...@mrabarnett.plus.com wrote: Vincent Davis wrote: Sorry for not being clear I would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem, getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works The list itself doesn't have a name. You need to pass in both the name and the list: def savedata(name, data): .. savedata(x, x) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Date Comparison
Bill McClain wrote: On 2009-02-03, mohana2...@gmail.com mohana2...@gmail.com wrote: Hi, I need to compare two dates and find the number of days between those two dates.This can be done with datetime module in python as below, but this is not supported in Jython. There are julian day routines in this astronomy package: http://astrolabe.sourceforge.net/ and in Mark Lemburg's mxDate Colin W. -Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
I know nothing but that sucks. I can think of a lot of times I would like to do something similar. There really is no way to do this, it seems like there would be some simple way kind of like str(listname) but backwards or different. Python does the only reasonable thing: doesn't give you access to the name. Consider the following situation: a = [1,2,3,4,5] b = a savedata(b) Do you want a or b as the variable-name? Both are valid names for the same list. If it matters, you can do something like this hack: def savedata(**kwargs): assert len(kwargs) == 1, Just pass one parameter filename, data = kwargs.iteritems().next() ext1 = '\.csv' flex = filename + ext1 datawrite = csv.writer(open(flex, wb)) datawrite.writerows(data) which can then be called with something like savedata(foo=[1,2,3,4,5]) savedata(bar=a) savedata(name=name) to create foo.csv containing that data. Or you could just pass it explicitly which would make more sense and be easier to understand. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: re.sub and named groups
Hi everybody, I'm having a ball with the power of regular expression but I stumbled on something I don't quite understand: theOriginalString = spam:(?Pfirst.*) ham:(?Psecond.*) aReplacementPattern = \(\?Pfirst.*\) aReplacementString= foo re.sub(aReplacementPattern , aReplacementString, theOriginalString) results in : spam:foo instead, I was expecting: spam:foo ham: Why is that? Thanks for your help! Manu I think that .* in your replacement pattern matches .*) ham:(?Psecond.* in your original string which seems correct for a regexp. Perhaps you should try aReplacementPattern = \(\?Pfirst\.\*\) or use replace() since your replacement pattern is not a regexp anymore. Sebastien -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
can I do it the otherway, that issavedata('nameoflist') for limited cases where your variable is defined globally, you can use: a = [1,2,3,4] def save(s): ... print globals().get(s, UNDEFINED) ... save(a) [1, 2, 3, 4] save(b) UNDEFINED b = (6,5,4,3) save(b) (6, 5, 4, 3) However, it's a hideous hack, and fragile as demonstrated by x = 7000 def baz(): ... x = (7,8,9) # this isn't in save()'s globals() ... save(x) ... baz() 7000 x = 8000 baz() 8000 and using locals() doesn't help either: print locals().get(s, globals().get(s, UNDEFINED)) and has even weirder (but totally understandable) behavior: save(s) # s hasn't been defined in globals() 's' Just pass the filename as a string, and skip trying to sniff internal variable-names. Or you'll experience a world of headaches. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Use list name as string
Vincent Davis wrote: I guess what I am saying is that it does not seem like I am adding any information that is not already there when I have to enter that list and list name after all they are the same. If you write: y = x then both x and y refer to the same list. The actual names of the variables and functions shouldn't matter to the outside world; the name of an output file shouldn't depend on the name of a variable. On Wed, Feb 4, 2009 at 10:18 AM, Vincent Davis vinc...@vincentdavis.net mailto:vinc...@vincentdavis.net wrote: I know nothing but that sucks. I can think of a lot of times I would like to do something similar. There really is no way to do this, itseems like there would be some simple way kind of like str(listname)but backwards or different. On Wed, Feb 4, 2009 at 10:07 AM, MRAB goo...@mrabarnett.plus.com mailto:goo...@mrabarnett.plus.com wrote: Vincent Davis wrote: Sorry for not being clear I would have something like this x = [1, 2, 3,5 ,6 ,9,234] Then def savedata(dataname): .. savedata(x) this would save a to a file called x.csv This is my problem,getting the name to be x.csv which is the same as the name of the list. and the data in the file would be 1,2,3,5,6,9,234 this parts works The list itself doesn't have a name. You need to pass in both the name and the list: def savedata(name, data): .. savedata(x, x) -- http://mail.python.org/mailman/listinfo/python-list
Couple of noobish question
Quoth Catherine Heathcote catherine.heathc...@gmail.com: all goes well. I have an idea for a small project, an overly simplistic interactive fiction engine (well more like those old choose your own adventure books, used to love those!) that uses XML for its map files. The main issues I see so far is the XML parsing (I should pick that up ok, I have a blackbelt in google-foo), but more importantly splitting Others have answered your other question, but I thought I'd mention that you will probably want to take a look at the ElementTree module. --RDM -- http://mail.python.org/mailman/listinfo/python-list
Running CVSNT commands from python to Automate the job
Hi All, i want to automate my task for of doing cvs checkout for different modules. I am on Windows XP and i am using Python 2.6. here is my attched python code. The thing is when i am running this nothing is happening. I am not sure at which end the problem is. am i giving wrong parameters or what? any help or pointers to write directions will be helpfull. CVS_PATH='C:\Program Files\CVSNT\cvs.exe' CVS_PATH=(os.sep).join(CVS_PATH.split('\\')) BRANCH_NAME='B_PKG14_01' ''' Filters the directories only from the list of files and directories excluding the directories starting with name '.' @param dirList=List of all the files and directories @param basePath=path where we are doing our filtering ''' def filterDir(dirList,basePath): import os temp=[] for data in dirList: #if(data[0]!='.'): mydir=os.path.join(basePath,data) flag=os.path.isdir(mydir) if(flag==True): temp.append(mydir) return temp def main(): import os curr_dir=os.getcwd()#current working directory curr_list=os.listdir(curr_dir)#list of all files and directories in current working directory global CVS_PATH,BRANCH_NAME temp=filterDir(curr_list,curr_dir) for mydir in temp: dir_name=os.path.split(mydir)[1] #os.rmdir(mydir) CVS_COMMAND='checkout -r '+BRANCH_NAME+' -P '+dir_name print ''+CVS_PATH+''+' -q '+CVS_COMMAND main() thanks, sandeep -- http://mail.python.org/mailman/listinfo/python-list
Re: Added-value of frameworks?
Matimus mccre...@gmail.com writes: On Feb 4, 8:08 am, Gilles Ganault nos...@nospam.com wrote: Hello If I wanted to build some social web site such as Facebook, what do frameworks like Django or TurboGears provide over writing a site from scratch using Python? Thank you for your feedback. Why not just look at the frameworks themselves and see what they have to offer. Django and Turbogears both have pretty good tutorials. You can be up and running in 20 minutes with each one. You be the judge. The frameworks provide a lot of boilerplate code that I would rather not write. They are probably more secure and scalable than something I would come up with. You also get many extras for free. I think in both of the frameworks you mention you get an administrative back end for free. Other people have created apps/plugins that you can use with those frameworks. So, for example, you might be able to borrow the code to help you add a forum to your site. I'm not sure I know the advantage of not using a framework. Unless I get to write more code is an advantage. Creating your own framework might be fun, but if you really just want a website don't do more work than you need to. Matt In other words, it boils down to what you get paid to do. If you're being paid for a frob (the product, in this case a website) then you use a frob-maker (a framework). If you're being paid to make frobs, then you make the frob-maker. Most frob-makers are good at producing frobs of a certain kind. Just choose the frob-maker that makes the frobs you need. In rare circumstances you'll need a really customized frob. Call on me when you get there. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
En Wed, 04 Feb 2009 12:38:04 -0200, Pat p...@junk.net escribió: Andreas Waldenburger wrote: On Sat, 31 Jan 2009 13:27:02 -0500 Pat p...@junk.net wrote: Tobiah wrote: Just out of curiosity, why was len() made to be it's own function? I often find myself typing things like my_list.len before I catch myself. I'm surprised that no one responded to that question. Huh? Gabriel Genellina replied about 46 minutes after it was posted. Might it be that your newsserver is a bit laggy? Might be laggy. Who knows. Why didn't you answer the len() question? Why should he? Why didn't you look for the answer yourself, after being told that it existed? Why do you expect *us* to repeat ourselves again and again? Don't be so lazy... You can read all these posts using the mailing list (python-list@python.org), Usenet (comp.lang.python), Google Groups, and many other mirrors. See this same thread in 3 different ways: Google groups: http://groups.google.com/group/comp.lang.python/t/247ec641c289a326/ Gmane: http://permalink.gmane.org/gmane.comp.python.general/608346 Python.org: http://mail.python.org/pipermail/python-list/2009-January/526500.html and many others, like the forum look feel provided by www.velocityreviews.com -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
En Wed, 04 Feb 2009 07:05:22 -0200, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid escribió: Gabriel Genellina a écrit : En Mon, 02 Feb 2009 19:51:11 -0200, Russ P. russ.paie...@gmail.com escribió: Suppose a library developer (or a module developer on a large team) uses leading underscores. Now suppose that, for whatever reason (pressure from the users, perhaps), the library developer decides to change a private attribute to public. Now all occurrences of the identifier need to be changed. If an assignment to the previously private attribute is missed, no warning will be issued (because Python allows new attributes to be added anywhere, even completely outside the class definition itself). And if the library is widely used, the probability of such bugs occurring is very high. So _foo becomes foo. Then: class X(object): def get_foo(self): return self._foo def set_foo(self, value): self._foo = value foo = property(get_foo, set_foo) FWIW, if there's no other need for the property, I'd do it the other way round : directly make foo a plain attribute, and add a _foo property whose accessors would raise a deprecation warning. Then there's no chance I miss a an assignement to _foo !-) Yes, that would be better. In any case, one has both static analysis tools (e.g. pylint) and dynamic warnings (like you said above) so I don't see a problem here. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Hendrik van Rooyen wrote: Scott David Daniels s..@acm.org wrote: You might enjoy looking at QNX, since I think it is built along the lines you are describing here. I have an ancient copy of their OS, but haven't followed for more than couple of decades. I vaguely know about it, and I know they claim to be hot on real time stuff. I have never pursued it in any depth because of the real tiny nature of the processors I have been working with (8031). When I had a cursory look at it a long time ago, it seemed to be almost unix like in its make up, and I doubted that I could persuade it to run on of them. (I may be dead wrong of course - I don't know) I will put it on my list of stuff to try to get done. Slightly OT: QNX was open-sourced, at least for non-commercial use, a little more that a year ago. So it might be worth a new look. -- http://mail.python.org/mailman/listinfo/python-list
Re: len()
Pat wrote: Andreas Waldenburger wrote: On Sat, 31 Jan 2009 13:27:02 -0500 Pat p...@junk.net wrote: Tobiah wrote: Just out of curiosity, why was len() made to be it's own function? I often find myself typing things like my_list.len before I catch myself. Thanks, Toby I'm surprised that no one responded to that question. Huh? Gabriel Genellina replied about 46 minutes after it was posted. Might it be that your newsserver is a bit laggy? regards /W Might be laggy. Who knows. Why didn't you answer the len() question? I didn't respond because it has been asked and answered before, so the answer can be found in the google archives or even maybe the FAQ. -- http://mail.python.org/mailman/listinfo/python-list
sys.float_info.epsilon
I'm reading Mark Summerfield's Programming Python 3.0 at the moment, and I'm puzzled by some of his uses of sys.float_info.epsilon. I appreciate the issues of comparing floating point numbers, but I'm puzzled by code like: ... x = float(input(msg)) if abs(x) sys.float_info.epsilon: ... What could the float() conversion return that would give different results for: if abs(x) sys.float_info.epsilon and (to my mind, more obvious): if abs(x) == 0.0 I didn't realise that float() could return anything with an absolute value less than sys.float_value.epsilon other than 0.0 (which I think all representations can represent exactly). What am I missing here? -- Tim Rowe -- 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: Tkinter
Luke wrote: 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: ... from Tkinter import * def MainWin(): main=Tk() ... close_frame1=Button(frame1,text='close',bg='light gray', command=frame1.destroy) close_frame1.pack_propagate(0) close_frame1.pack(side=TOP, anchor=N,pady=25) if frame1.destroy==True: frame1=Frame(back_ground,width=213,height=480,bg='white') frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) main.mainloop() MainWin() It may just be bad coding but either way I could use some help. I'll tell you what I find helps me in exploring Tkinter: running Idle in the no-subprocesses mode. Now the resulting system _is_ less stable and may well require you to restart from time to time, but there is a compensation: you can see the effect of each operation as you do it by hand, as well as checking expressions: If in Windows: run cmd C:\ python -m idlelib.idle -n If in Linux / MacOSx: Start a terminal: $ python -m idlelib.idle -n Once idle shows up, import Tkinter main = Tkinter.Tk() a window shows up ... Following through your code, you'll see you start the frame, add the button, and, immediately after getting everything set up, you check: if frame1.destroy==True: Which it will never be (frame1.destroy is a method, not data). Once you get the base set up, your code should runfrom events. So, to get a single step farther: At the top of the MainWin function, insert: global frame1, close_frame1 Replace your close_frame1 = line down to end-o-function with: def on_click(): global frame1, close_frame1 frame1.destroy() frame1 =Frame(back_ground,width=213,height=480,bg='white') frame1.pack_propagate(0) frame1.pack(side=TOP,anchor=N) close_frame1 = Button(frame1,text='retry', bg='light blue', command=on_click) close_frame1.pack_propagate(0) close_frame1.pack(side=TOP, anchor=N,pady=25) close_frame1 = Button(frame1,text='close',bg='light gray', command=on_click) close_frame1.pack_propagate(0) close_frame1.pack(side=TOP, anchor=N,pady=25) The global lines are needed so that on_click and MainWin (which both set the two names) are talking about the same objects. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: x64 speed
Is it the x64 working faster at its design sizes Another guess (still from the darkness of not having received the slightest clue what the test actually does): if it creates integers in range(2**32, 2**64), then they fit into a Python int on AMD64-Linux, but require a Python long on 32-bit Windows; long operations are much slower than int operations. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
On Feb 4, 3:11 am, Bruno Desthuilliers bruno. 42.desthuilli...@websiteburo.invalid wrote: thmpsn@gmail.com a écrit : On Feb 3, 1:14 am, David Cournapeau courn...@gmail.com wrote: (snip) after all, we have used FILE* for years and I have no idea about the FILE structure. Your lack of knowledge about it doesn't mean that it has somehow magically private members. The only reason that most of us don't know what a FILE is is that it's definition is implementation-defined (i.e., every compiler may define it differently). That doesn't have anything to do with private members. For example, on my system, stdio.h defines FILE as: struct _iobuf { char *_ptr; int _cnt; char *_base; int _flag; int _file; int _charbuf; int _bufsiz; char *_tmpfname; }; Didn't you notice kind of a pattern here ? You mean the leading underscores? I don't think they're used for the same purpose as in Python. In C/C++, identifiers that begin with an underscore are reserved (at least at the outer level). Thus, if the member '_ptr' would instead be named 'ptr', something like this would break things: #define ptr // OOPS!! #include stdio.h That shouldn't happen with '_ptr', since programs are not supposed to define those kinds of names (yeah, right). typedef struct _iobuf FILE; Given this information, nothing prevents me from writing things like: FILE* fp = fopen(file.txt, r); if (!fp) { /* do something */ } printf(fp-_cnt = %d\n, fp-cnt); printf(fp-_flag = %d\n, fp-_flag); printf(fp-_file = %d\n, fp-_file); fp-_flag = 0x20; // OOPS!! Indeed - and that's exactly the point : nothing prevents you from accessing the implementation, *and yet, you don't* I sure don't, but I still *can*. CHAOS MAY ENSUE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.float_info.epsilon
Tim Rowe wrote: I'm reading Mark Summerfield's Programming Python 3.0 at the moment, and I'm puzzled by some of his uses of sys.float_info.epsilon. I appreciate the issues of comparing floating point numbers, but I'm puzzled by code like: ... x = float(input(msg)) if abs(x) sys.float_info.epsilon: ... What could the float() conversion return that would give different results for: if abs(x) sys.float_info.epsilon and (to my mind, more obvious): if abs(x) == 0.0 I didn't realise that float() could return anything with an absolute value less than sys.float_value.epsilon other than 0.0 (which I think all representations can represent exactly). What am I missing here? You are missing the whole thing that mes floating point tricky. I _believe_ that the epsilon is the smallest positive x such that 1.0 != 1.0 + x That doesn't mean that x is the smallest representable. for example, .0125 + epsilon / 4 != .0125 To avoid using epsilon, do something like: if 1 + abs(x) != 1: To learn a bit more, look into numerical analysis -- there is a whole field dedicated to figuring out how to make floating point behave a little bit like real numbers. The reason it is tough is that addition is not associative in real numbers, and associativity is at the core of a lot of proofs in arithmetic (and group theory). --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.float_info.epsilon
On Feb 4, 7:18 pm, Tim Rowe digi...@gmail.com wrote: I didn't realise that float() could return anything with an absolute value less than sys.float_value.epsilon other than 0.0 (which I think all representations can represent exactly). What am I missing here? There are many positive floating-point values smaller than sys.float_info.epsilon. sys.float_info.epsilon is defined as the difference between 1.0 and the next largest representable floating-point number. On your system, the next largest float is almost certainly 1 + 2**-52, so sys.float_info.epsilon will be exactly 2**-52, which is around 2.2e-16. This number is a good guide to the relative error from rounding that you can expect from a basic floating-point operation. The smallest positive floating-point number is *much* smaller: again, unless you have a very unusual platform, it's going to be 2**-1074, or around 4.9e-324. In between 2**-1074 and 2**-52 there are approximately 4.4 million million million different floating-point numbers. Take your pick! If you want a specific example, how about float('6.626e-34'). Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Using lxml to screen scrap a site, problem with charset
Tim Arnold wrote: ?? ??? gdam...@gmail.com wrote in message news:ciqh56-ses@archaeopteryx.softver.org.mk... So, I'm using lxml to screen scrap a site that uses the cyrillic alphabet (windows-1251 encoding). The sites HTML doesn't have the META ..content-type.. charset=.. header, but does have a HTTP header that specifies the charset... so they are standards compliant enough. Now when I run this code: from lxml import html doc = html.parse('http://a1.com.mk/') root = doc.getroot() title = root.cssselect(('head title'))[0] print title.text the title.text is ? unicode string, but it has been wrongly decoded as latin1 - unicode The way I do that is to open the file with codecs, encoding=cp1251, read it into variable and feed that to the parser. Yes, if you know the encoding through an external source (especially when parsing broken HTML), it's best to pass in either a decoded string or a decoding file-like object, as in tree = lxml.html.parse( codecs.open(..., encoding='...') ) You can also create a parser with an encoding override: parser = etree.HTMLParser(encoding='...', **other_options) Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.float_info.epsilon
On Feb 4, 7:52 pm, Scott David Daniels scott.dani...@acm.org wrote: You are missing the whole thing that mes floating point tricky. I _believe_ that the epsilon is the smallest positive x such that 1.0 != 1.0 + x Nitpick alert: this isn't quite the same thing, since that definition is affected by rounding. For example, if you're using IEEE 754 doubles but (somehow) you've got a round-half-up rounding mode then this makes epsilon 2**-53 rather than 2**-52, because 1 + 2**-53 rounds to 1 + 2**-52 != 1. (This confused the hell out of me many years ago when I was reading Numerical Recipes, and trying to figure out why on earth IEEE 754 and the VAX format had different epsilons even though both had 53-bit mantissas. The answer is that IEEE 754 uses round-half-even as standard, and VAX uses round-half-up. Oh, and the authors of Numerical Recipes used the 1 != 1+x definition...) Python's float_info.epsilon comes straight from C's DBL_EPSILON, which is defined very carefully in the C99 standard as: the difference between 1 and the least value greater than 1 that is representable in the given floating point type (taking the 'given floating point type' to be double). Mark -- http://mail.python.org/mailman/listinfo/python-list
how to compile in jython 2.5b1??
I have to use jython 2.5b1 couse with the stable version it's not possible to use sympy library for mathematic operation but the jythonc.bat it's not included. I look to this link: http://www.jython.org/Project/jythonc.html ..jythonc is unmaintained and will not be present in its current form in Jython 2.5... so what can I do?? thank you for the answer!! -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.float_info.epsilon
Tim Rowe wrote: I'm reading Mark Summerfield's Programming Python 3.0 at the moment, and I'm puzzled by some of his uses of sys.float_info.epsilon. I appreciate the issues of comparing floating point numbers, but I'm puzzled by code like: ... x = float(input(msg)) if abs(x) sys.float_info.epsilon: ... What could the float() conversion return that would give different results for: if abs(x) sys.float_info.epsilon and (to my mind, more obvious): if abs(x) == 0.0 I didn't realise that float() could return anything with an absolute value less than sys.float_value.epsilon other than 0.0 (which I think all representations can represent exactly). What am I missing here? epsilon is the difference between *1.0* and the next smallest number in the representation. It seems pretty obvious that the smallest representable number will be way smaller than that. To me, at least. Think about the representation of 1. + epsilon - the mantissa will have a leading 1, then all zeros but for a trailing 1, and the exponent will effectively be 0. For numbers close to zero the exponent will have a large negative effective value (exponents are usually stored as biased positive numbers), and so the smallest value will be tiny compared with epsilon. Though it's a long time since I did my numerical analysis, and it isn't clear to me exactly what the test *is* supposed to do. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: [Web 2.0] Added-value of frameworks?
They provide a nice framework that will handle most of the annoying things. With Django you don't need to write SQL (in a sense). etc.. On Wed, Feb 4, 2009 at 6:08 PM, Gilles Ganault nos...@nospam.com wrote: Hello If I wanted to build some social web site such as Facebook, what do frameworks like Django or TurboGears provide over writing a site from scratch using Python? Thank you for your feedback. -- http://mail.python.org/mailman/listinfo/python-list -- http://www.goldwatches.com/ http://www.jewelerslounge.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Russ P. russ.paie...@gmail.com writes: Imagine you own a company, and you decide to lease an office building. Would you expect the office doors to have locks on them? Oh, you would? Why? You mean you don't trust your co-workers? What are locks but enforced access restriction? Huh? The lock on the door isn't to keep the coworkers out. It's to let them /in/ while keeping everyone else out. So I don't really see the analogy. Or are you talking about the individual offices? If so, then I'd expect the locks to be /used/ only under rather unusual circumstances. If someone in the office has something to hide, I think that's rather suspicious, actually... -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Upgrade 2.6 to 3.0
I am fairly new to Python, the first version I loaded was 2.6. I have since downloaded 3.0 and I was wondering what the best practice for upgrading is? I am using Windows XP Pro for my OS. Thanks, Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: Upgrade 2.6 to 3.0
joviyach wrote: I am fairly new to Python, the first version I loaded was 2.6. I have since downloaded 3.0 and I was wondering what the best practice for upgrading is? I am using Windows XP Pro for my OS. On Windows, X.Y.* all go in one directory (over-riding each other) So the whole 2.6.* family should work just fine alongside the 3.0.* family. In just a bit, 3.0.1 is coming soon, correcting some problems in 3.0, so if you do install 3.0, check in a few weeks for an update. The 2 - 3 change was pretty substantial, so it will be a bit until the 3.0 line gets lots of outside packages. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: is python Object oriented??
Steven D'Aprano ste...@remove.this.cybersource.com.au writes: Now, that's a toy example. Languages like Ada make correctness proofs, well, perhaps not easy, but merely difficult compared to impossible for languages like Python. Say `generally impractical' rather than `impossible' and I'll agree with you. But I'm not actually sure that the situation for Python with respect to correctness proofs is significantly harder than it is for C. Certainly Ada (or at least dialects of Ada) have features which make proof-supporting tools easier; I'm not aware of such proof support for other languages. Actually, if you're starting from a formal specification in Z, say, and implementing in Python, well, the Z checker will already have ensured that your specification is well typed; your proof that the implementation follows the specification will automatically contain a well-typed-ness proof of your implementation regardless of whether the compiler provides static verification. To bring it back to private/public attributes, side-effects make correctness proofs difficult. Modifications of attributes are side- effects. When attributes are subject to being modified by arbitrary code, it is harder to reason about the correctness of the code: class Inverter(object): def __init__(self, x): # Pre-condition: x is always a float if x: self.x = x else: raise ValueError(x must not be zero) # Post-condition: if self.x exists, it is a non-zero float def invert(self): return 1.0/self.x Is method invert correct? I'd argue that it isn't, and in fact that the specification is wrong. In particular, it ought to be a precondition that x is nonzero. At this point you can dump the explicit check at the cost of imposing a proof obligation on the caller. No, it is not, because the invariant that self.x is non-zero may have been broken by some arbitrary piece of code elsewhere. It's not stated as an invariant. It's stated as a post-condition, which is indeed true (almost[1]) regardless of the behaviour of other parts of the program. [1] A subclass may have already set self.x before invoking Inverter.__init__. If you explicitly `del self.x' before raising the exception, the subclass can still defeat you by passing the reference to the half-constructed object to another thread which mutates the object at an inconvenient time. I mention all of this merely to avoid pedantry in follow-ups. I'd also argue that maintaining the invariant about self.x is the responsibility of code that messes with self.x, and therefore it is /legitimate/ to modify self.x from external code which maintains the invariant. Our ability to reason about the correctness of the code is weakened significantly. Sticking an underscore in front of x does not help: there's nothing to stop some arbitrary function elsewhere changing _x to zero. Dichotomy for you. * EITHER the other code is written to the same high standards, in which case it will come with appropriate specifications, preconditions, postconditions, invariants and proofs for whatever it does, even -- especially -- if it involves grubbily messing about with your module's innards (so everything is fine); * OR the other code doesn't meet your high standards, in which case all bets are off anyway, from the point of view of formal-methods types at any rate (so you can wash your hands of the whole affair). (1) Paranoia. Make the developer responsible for checking everything all the time: [...] (2) Hope the error never occurs, and if it does, let the caller deal with it. [...] There is a third strategy, sadly not available to Python programmers: prevention by catching potential errors at compile-time. Four: Describe your interface clearly, specify the behaviour of functions and so on; and leave whoever messes with your module with the task of proving -- to whatever level of formality is required by their project -- that what they've done is sane and reasonable. In fact, since whatever one does in a project should be held to this standard, whether it involves grubbing about inside undocumented internals or not, there's nothing particularly special about this case. Good job, really, since Python doesn't distinguish either. ;-) -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to compile in jython 2.5b1??
pellegrin...@gmail.com schrieb: I have to use jython 2.5b1 couse with the stable version it's not possible to use sympy library for mathematic operation but the jythonc.bat it's not included. I look to this link: http://www.jython.org/Project/jythonc.html ..jythonc is unmaintained and will not be present in its current form in Jython 2.5... so what can I do?? thank you for the answer!! What do you need jythonc for? That's purely for a somewhat neater integration of *Java* with jython - nothing to do with sympy. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Where how to deallocate resources in Python C extension
fredbasset1...@gmail.com writes: I've written a C extension, see code below, to provide a Python interface to a hardware watchdog timer. As part of the initialization it makes some calls to mmap, I am wondering should I be making balanced calls to munmap in some kind of de-init function? The kernel should remove the mapping when your process exits anyway -- otherwise the world would be left in an inconsistent state if your process got killed by SIGKILL for example. Do Python extensions have d'tors? No. But you can cheat: stash some object whose tp_del slot does your cleanup in your extension's module under some funny name. (And woe betide anyone who dels the funny name prematurely!) I'm not sure I'd bother. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: structs
Scott David Daniels scott.dani...@acm.org writes: To avoid using epsilon, do something like: if 1 + abs(x) != 1: An OK effort, but you're wrong. That's not how to do it at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to compile in jython 2.5b1??
What do you need jythonc for? That's purely for a somewhat neater integration of *Java* with jython - nothing to do with sympy. Diez I need jythonc to compile a simple script in java, this script import SymPy library. thank you ruelle -- http://mail.python.org/mailman/listinfo/python-list
Re: JDBC in CPYTHON
On 2009-02-03 19:30, KMCB wrote: I was wondering if anyone was aware of a JDBC DBAPI module for cpython. I have looked at PYJDBC and was interested in avoiding using that extra level of ICE. I was thinking maybe someone would have back ported zxJDBC from Jython. Or used that as a starting point, to create a module and had a C based wrapper for the driver. This type of activity was talked about back in 2004 on this forum, but I was wondering if anyone had newer information. Why not use ODBC instead ? http://www.egenix.com/products/python/mxODBC/ (zxJDBC is based on and was inspired by mxODBC) Or, if you don't have ODBC drivers for your database, use an ODBC-JDBC bridge such as: http://www.easysoft.com/products/data_access/odbc_jdbc_gateway/ or http://odbcjdbc.sourceforge.net/ -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 04 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: structs
Gary Herron gher...@islandtraining.com writes: Python *is* object-oriented I disagree. Care to provide proof of that statement? -- http://mail.python.org/mailman/listinfo/python-list
Re: x64 speed
On 2009-02-04 11:14, Robin Becker wrote: Martin v. Löwis wrote: I follow David's guess that Linux does better IO than Windows (not knowing anything about the benchmark, of course) I originally thought it must be the vmware host stuff offloading IO to the second core, but watching with sysinternals didn't show a lot of extra stuff going on with the vm compared to just running on the host. I'm not talking about vmware. I'm suggesting that Linux ext3, and the Linux buffer handling, is just more efficient than NTFS, and the Windows buffer handling. If you split the total runtime into system time and user time, how do the 30s split up? ... so here is one for the vm clock is bad theorists :) [rpt...@localhost tests]$ time python25 runAll.py . . -- Ran 193 tests in 27.841s OK real0m28.150s user0m26.606s sys 0m0.917s [rpt...@localhost tests]$ magical how the total python time is less than the real time. time(1) also measures the Python startup and shutdown time, so I don't quite see the magic :-( FWIW: VMware VMs need the VMware tools installed to make their clocks work more or less. With Linux, you need some extra tweaks as well, otherwise the clocks are just completely unreliable. See these notes: http://kb.vmware.com/selfservice/viewContent.do?language=en_USexternalId=1420 http://communities.vmware.com/message/782173 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 04 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Kill a function while it's being executed
Noam Aigerman no...@answers.com writes: About the hijacking - I *might* have done it without understanding what I did (replied to a previous message and then changed the subject), if that's what you mean... Right. The message still declares itself (via fields in the header) to be a reply to the original, regardless of the subject change. If your reply actually has no bearing on the original, then that's what is known as hijacking a thread. To start a new thread, you need to compose a new message to the forum. -- \ “[Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself.” —_Hocus Pocus_, Kurt | _o__) Vonnegut | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Unzipping a .zip properly, and from a remote URL
On 2009-02-03 15:32, Tino Wildenhain wrote: Christopher Culver wrote: Tino Wildenhain t...@wildenhain.de writes: so instead you would use archive = zipfile.ZipFile(remotedata) That produces the following error if I try that in the Python interpreter (URL edited for privacy): import zipfile import urllib2 remotedata = urllib2.urlopen(http://...file.zip;) archive = zipfile.ZipFile(remotedata) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.5/zipfile.py, line 346, in __init__ self._GetContents() File /usr/lib/python2.5/zipfile.py, line 366, in _GetContents self._RealGetContents() File /usr/lib/python2.5/zipfile.py, line 376, in _RealGetContents endrec = _EndRecData(fp) File /usr/lib/python2.5/zipfile.py, line 133, in _EndRecData fpin.seek(-22, 2) # Assume no archive comment. AttributeError: addinfourl instance has no attribute 'seek' Try this: import urllib, zipfile, cStringIO zipwebfile = urllib.urlopen('http://downloads.egenix.com/python/locale-0.1.zip') buffer = cStringIO.StringIO(zipwebfile.read()) zfile = zipfile.ZipFile(buffer) zfile.printdir() File Name Modified Size locale/Makefile.pre.in 1997-10-31 21:13:06 9818 locale/Setup.in1997-10-31 21:14:04 74 locale/locale.c1997-11-19 17:36:46 4698 locale/CommandLine.py 1997-11-19 15:50:02 2306 locale/probe.py1997-11-19 15:51:18 1870 locale/__init__.py 1997-11-19 17:55:020 The trick is to use a StringIO buffer to provide the .seek() method. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 04 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list