Re: What is different with Python ?
On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith [EMAIL PROTECTED] wrote: How far down do you have to go? What makes bytes of memory, data busses, and CPUs the right level of abstraction? They're things that can be IMO genuinely accept as obvious. Even counting is not the lowest level in mathematic... there is the mathematic philosohy direction. From counting you can go up in the construction direction (rationals, reals, functions, continuity and the whole analysis area) building on the counting concept or you can go down asking yourself what it does really mean counting, what do you mean with a proof, what really is a set. However the counting is naturally considered obvious for our minds and you can build the whole life without the need to look at lower levels and without getting bitten too badly for that simplification. Also lower than memory and data bus there is of course more stuff (in our universe looks like there is *always* more stuff no mattere where you look :-) ), but I would say it's more about electronic than computer science. Why shouldn't first-year CS students study how a computer works at the level of individual logic gates? After all, if you don't know how gates work, things like address bus decoders, ALUs, register files, and the like are all just magic (which you claim there is no room for). It's magic if I'm curious but you can't answer my questions. It's magic if I've to memorize because I'm not *allowed* to understand. It's not magic if I can (and naturally do) just ignore it because I can accept it. It's not magic if I don't have questions because it's for me obvious enough. Also concrete-abstract shows a clear path; starting in the middle and looking both up (to higher abstractions) and down (to the implementation details) is IMO much more confusing. At some point, you need to draw a line in the sand (so to speak) and say, I understand everything down to *here* and can do cool stuff with that knowledge. Below that, I'm willing to take on faith. I suspect you would agree that's true, even if we don't agree just where the line should be drawn. You seem to feel that the level of abstraction exposed by a language like C is the right level. I'm not convinced you need to go that far down. I'm certainly not convinced you need to start there. I think that if you don't understand memory, addresses and allocation and deallocation, or (roughly) how an hard disk works and what's the difference between hard disks and RAM then you're going to be a horrible programmer. There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. If those are magic formulas you'll just forget them and you'll end up writing code that is thousands times slower than necessary. If you don't understand *why* C needs malloc then you'll forget about allocating objects. Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: count string replace occurances
Jeff Epler wrote: On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote: if i have mytext.replace(a,b) how to find out many many occurances has been replaced? The count isn't returned by the replace method. You'll have to count and then replace. def count_replace(a, b, c): count = a.count(b) return count, s.replace(b, c) count_replace(a car and a carriage, car, bat) (2, 'a bat and a batriage') I thought naively that scanning a long string twice would be almost twice as slow compared to when counting was done along with replacing. Although it can done with a single scan, it is almost 9-10 times slower, mainly because of the function call overhead; the code is also longer: import re def count_replace_slow(aString, old, new): count = [0] def counter(match): count[0] += 1 return new replaced = re.sub(old,counter,aString) return count[0], replaced A good example of trying to be smart and failing :) George -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Sun, 12 Jun 2005 19:53:29 -0500, Mike Meyer [EMAIL PROTECTED] wrote: Andrea Griffini [EMAIL PROTECTED] writes: On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen [EMAIL PROTECTED] wrote: Also concrete-abstract shows a clear path; starting in the middle and looking both up (to higher abstractions) and down (to the implementation details) is IMO much more confusing. So you're arguing that a CS major should start by learning electronics fundamentals, how gates work, and how to design hardware(*)? Because that's what the concrete level *really* is. Start anywhere above that, and you wind up needing to look both ways. Not really. Long ago I've drawn a line that starts at software. I think you can be a reasonable programmer even without the knowledge about how to design hardware. I do not think you can be a reasonable programmer if you never saw assembler. Admittedly, at some level the details simply stop mattering. But where that level is depends on what level you're working on. Writing Python, I really don't need to understand the behavior of hardware gates. Writing horizontal microcode, I'm totally f*cked if I don't understand the behavior of hardware gates. But you better understand how, more or less, your computer or language works, otherwise your code will be needless thousand times slower and will require thousand times more memory than is necessary. Look a recent thread where someone was asking why python was so slow (and the code contained stuff like if x in range(low, high): in an inner loop that was itself pointless). In short, you're going to start in the middle. I've got bad news for you. You're always in the middle :-D. Apparently it looks like this is a constant in our universe. Even counting (i.e. 1, 2, 3, ...) is not the start of math (you can go at lower levels). Actually I think this is a nice property of our universe, but discussing this would bring the discussion a bit OT. Is it really justified to confuse them all by introducing what are really extraneous details early on? I simply say that you will not able to avoid introducing them. If they're going to write software those are not details that you'll be able to hide behind a nice and perfect virtual world (this is much less true about bus cycles... at least for many programmers). But if you need to introduce them, then IMO is way better doing it *first*, because that is the way that our brain works. You cannot build on loosely placed bricks. You've stated your opinion. Personally, I agree with Abelson, Sussman and Sussman, whose text The Structure and Interpretation of Computer Programs was the standard text at one of the premiere engineering schools in the world, and is widely regarded as a classic in the field: they decided to start with the abstract, and deal with concrete issues - like assignment(!) later. Sure. I know that many think that starting from higher levels is better. However no explanation is given about *why* this should work better, and I didn't even see objective studies about how this approach pays off. This is of course not a field that I've investigated a lot. What I know is that every single competent programmer I know (not many... just *EVERY SINGLE ONE*) started by placing firmly concrete concepts first, and then moved on higher abstractions (for example like structured programming, OOP, functional languages ...). Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
They're things that can be IMO genuinely accept as obvious. Even counting is not the lowest level in mathematic... there is the mathematic philosohy direction. I am personally highly interested in become aware of the very bottom, the fundaments all our knownledge is build on. Trying to answer questions like: What are the most basic ideas all other are derived from in mathematics and programming? keeps me busy for hours, days, years ... Any insights you can share with me(and/or this group)? Claudio Andrea Griffini [EMAIL PROTECTED] schrieb im Newsbeitrag news:[EMAIL PROTECTED] On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith [EMAIL PROTECTED] wrote: How far down do you have to go? What makes bytes of memory, data busses, and CPUs the right level of abstraction? They're things that can be IMO genuinely accept as obvious. Even counting is not the lowest level in mathematic... there is the mathematic philosohy direction. From counting you can go up in the construction direction (rationals, reals, functions, continuity and the whole analysis area) building on the counting concept or you can go down asking yourself what it does really mean counting, what do you mean with a proof, what really is a set. However the counting is naturally considered obvious for our minds and you can build the whole life without the need to look at lower levels and without getting bitten too badly for that simplification. Also lower than memory and data bus there is of course more stuff (in our universe looks like there is *always* more stuff no mattere where you look :-) ), but I would say it's more about electronic than computer science. Why shouldn't first-year CS students study how a computer works at the level of individual logic gates? After all, if you don't know how gates work, things like address bus decoders, ALUs, register files, and the like are all just magic (which you claim there is no room for). It's magic if I'm curious but you can't answer my questions. It's magic if I've to memorize because I'm not *allowed* to understand. It's not magic if I can (and naturally do) just ignore it because I can accept it. It's not magic if I don't have questions because it's for me obvious enough. Also concrete-abstract shows a clear path; starting in the middle and looking both up (to higher abstractions) and down (to the implementation details) is IMO much more confusing. At some point, you need to draw a line in the sand (so to speak) and say, I understand everything down to *here* and can do cool stuff with that knowledge. Below that, I'm willing to take on faith. I suspect you would agree that's true, even if we don't agree just where the line should be drawn. You seem to feel that the level of abstraction exposed by a language like C is the right level. I'm not convinced you need to go that far down. I'm certainly not convinced you need to start there. I think that if you don't understand memory, addresses and allocation and deallocation, or (roughly) how an hard disk works and what's the difference between hard disks and RAM then you're going to be a horrible programmer. There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. If those are magic formulas you'll just forget them and you'll end up writing code that is thousands times slower than necessary. If you don't understand *why* C needs malloc then you'll forget about allocating objects. Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Sun, 12 Jun 2005 21:52:12 -0400, Peter Hansen [EMAIL PROTECTED] wrote: I'm curious how you learned to program. An HP RPN calculator, later TI-57. Later Apple ][. With Apple ][ after about one afternoon spent typing in a basic program from a magazine I gave up with basic and started with 6502 assembler (call -151 was always how I started my computer sessions). What path worked for you, and do you think it was a wrong approach, or the right one? I was a fourteen with no instructor, when home computers in my city could be counted on the fingers of one hand. Having an instructor I suppose would have made me going incredibly faster. Knowing better the english language at that time would have made my life also a lot easier. I think that anyway it was the right approach in terms of path, not the (minimal energy) approach in terms of method. Surely a lower energy one in the long run comparing to those that started with basic and never looked at lower levels. In my case, I started with BASIC. Good old BASIC, with no memory management to worry about, no pointers, no concrete details, just FOR loops and variables and lots of PRINT statements. That's good as an appetizer. A while (some months) later I stumbled across some assembly language and -- typing it into the computer like a monkey, with no idea what I was dealing with -- began learning about some of the more concrete aspects of computers. That is IMO a very good starting point. Basically it was the same I used. This worked very well in my case, and I strongly doubt I would have stayed interested in an approach that started with talk of memory addressing, bits and bytes, registers and opcodes and such. I think that getting interested in *programming* is important... it's like building with LEGOs, but at a logical level. However that is just to get interest... and a few months with basic is IMO probably too much. But after you've a target (making computers do what you want) then you've to start placing solid bricks, and that is IMO assembler. Note that I think that any simple assembler is OK... even if you'll end up using a different processor when working in C it will be roughly ok. But I see a difference between those that never (really) saw assembler and those that did. I won't say that I'm certain about any of this, but I have a very strong suspicion that the *best* first step in learning programming is a program very much like the following, which I'm pretty sure was mine: 10 FOR A=1 TO 10: PRINTPeter is great!: END Just as a motivation. After that *FORGETTING* that (for and the next you missed) is IMO perfectly ok. More importantly by far, *I made the computer do something*. Yes, I agree. But starting from basic and never looking lower is quit a different idea. Andrea -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: At some point, you need to draw a line in the sand (so to speak) and say, I understand everything down to *here* and can do cool stuff with that knowledge. Below that, I'm willing to take on faith. I suspect you would agree that's true, even if we don't agree just where the line should be drawn. You seem to feel that the level of abstraction exposed by a language like C is the right level. I'm not convinced you need to go that far down. I'm certainly not convinced you need to start there. The important question is, what are the consequences of that faith when it is mistaken? As a Python developer, I probably won't write better code if I understand how NAND gates work or the quantum mechanics of electrons in solid crystals. But I will write better code if I understand how Python implements string concatenation, implicit conversion from ints to longs, floating point issues, etc. It seems that hardly a day goes by without some newbie writing to the newsgroup complaining that Python has a bug because they have discovered that the floating point representation of 0.1 in decimal is actually more like 0.10001. And let's not forget the number of bugs out there because developers thought that they didn't need to concern themselves with the implementation details of memory management. It makes a difference whether your algorithm runs in constant time, linear, quadratic, logarithmic or exponential time -- or something even slower. The implementation details of the language can hide quadratic or exponential algorithms in something that looks like a linear or constant algorithm. Premature optimization is a sin... but so is unusably slow code. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Andrea Griffini wrote: I think that if you don't understand memory, addresses and allocation and deallocation, or (roughly) how an hard disk works and what's the difference between hard disks and RAM then you're going to be a horrible programmer. There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. There's a crucial distinction between these two scenarios though: the first one has to do with today's hardware and software limitations while the second one expresses fundamental, independent of technology, algorithmic properties. In the not-too-far-future, the difference between RAM and hard disks may be less important than today; hard disks may be fast enough for most purposes, or the storage policy may be mainly decided by the OS, the compiler, the runtime system or a library instead of the programmer (similarly to memory management being increasingly based on garbage collection). As programmers today don't have to know or care much about register allocation, future programmers may not have to care about whether something is stored in memory or in disk. OTOH, an algorithm or problem with exponential complexity will always be intractable for sufficiently large input, no matter how fast processors become. The bottom line is that there is both fundamental and contemporary knowledge, and although one needs to be good at both at any given time, it's useful to distinguish between them. George -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Andrea Griffini [EMAIL PROTECTED] writes: In short, you're going to start in the middle. I've got bad news for you. You're always in the middle :-D. That's what I just said. Is it really justified to confuse them all by introducing what are really extraneous details early on? I simply say that you will not able to avoid introducing them. If they're going to write software those are not details that you'll be able to hide behind a nice and perfect virtual world (this is much less true about bus cycles... at least for many programmers). I disagree. If you're going to make competent programmers of them, they need to know the *cost* of those details, but not necessarily the actual details themselves. It's enough to know that malloc may lead to a context switch; you don't need to know how malloc actually works. But if you need to introduce them, then IMO is way better doing it *first*, because that is the way that our brain works. That's the way *your* brain works. I'd not agree that mine works that way. Then again, proving either statement is an interesting proposition. You've stated your opinion. Personally, I agree with Abelson, Sussman and Sussman, whose text The Structure and Interpretation of Computer Programs was the standard text at one of the premiere engineering schools in the world, and is widely regarded as a classic in the field: they decided to start with the abstract, and deal with concrete issues - like assignment(!) later. Sure. I know that many think that starting from higher levels is better. However no explanation is given about *why* this should work better, and I didn't even see objective studies about how this approach pays off. This is of course not a field that I've investigated a lot. The explanation has been stated a number of times: because you're letting them worry about learning how to program, before they worry about learning how to evaluate the cost of a particular construct. Especially since the latter depends on implementation details, which are liable to have to be relearned for every different platform. What I know is that every single competent programmer I know (not many... just *EVERY SINGLE ONE*) started by placing firmly concrete concepts first, and then moved on higher abstractions (for example like structured programming, OOP, functional languages ...). I don't normally ask how people learned to program, but I will observe that most of the CS courses I've been involved with put aside concrete issues - like memory management - until later in the course, when it was taught as part of an OS internals course. The exception would be those who were learning programming as part of an engineering (but not software engineering) curriculum. The least readable code examples almost uniformly came from the latter group. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
new string function suggestion
What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' The names are analogous to strip, rstrip, and lstrip. But the functionality is basically this: def lchop(self, prefix): assert self.startswith(prefix) return self[len(prefix):] def rchop(self, suffix): assert self.endswith(suffix) return self[:-len(suffix] def chop(self, prefix, suffix): assert self.startswith(prefix) assert self.endswith(suffix) return self[len(prefix):-len(suffix] The assert can be a raise of an appropriate exception instead. I find this to be a very common need, and often newbies assume that the strip/lstrip/rstrip family behaves like this, but of course they don't. I get tired of writing stuff like: if path.startswith('html/'): path = path[len('html/'):] elif s.startswith('text/'): path = path[len('text/'):] It just gets tedious, and there is duplication. Instead I could just write: try: path = path.lchop('html/') path = path.lchop('text/') except SomeException: pass Does anyone else find this to be a common need? Has this been suggested before? Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system
My code is os.system(NET SEND computer hihi) i use this funtion on Windows server 2003. it's ok. But the same code running on Windows XP SP2, it shows the command window twice. How do i remove the command window? Hi, You can remove the command window which comes from python if you use .pyw as extension. This is not an answer why the system method opens a second window, but maybe it helps, too. Thomas Hi, but my program is complied from py2exe. All extension is 'pyd'. Hm... is there any way to do? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Mon, Jun 13, 2005 at 06:13:13AM +, Andrea Griffini wrote: Andrea Griffini [EMAIL PROTECTED] writes: So you're arguing that a CS major should start by learning electronics fundamentals, how gates work, and how to design hardware(*)? Because that's what the concrete level *really* is. Start anywhere above that, and you wind up needing to look both ways. Yep. Probably. Without a basic understanding of hardware design, one cannot many of todays artifacts: Like longer pipelines and what does this mean to the relative performance of different solutions. Or how does one explain that a stupid and slow algorithm can be in effect faster than a clever and fast algorithm, without explaining how a cache works. And what kinds of caches there are. (I've seen documented cases where a stupid search was faster because all hot data fit into the L1 cache of the CPU, while more clever algorithms where slower). So yes, one needs a basic understanding of hardware, so that one can understand the design of assembly. And without knowledge of these you get C programmers that do not really understand what their programs do. (Be it related to calling sequences, portability of their code, etc.) Again you can sometimes see developers that pose questions that suggest that they do not know about the lowlevel. (Example from a current project: Storing booleans in a struct-bit-field so that it's faster. Obviously such a person never seen the code needed to manipulate bit fields on most architectures.) A good C programmer needs to know about assembly, libc (stuff like malloc and friends and the kernel API). Now a good python programmer needs to know at least a bit about the implementation of python. (Be it CPython or Jython). So yes, one needs to know the underlying layers, if not by heart, than at least on a I-know-which-book-to-consult level. Or you get perfect abstract designs, that are horrible when implemented. Not really. Long ago I've drawn a line that starts at software. I think you can be a reasonable programmer even without the knowledge about how to design hardware. Well, IMHO one needs to know at least a bit. But one doesn't need to know it well enough to be able to design hardware by himself. ;) I do not think you can be a reasonable programmer if you never saw assembler. Admittedly, at some level the details simply stop mattering. But where that level is depends on what level you're working on. Writing Python, I really don't need to understand the behavior of hardware Yes. But for example to understand the memory behaviour of Python understanding C + malloc + OS APIs involved is helpful. gates. Writing horizontal microcode, I'm totally f*cked if I don't understand the behavior of hardware gates. But you better understand how, more or less, your computer or language works, otherwise your code will be needless thousand times slower and will require thousand times more memory than is necessary. Look a recent thread where someone was asking why python was so slow (and the code contained stuff like if x in range(low, high): in an inner loop that was itself pointless). Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: new string function suggestion
Andy wrote: What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' Your use case is I get tired of writing stuff like: if path.startswith('html/'): path = path[len('html/'):] elif s.startswith('text/'): path = path[len('text/'):] It just gets tedious, and there is duplication. Instead I could just write: try: path = path.lchop('html/') path = path.lchop('text/') except SomeException: pass But your posted code doesn't implement your use case. Consider if path == html/text/something. Then the if/elif code sets path to text/something while the lchop code sets it to something. One thing to consider is a function (or string method) which is designed around the 'or' function, like this. (Named 'lchop2' but it doesn't give the same interface as your code.) def lchop2(s, prefix): if s.startswith(prefix): return s[len(prefix):] return None path = lchop2(path, html/) or lchop2(path, text/) or path If I saw a function named lchop (or perhaps named lchomp) I would expect it to be (named 'lchomp3' so I can distinguish between it and the other two) def lchop3(s, prefix): if s.startswith(prefix): return s[len(prefix):] return s and not raise an exception if the prefix/suffix doesn't match. Though in this case your use case is not made any simpler. Indeed it's uglier with either newpath = path.lchop3(html/) if newpath == path newpath = path.lchop3(text/) if newpath == path: ... or if path.startswith(html/): path = path.lstrip(html/) elif path.startswith(text/): path = path.lstrip(text/) ... I tried finding an example in the stdlib of code that would be improved with your proposal. Here's something that would not be improved, from mimify.py (it was the first grep hit I looked at) if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' In your version it would be: if prefix: try: line = line.rstrip(prefix) except TheException: pref = '' else: pref = prefix else: pref = '' which is longer than the original. From pickle.py (grepping for 'endswith(' and a context of 2) pickle.py-if ashex.endswith('L'): pickle.py:ashex = ashex[2:-1] pickle.py-else: pickle.py:ashex = ashex[2:] this would be better with my '3' variant, as ashex = ashex.rchop3('L')[2:] while your version would have to be try: ashex = ashex.rchomp('L')[2:] except SomeException: ashex = ashex[2:] Even with my '2' version it's the simpler ashex = (ashex.rchop2('L') or ashex)[2:] The most common case will be for something like this tarfile.py-if self.name.endswith(.gz): tarfile.py-self.name = self.name[:-3] My 3 code handles it best self.name = self.name.rstrip3(.gz) Because your code throws an exception for what isn't really an exceptional case it in essence needlessly requires try/except/else logic instead of the simpler if/elif logic. Does anyone else find this to be a common need? Has this been suggested before? To summarize: - I don't think it's needed that often - I don't think your implementation's behavior (using an exception) is what people would expect - I don't think it does what you expect Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to operate the excel by python?
i want to compare the content in excel,but i don't know whick module to use! can you help me? Read Python programming on Win32 book, use win32api module. According to Chad's advices about Excel (VBA) constants, you can find following link usefull as well. http://fox.wikis.com/wc.dll?Wiki~ExcelConstants~VFP HTH Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic Lists, or...?
# Professional driver on a closed course. # Don't try this at home. data = rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 data = data.replace(', 1, ', ' += ') data = data.replace(', 0, ', ' -= ') class DefaultDict(dict): def __getitem__(self, key): return self.get(key, 0) d = DefaultDict() exec data in {}, d print d.items() -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning more about The Python Way
Kalle Anke wrote: Those who have read my posts today have probably understood that I'm not a true Python programmer ... but I want to learn more (I think that Python is rather fun). I've read Learning Python pretty thoroughly, I've looked at some of the tutorials, some of online documentation, etc. But I still miss a lot of pieces for writing good python code, idioms, advanced usage/features, etc. I've also seen a lot of references to v3, but I haven't found any real documentation of what's planned for that version. So, I'm looking for advice/information on: + How to write proper python code instead of Java/Perl/C/C++/Pascal/Modula-2/etc inspired code + The more advanced parts/uses of Python + Discussions about the ideas behind different Python constructs + What's going to happen with v3 I would really appriciate some pointers to where I can find info about this. Web sites (I've looked at python.org but haven't manage to find the stuff of what I'm looking for ... but perhaps I've missed all the interesting parts) ? Books (I've got 'Learning Python' and 'Programming Python')? Other things? jem latest edition of the Python Cookbook (read a review here http://www.techbookreport.com/tbr0163.html). Also online at ActiveState. -- http://mail.python.org/mailman/listinfo/python-list
Re: new string function suggestion
On Mon, 13 Jun 2005 07:05:39 +, Andy wrote: What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' The names are analogous to strip, rstrip, and lstrip. If chop is analogous to strip, then they shouldn't raise exceptions if the strings do not start with the prefix or suffix. I get tired of writing stuff like: if path.startswith('html/'): path = path[len('html/'):] elif s.startswith('text/'): path = path[len('text/'):] It just gets tedious, and there is duplication. Instead I could just write: Any time you are writing the same piece of code over and over again, you should refactor it out as a function in your module, or even in a special utility functions module: def lchop(s, prefix): if s.startswith(prefix): return s[len(prefix):] raise ValueError(Substring doesn't begin with prefix.) # or just return s if you prefer and then call them whenever you need them. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: count string replace occurances
Xah Lee [EMAIL PROTECTED] wrote: if i have mytext.replace(a,b) how to find out many many occurances has been replaced? If 'a' and 'b' are different length, - Count the string length, before and after. The difference should be multiple of difference between length of 'a' and 'b'. If they are same length, - Split 'mytext', and count items. -- William Park [EMAIL PROTECTED], Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html -- http://mail.python.org/mailman/listinfo/python-list
Re: new string function suggestion
[Andrew Dalke] 200 lines of thorough analysis To summarize: - I don't think it's needed that often - I don't think your implementation's behavior (using an exception) is what people would expect - I don't think it does what you expect Wow, that was a remarkably thoughtful, total demolition ;-) I expect that this thread is going to be somewhat short lived. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test if an object IS another object?
[EMAIL PROTECTED] wrote: Tuples (which are immutable) also appear to be reused foo = () bar = () foo is bar True Not always: foo = (1,) bar = (1,) foo is bar = False -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic Lists, or...?
On Sat, 11 Jun 2005 10:30:53 -0700, Lorn wrote: I'm trying to figure out a way to create dynamic lists or possibly antother solution for the following problem. I have multiple lines in a text file (every line is the same format) that are iterated over and which need to be compared to previous lines in the file in order to perform some simple math. Each line contains 3 fileds: a descriptor and two integers. Here is an example: rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 The idea is that the 0/1 values are there to let the program know wether to add or subtract the second integer value for a specific descriptor (flower in this case). So the program comes upon rose, adds the 500 to an empty list, waits for the next appearance of the rose descriptor and then (in this case) subtracts 100 from 500 and prints the value. If the next rose was a 1 then it would have added 100. Why not just use a leading minus sign for the number if it is to be subtracted? I'm uncertain on how to approach doing this though. My idea was to somehow be able to create lists dynamically upon each new occurence of a descriptor that currently has no list and then perform the calculations from there. Unfortunately, the list of descriptors is potentially infinte, so I'm unable to previously create lists with the descriptor names. Could anyonw give any suggestions on how to best approach this problem, hopefully I've been clear enough? Any help would be very gratly appreciated. Use a dictionary: def update_dict(D, key, sign, value): Update dictionary D item with key by adding or subtracting value. if not sign: value = -value x = D.get(key, 0) D[key] = x + value def split_line(s): Split a string s into a tuple (key, sign, value), ignoring whitespace. L = s.split(,) return L[0].strip(), L[1].strip(), L[2].strip() # WARNING: insufficient error checking for real world use. Then call them like this: D = {} for line in sourcetext: key, sign, value = split_line(line) update_dict(D, key, sign, value) Oh, by the way... just in case this is homework, which I'm sure it isn't wink, I've deliberately left a teeny tiny bug in the code. You'll find the bug pretty much the first time you run it, and the fix is very simple. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: new string function suggestion
Andy wrote: What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' The names are analogous to strip, rstrip, and lstrip. But the functionality is basically this: def lchop(self, prefix): assert self.startswith(prefix) return self[len(prefix):] def rchop(self, suffix): assert self.endswith(suffix) return self[:-len(suffix] def chop(self, prefix, suffix): assert self.startswith(prefix) assert self.endswith(suffix) return self[len(prefix):-len(suffix] The assert can be a raise of an appropriate exception instead. I find this to be a very common need, I'm not sure whether I should be surprised or not. I've never felt the need for such a gadget. I don't even recall seeing such a gadget in other languages. One normally either maintains a cursor (index or pointer) without chopping up the original text, or splits the whole text up into tokens. AFAICT, most simple needs in Python are satisfied by str.split or re.split. For the special case of file paths, see os.path.split*. There are also various 3rd party parsing modules -- look in PyPI. and often newbies assume that the strip/lstrip/rstrip family behaves like this, but of course they don't. I get tired of writing stuff like: if path.startswith('html/'): path = path[len('html/'):] elif s.startswith('text/'): path = path[len('text/'):] So create a function (example below) and put it along with others in a module called (say) andyutils.py ... def chop_known_prefixes(path, prefixes): for prefix in prefixes: if path.startswith(prefix): return path[len(prefix):] return path By the way, what do you do if path doesn't start with one of the known prefixes? It just gets tedious, and there is duplication. Instead I could just write: try: path = path.lchop('html/') path = path.lchop('text/') except SomeException: pass In the event that path contains (say) 'html/text/blahblah...', this produces 'blahblah...'; the original tedious stuff produces 'text/blahblah...'. Does anyone else find this to be a common need? Has this been suggested before? You can answer that last question yourself by googling comp.lang.python ... -- http://mail.python.org/mailman/listinfo/python-list
Request for help on naming conventions
Are there any useful naming conventions for modules, classes and functions? For instance, should I name functions as verbs and classes as nouns? eg class Transformer(): pass def transform(): do_stuff What about the module name? transformations.py or transform.py? What do people do with their own code? Do folks find that being consistent helps them remember what is what, or do you name objects whatever feels right at the time? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
why python on debian without the module profile?
Hi All: Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type help, copyright, credits or license for more information. import hotshot,hotshot.stats Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/hotshot/stats.py, line 3, in ? import profile ImportError: No module named profile Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type help, copyright, credits or license for more information. import hotshot,hotshot.stats Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.3/hotshot/stats.py, line 3, in ? import profile ImportError: No module named profile -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree Namespace Prefixes
Chris Spencer wrote: If an XML parser reads in and then writes out a document without having altered it, then the new document should be the same as the original. says who? With Elementtree this isn't so. Lundh apparently believes he knows better than you and I on how our namespaces should be represented. do you even understand how XML namespaces work? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: re - multiple results
Pingveno wrote: I'm working on the Python Challenge (make sure to try it: http://www.pythonchallenge.com). One of the puzzles requires the use of regular expressions, but with multiple matches in the text. I tried to use re.findall(), but I only go one result instead of a list of results. print re.findall(rmyexpression,text) ['AZBaCTR'] There should, of course, be several matches. myexpression won't return AZBaCTR for any kind of input, so I'm not sure what of course really refers to... What function should I use? Or is it not a function issue? my guess is that you're using * or + in a situation where you don't really need them. cf. re.findall(\w, abcdef) ['a', 'b', 'c', 'd', 'e', 'f'] re.findall(\w+, abcdef) ['abcdef'] /F -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system
Austin wrote: My code is os.system(NET SEND computer hihi) i use this funtion on Windows server 2003. it's ok. But the same code running on Windows XP SP2, it shows the command window twice. How do i remove the command window? Hi, You can remove the command window which comes from python if you use .pyw as extension. This is not an answer why the system method opens a second window, but maybe it helps, too. Thomas Hi, but my program is complied from py2exe. All extension is 'pyd'. Hm... is there any way to do? no time to test, but the subprocess module might be what you need: http://www.python.org/dev/doc/devel/lib/module-subprocess.html http://www.effbot.org/downloads/#subprocess (for 2.2 and 2.3) (I assume you're already using the windows py2exe option for your own program) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: why python on debian without the module profile?
My understanding is that there are licence issues (someone please correct me if I'm wrong). The moral of the story is that there's a seperate (non-free) package for the profiler: http://packages.debian.org/testing/python/python2.4-profiler HTH Tim On 6/13/05, kyo guan [EMAIL PROTECTED] wrote: Hi All: Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type help, copyright, credits or license for more information. import hotshot,hotshot.stats Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/hotshot/stats.py, line 3, in ? import profile ImportError: No module named profile Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type help, copyright, credits or license for more information. import hotshot,hotshot.stats Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.3/hotshot/stats.py, line 3, in ? import profile ImportError: No module named profile -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: \r\n or \n notepad editor end line ???
[EMAIL PROTECTED] wrote: It means in windows we should use 'wb' to write and 'rb' to read ? Am I right? no. you should use wb to write *binary* files, and rb to read *binary* files. if you're working with *text* files (that is, files that contain lines of text separated by line separators), you should use w and r instead, and treat a single \n as the line separator. /F -- http://mail.python.org/mailman/listinfo/python-list
Java to Python - how to??
Hello I just start programing in Python. I've got a qestion, how translate the example code writen in Java to Python?? public class ConnectionManager { public ConnectionManager() { super(); } public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) { } } bye -- http://mail.python.org/mailman/listinfo/python-list
Re: About size of Unicode string
Frank Abel Cancio Bello wrote: Can I get how many bytes have a string object independently of its encoding? strings hold characters, not bytes. an encoding is used to convert a stream of characters to a stream of bytes. if you need to know the number of bytes needed to hold an encoded string, you need to know the encoding. (and in some cases, including UTF-8, you need to *do* the encoding before you can tell how many bytes you get) Is the len function the right way of get it? len() on the encoded string, yes. Laci look the following code: import urllib2 request = urllib2.Request(url= 'http://localhost:6000') data = 'data to send\n'.encode('utf_8') request.add_data(data) request.add_header('content-length', str(len(data))) request.add_header('content-encoding', 'UTF-8') file = urllib2.urlopen(request) Is always true that the size of the entity-body is len(data) independently of the encoding of data? your data variable contains bytes, not characters, so the answer is yes. on the other hand, that add_header line isn't really needed -- if you leave it out, urllib2 will add the content-length header all by itself. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Java to Python - how to??
[EMAIL PROTECTED] wrote: Hello I just start programing in Python. I've got a qestion, how translate the example code writen in Java to Python?? public class ConnectionManager { public ConnectionManager() { super(); } public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) { } } bye class ConnectionManager(object): def __init__(self): super(ConnectionManager,self).__init__() def sendAgent(self, anAgent, anAddress): pass George -- http://mail.python.org/mailman/listinfo/python-list
asyncore and GUI (wxPython)
Hi, I have the followin situation. 1) I've a machine controled by a computer programn that can comunicate with TCP/IP (server)to recive the request of other program to knwo what the machine should do. 2) The other program (client) has a GUI (with wxPython), recives data from the machine and should process it (draw and write to file). In the current situation the comunication is done in a thread. Every time data is collected it is pased to the main thread of the GUI, with a wxPostEvent. Every stream_socketk sended by the client has its correspondig answer from the server. (I log the comunication an every received socket is the anser of the sended one) The problem: when i stop the thread (i don't no why) the answer to the last socket don't correspond to the last sended (they mix). The possible correction? I have been told not to do network connection in other thread, instead i should use asyncore. I'll be sending sockets every 0.1 seconds or faster. Will be the main progam freeze in the asyncore loop, or it will refresh the windows and response to mouse/keyboard properly? How fast can i be sending sockets without distourbing the main program; or (it is very likeyly) i am totaly wrong and i should take another way? Thanks in advance Zunbeltz -- http://mail.python.org/mailman/listinfo/python-list
Re: DB API 2.0 and transactions
I'm CC:ing this to D'Arcy J.M. Cain. (See comp.lang.python for prequel D'Arcy.) Christopher J. Bottaro wrote: Check this out... code import pgdb import time print time.ctime() db = pgdb.connect(user='test', host='localhost', database='test') time.sleep(5) db.cursor().execute('insert into time_test (datetime) values (CURRENT_TIMESTAMP)') db.commit() curs = db.cursor() curs.execute('select datetime from time_test order by datetime desc limit 1') row = curs.fetchone() print row[0] /code output Fri Jun 10 17:27:21 2005 '2005-06-10 17:27:21.654897-05' /output Notice the times are exactly the same instead of 5 sec difference. What do you make of that? Some other replies to this thread seemed to indicate that this is expected and proper behavior. This is wrong. It should not behave like that if it is to follow the SQL standard which *I* would expect and consider proper. I don't think the SQL standard mandates that all evaluations of CURRENT_TIMESTAMP within a transaction should be the same. It does manadate that CURRENT_TIMESTAMP in only evaluated once in each SQL statement, so CURRENT_TIMESTAMP=CURRENT_TIMESTAMP should always be true in a WHERE statement. I don't think it's a bug if all timestamps in a transaction are the same though. It's really a bonus if we can view all of a transaction as taking place at the same time. (A bit like Piper Halliwell's time-freezing spell in Charmed.) The problem is that transactions should never start until the first transaction-initiating SQL statement takes place. (In SQL-92, all standard SQL statements are transaction initiating except CONNECT, DISCONNECT, COMMIT, ROLLBACK, GET DAIGNOSTICS and most SET commands (SET DESCRIPTOR is the exception here).) Issuing BEGIN directly after CONNECT, ROLLBACK and COMMIT is in violation with the SQL standards. A workaround for you could be to explicitly start a new transaction before the insert as PostgreSQL (but not the SQL standard) wants you to do. I suppose you can easily do that using e.g. db.rollback(). If you like, I guess you could do db.begin=db.rollback in the beginning of your code and then use db.begin(). Another option would be to investigate if any of the other postgreSQL drivers have a more correct behaviour. The non-standard behaviour that you describe it obvious from the pgdb source. See: http://www.pygresql.org/cvsweb.cgi/pygresql/module/pgdb.py?rev=1.27 (Comments added by me.) class pgdbCnx: def __init__(self, cnx): self.__cnx = cnx self.__cache = pgdbTypeCache(cnx) try: src = self.__cnx.source() src.execute(BEGIN) # Ouch! except: raise OperationalError, invalid connection. ... def commit(self): try: src = self.__cnx.source() src.execute(COMMIT) src.execute(BEGIN) # Ouch! except: raise OperationalError, can't commit. def rollback(self): try: src = self.__cnx.source() src.execute(ROLLBACK) src.execute(BEGIN) # Ouch! except: raise OperationalError, can't rollback. ... This should be changed to something like this (untested): class pgdbCnx: def __init__(self, cnx): self.__cnx = cnx self.__cache = pgdbTypeCache(cnx) self.inTxn = False #NEW try: src = self.__cnx.source() # No BEGIN here except: raise OperationalError, invalid connection. ... def commit(self): try: src = self.__cnx.source() src.execute(COMMIT) self.inTxn = False # Changed except: raise OperationalError, can't commit. def rollback(self): try: src = self.__cnx.source() src.execute(ROLLBACK) self.inTxn = False # Changed except: raise OperationalError, can't rollback. ... def cursor(self): try: src = self.__cnx.source() return pgdbCursor(src, self.__cache, self) # Added self except: raise pgOperationalError, invalid connection. ... class pgdbCursor: def __init__(self, src, cache, conn): # Added conn self.__cache = cache self.__source = src self.__conn = conn # New self.description = None self.rowcount = -1 self.arraysize = 1 self.lastrowid = None ...
translating C++ exceptions to python
Hi all, I have a C++ library I call from python. The problem is I have c++ exceptions that i want to be translated to python. I want to be able to do stuff like: try: my_cpp_function() except cpp_exception_1: do_stuff except cpp_exception_2: do_other_stuff any ideas how can i do the translation? Thanks, calin -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use 8bit character sets?
Martin v. Löwis [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] copx wrote: For some reason Python (on Windows) doesn't use the system's default character set and that's a serious problem for me. I very much doubt this statement: Python does use the system's default character set on Windows. What makes you think it doesn't? Is it possible to tell Python to use an 8bit charset (latin-1 in my case) for textfile and string processing by default? That is the default. As far as I can tell, there are actually two defaults, which tends to confuse things. One is used whenever a unicode to 8-bit conversion is needed on output to stdout, stderr or similar; that's usually Latin-1 (or whatever the installation has set up.) The other is used whenever the unicode to 8-bit conversion doesn't have a context - that's usually Ascii-7. John Roth Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Andrea Griffini schrieb: On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen [EMAIL PROTECTED] wrote: I think new CS students have more than enough to learn with their *first* language without having to discover the trials and tribulations of memory management (or those other things that Python hides so well). I'm not sure that postponing learning what memory is, what a pointer is and others bare metal problems is a good idea. I think Peter is right. Proceeding top-down is the natural way of learning (first learn about plants, then proceed to cells, molecules, atoms and elementary particles). If you learn a computer language you have to know about variables, of course. You have to know that they are stored in memory. It is even useful to know about variable address and variable contents but this doesn't mean that you have to know about memory management. MM is a low level problem that has to do with the internals of a computer system and shouldn't be part of a first *language* course. The concepts of memory, data and addresses can easily be demonstrated in high level languages including python e.g. by using a large string as a memory model. Proceeding to bare metal will follow driven by curiosity. -- --- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') --- -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Sun, 12 Jun 2005, Roy Smith wrote: Andrea Griffini [EMAIL PROTECTED] wrote: I think that for a programmer skipping the understanding of the implementation is just impossible: if you don't understand how a computer works you're going to write pretty silly programs. Note that I'm not saying that one should understand every possible implementation down to the bit (that's of course nonsense), but there should be no room for magic in a computer for a professional programmer. How far down do you have to go? What makes bytes of memory, data busses, and CPUs the right level of abstraction? Why shouldn't first-year CS students study how a computer works at the level of individual logic gates? After all, if you don't know how gates work, things like address bus decoders, ALUs, register files, and the like are all just magic (which you claim there is no room for). Digging down a little deeper, a NAND gate is magic if you don't know how a transistor works or can't do basic circuit analysis. And transistors are magic until you dig down to the truly magical stuff that's going on with charge carriers and electric fields inside a semiconductor junction. That's about where my brain starts to hurt, but it's also where the quantum mechanics are just getting warmed up. It's all true - i wouldn't be the shit-hot programmer i am today if i hadn't done that A-level physics project on semiconductors. tom -- Think logical, act incremental -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Sun, 12 Jun 2005, Peter Hansen wrote: Andrea Griffini wrote: On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen [EMAIL PROTECTED] wrote: I think new CS students have more than enough to learn with their *first* language without having to discover the trials and tribulations of memory management (or those other things that Python hides so well). I'm not sure that postponing learning what memory is, what a pointer is and others bare metal problems is a good idea. ... I think that for a programmer skipping the understanding of the implementation is just impossible: if you don't understand how a computer works you're going to write pretty silly programs. I won't say that I'm certain about any of this, but I have a very strong suspicion that the *best* first step in learning programming is a program very much like the following, which I'm pretty sure was mine: 10 FOR A=1 TO 10: PRINTPeter is great!: END 10 PRINT TOM IS ACE 20 GOTO 10 The first line varies, but i suspect the line 20 GOTO 10 figures prominently in the early history of a great many programmers. More importantly by far, *I made the computer do something*. Bingo. When you realise you can make the computer do things, it fundamentally changes your relationship with it, and that's the beginning of thinking like a programmer. tom -- Think logical, act incremental -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Mon, 13 Jun 2005, Andrea Griffini wrote: On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith [EMAIL PROTECTED] wrote: Also concrete-abstract shows a clear path; starting in the middle and looking both up (to higher abstractions) and down (to the implementation details) is IMO much more confusing. At some point, you need to draw a line in the sand (so to speak) and say, I understand everything down to *here* and can do cool stuff with that knowledge. Below that, I'm willing to take on faith. I think that if you don't understand memory, addresses and allocation and deallocation, or (roughly) how an hard disk works and what's the difference between hard disks and RAM then you're going to be a horrible programmer. There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. If those are magic formulas you'll just forget them and you'll end up writing code that is thousands times slower than necessary. I don't buy that. I think there's a world of difference between knowing what something does and how it does it; a black-box view of the memory system (allocation + GC) is perfectly sufficient as a basis for programming using it. That black-box view should include some idea of how long the various operations take, but it's not necessary to understand how it works, or even how pointers work, to have this. tom -- Think logical, act incremental -- http://mail.python.org/mailman/listinfo/python-list
Re: What language to manipulate text files
Roose wrote: Why do people keep asking what language to use for certain things in the Python newsgroup? Obviously the answer is going to biased. Not that it's a bad thing because I love Python, but it doesn't make sense if you honestly want an objective opinion. It will, however, have the side-effect of helping people who google for it tomorrow. I've often found a several months old answer that people on a group had taken the trouble of patiently answering, which was a big help to me. In this case I can imagine a person who has heard that Python is in a class of languages like Perl and Ruby, and who googles around with some keywords to get some idea of whether it can solve their problem. Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Andrea Griffini [EMAIL PROTECTED] wrote: There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. People were thinking about algorithmic complexity before there was random access memory. Back in the unit record equipment (i.e. punch card) days, people were working out the best ways to sort and merge decks of punch cards with the fewest trips through the sorting machine. Likewise for data stored on magnetic tape. I can certainly demonstrate algorithmic complexity without ever going deeper than the level of abstraction exposed by Python. You can learn enough Python in an afternoon to write a bubble sort and start learning about O(2) behavior without even knowing what a memory address is. Somebody mentioned that string addition in Python leads to O(2) behavior. Yes it does, but that's more an artifact of how Guido decided he wanted strings to work than anything fundamental about memory allocation. He could have taken a different design path and made Python strings more like STL vectors, in which case string addition would be O(n). Teaching that string addition is O(2) is not only needlessly confusing for somebody just starting out, it's also wrong (or at best, a specific case valid for one particular implementation). And, BTW, I started out programming on a big HP desktop calculator (http://www.hpmuseum.org/hp9810.htm). Next came BASIC. Then Fortan and assembler on a pdp-10. Then C, a couple of years later. After that, I've lost track. Some of the languages that taught me the most were ones that got very far away from the hardware. NewtonScript was my first introduction to OOPL, and PostScript showed me that stack languages aren't just for calculators. Lisp, of course, expanded my mind in ways that only Lisp can (the same could be said for many things I tried back in those days). Even quirky HyperCard showed me a different way to think about programming. I think it's probably just as important for a CS major to play with those mind-altering languages as it is to worry about bytes and pointers and memory locations. But you can't start everywhere, and if you've got to start someplace, Python let's you concentrate on the real universal fundamentals of data structures, algorithms, and control flow without getting bogged down in details. -- http://mail.python.org/mailman/listinfo/python-list
Re: why python on debian without the module profile?
kyo guan wrote: ImportError: No module named profile They moved it to non-free because the module's license isn't DFSG compliant. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
MD5 problem
Hi. I'm in trouble with the md5 module. Under Linux, it's ok, I get real signatures. The problem is under Windows XP, with some kind of files. If I use the md5 module with .txt files, it'ok. The Problem comes from the .msg files. I get the same signature for every .msg file I try to hash with the md5 algorithm. I think some character are strange for python, and makes it stop before the end of the .msg file. So, my question is : Do anybody have a solution to this problem ? (I can post my source code if needed) Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: MD5 problem
fargo wrote: Hi. I'm in trouble with the md5 module. Under Linux, it's ok, I get real signatures. The problem is under Windows XP, with some kind of files. If I use the md5 module with .txt files, it'ok. The Problem comes from the .msg files. I get the same signature for every .msg file I try to hash with the md5 algorithm. I think some character are strange for python, and makes it stop before the end of the .msg file. That sounds like you opened the file in text mode. For things like this it is better to open it in binary mode: file(filename, 'rb') -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning more about The Python Way
As someone else mentioned, get a copy of the 2nd edition of the Python Cookbook. It's full of gold. Or you can read the recipes online here: http://aspn.activestate.com/ASPN/Python/Cookbook/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for help on naming conventions
Steven D'Aprano wrote: Are there any useful naming conventions for modules, classes and functions? For instance, should I name functions as verbs and classes as nouns? eg class Transformer(): pass def transform(): do_stuff What about the module name? transformations.py or transform.py? You probably want to read the PEP 8, Style Guide for Python Code: http://www.python.org/peps/pep-0008.html What do people do with their own code? Do folks find that being consistent helps them remember what is what, or do you name objects whatever feels right at the time? Naming convention are mostly a matter of personal taste (unless you are working in a larger team, where there are some official conventions that must be followed). So I would say the 'feels right' is the most important factor. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning more about The Python Way
Neuruss wrote: [Me:] As someone else mentioned, get a copy of the 2nd edition of the Python Cookbook. It's full of gold. Or you can read the recipes online here: http://aspn.activestate.com/ASPN/Python/Cookbook/ While most (all?) of the recipes are there, the book is still worth buying for the discussion about each recipe that will help the reader learn more deeply how the code fits into The Python Way. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: MD5 problem
Roel Schroeven wrote: fargo wrote: Hi. I'm in trouble with the md5 module. Under Linux, it's ok, I get real signatures. The problem is under Windows XP, with some kind of files. If I use the md5 module with .txt files, it'ok. The Problem comes from the .msg files. I get the same signature for every .msg file I try to hash with the md5 algorithm. I think some character are strange for python, and makes it stop before the end of the .msg file. That sounds like you opened the file in text mode. For things like this it is better to open it in binary mode: file(filename, 'rb') It was excatly the problem. Thank you for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: separate IE instances?
the good news is that if run the ShellExecute bit twice, I get two instances of explorer in Task Manager The bad news is that the line ioObj = hwnds[1] tells me either This object does not support enumeration (if I have not used makepy to generate the classes) or object has no attribute __getitem__ (if I have used makepy) looking at the hwnds itself, it appears to be a win32com.gen_py.Microsoft Internet Controls.IWebBrowser2 instance If I call hwnds.Navigate(http://www.google.com;), I don't get an error, but I also don't see anything change in IE. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
Le Mon, 13 Jun 2005 07:53:03 -0400, Roy Smith a écrit : Python let's you concentrate on the real universal fundamentals of data structures, algorithms, and control flow without getting bogged down in details. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Dealing with marketing types...
Steve Jorgensen [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sat, 11 Jun 2005 11:51:02 -0500, tom [EMAIL PROTECTED] wrote: ... Let me add an Item #3 - If you have some entrepeneurial savvy and can keep your emotions out of it tou can simply tell them you have decided strike out on your own and tell them that you will be available. They will be happy to hear you are leaving and happier still to hear you can be available for backup. Their goals and fears are addressed at the same time. AND there is a very high possibility that they will *need* you at a later date for which you can charge them dearly. That last item #3 has actually worked for me with (2) prior employers. I did have to eat my indignation and keep it friendly but it did pay off in the end. Thomas Bartkus I have to say that, although I have yet to write a line of Python code for money, I've found that this concept basically works. When you realize that your employer is cutting you out to save the cost of paying you, funny enough, they'll be willing to -really- pay you as a consultant later when they get stuck, and one or more paying customers are impacted. Yup! It's theold stupid + greedy double whammy that means they end up paying more. Your not feeling sorry for them, are you? They also win't mind figuring out how to have you come in after hours so it won't conflict with your new day job if you have one. In my case, the work was in VB/VBA, but the same principle should apply to any technology. Do make sure that your contract with any new employer allows you to do at least small amounts of moonlighting - they probably won't object. They will insist that any moonlighting shall not compete with their line of business, and you should agree to that stipulation. How much of *my* time are they buying with a salary? 40Hrs a week? 24/7 ? You want to see that your contract as an employee doesn't somehow forbid you from earning extra on your own time. Unless, of course, they are paying enough to make you happy to sell them *all* your time. Sometimes you are hired mainly to keep your skills unavailable to their competitors. Thats ok as long as they pay you enough to keep you happy with this. Unless they are paying for it, your own free time is none of their business. Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list
Controlling assignation
I would like to know if there is for python's classes an equivalent of the operator= that can be overidden. Let's say I have a=A() and I want to write a=5 and I want this to change some internal value of a instead of making a point to a new object (an int 5) In other word, I would like to be able to use a=5 instead of a.set(5) Is that possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: separate IE instances?
Sorry about that I had an instance of ie running in the background that was version 0 didn't see the problem tell this morining when my computer started to not work. it should be hwnds[1] should be hwnds[0]. I woud enumerate them like in the code below. If you have ie as your default browser you can use a shellExecute(0,None,some url here, None, None, 1) To open directley to that page. Here is a more complete script: import win32api, time from win32com.client import Dispatch a = win32api.ShellExecute(0,None,iexplore.exe, www.ishpeck.net,None,1) b = win32api.ShellExecute(0,None,iexplore.exe, www.google.com,None,1) internetExplorerClassIdentity='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hwnds = Dispatch(internetExplorerClassIdentity) # way I showed you before dosn't work verry well if more then one ie is open #ieObj = hwnds[0] #ieObj.Navigate(http://www.google.com/search?hl=enlr=q=python;) time.sleep(30) for i in range(hwnds.Count): if hwnds[i].LocationURL.lower().find(ishpeck) -1: ieObj1 = hwnds[i] if hwnds[i].LocationURL.lower().find(google) -1: ieObj2 = hwnds[i] ieObj1.Navigate(http://www.google.com/search?hl=enlr=q=python;) ieObj2.Navigate(http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ba1395566452dba6/343672a01d5b2cdc?hl=en#343672a01d5b2cdc;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
Xavier Décoret wrote: I would like to know if there is for python's classes an equivalent of the operator= that can be overidden. Let's say I have a=A() and I want to write a=5 and I want this to change some internal value of a instead of making a point to a new object (an int 5) In other word, I would like to be able to use a=5 instead of a.set(5) Is that possible? Not with simple names, such as a. You can do it if you assign to an attribute of an object, such as a.b, by intercepting the assignment call via __setattr__ or a property. In Python, anyone reading your code would expect that a=5 represents a rebinding of the name a to a new object, possibly destroying the old object, and if you did manage to subvert that you'd just be making your code unreadable, in the way that overuse of #define to change syntax in C can make C code (even more) unreadable. Please reconsider why you want to do that and find a more conventional approach, such as a.set(5). -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: \r\n or \n notepad editor end line ???
On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote: [EMAIL PROTECTED] wrote: It means in windows we should use 'wb' to write and 'rb' to read ? Am I right? no. you should use wb to write *binary* files, and rb to read *binary* files. if you're working with *text* files (that is, files that contain lines of text separated by line separators), you should use w and r instead, and treat a single \n as the line separator. I get nervous when I read instructions like this. It sounds too much like voodoo: Do this, because it works, never mind how or under what circumstances, just obey or the Things From The Dungeon Dimensions will suck out your brain!!! Sorry Fredrik :-) When you read a Windows text file using r mode, what happens to the \r immediately before the newline? Do you have to handle it yourself? Or will Python cleverly suppress it so you don't have to worry about it? And when you write a text file under Python using w mode, will the people who come along afterwards to edit the file in Notepad curse your name? Notepad expects \r\n EOL characters, and gets cranky if the \r is missing. How does this behaviour differ from universal newlines? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to receive events (eg. user mouse clicks) from IE
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Resurrecting an old thread.. It seems that this solution does not return events on objects within frames in webpages eg . if you go to www.andersondirect.com - the page is composed of three frames called as topFrame main and address. Now when I click on say 'Select a Vehicle' which is within main - I do not get any Onclick event. I also do not get an OnMousemove event if I move the mouse. However, I do get on Mousemove event on a tag called as frameset (which is part of the top page). How does one get events from the frames then? As always thanks a lot. Roger Upole [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Each frame acts as a separate document. You should be able catch document events from a frame using something like win32com.client.DispatchWithEvents(ie.Document.frames(nbr of frame).document, your event class) Roger What Roger said is correct, however the frames you're wanting on that site are running Flash apps. I'm not aware of any method that allows one to intercept clicks within a Flash app. And even if you could determine a click occurred, you'd have to figure out where in the app precisely and what Flash will do with that information. I suspect this is not possible by design (i.e. security reasons, etc.) JC -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 15:52, Xavier Décoret wrote: I would like to know if there is for python's classes an equivalent of the operator= that can be overidden. Let's say I have a=A() and I want to write a=5 and I want this to change some internal value of a instead of making a point to a new object (an int 5) In other word, I would like to be able to use a=5 instead of a.set(5) Is that possible? the short answer is: no. the long answer: if you write a=A() an instance of class A is created and bound to the local identifier 'a'. If you later write a=5 the object 5 is reassigned to the same identifier, deleting whatever value was stored there before. The identifier itself does not impose any restrictions on the type of instances that can be bound to it. Binding an instance of class A in the first part, does not make the identifier of the kind 'can-only-bind-A-instances'. In other words: identifiers don't have types. Thus, there is no mechanism that allows to change the binding behavior of identifiers. As a general advise, don't try to write C++ in python. I think, for most cases, there are far better solutions than changing the assign operator anyway... explicit is better than implicit: If class A has only one dedicate value and no internal state, make it a construcotr call: a=A(5) Otherwise, it is worth mentioning the name of the member to set. IMHO this increases the readability of your source code: a.pressure=5 Cheers, - harold - -- I was born not knowing and have had only a little time to change that here and there. -- Richard Feynman -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On Mon, 13 Jun 2005 15:52:14 +0200, Xavier Décoret wrote: I would like to know if there is for python's classes an equivalent of the operator= that can be overidden. Let's say I have a=A() and I want to write a=5 and I want this to change some internal value of a instead of making a point to a new object (an int 5) In other word, I would like to be able to use a=5 instead of a.set(5) Is that possible? I don't know, because I don't understand what you mean. What is A()? A class or a function? What is a.set()? What does it do? I'm going to make a wild guess as to what you want to do. You want something like Pascal records or C structs, right? py a = MyCustomShapeClass() py print a # calls a.__repr__ for a nice printable representation [top = 0, bottom = 1, left = 5, right = 20, kind = rect] py a.kind = oval py a.bottom = 100 py print a [top = 0, bottom = 100, left = 5, right = 20, kind = oval] Is that the sort of thing you are looking for? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Tk() doesn't bring up a window in Python2.4
Hello. I recently installed Python2.4 on both Linux (Redhat FC3) and Windows XP. The build and installed went fine as far as I could tell. I Windows, when I bring up IDLE, or pythonwin, I can't bring up a new Frame widget with Tk(). If I use idle from a DOS window, everything's fine. Python programs I have that use Tkinter also work from either IDLE. Thanks for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On Mon, Jun 13, 2005 at 03:52:14PM +0200, Xavier Décoret wrote: In other word, I would like to be able to use a=5 instead of a.set(5) If a(5) is acceptable to you in stead of a=5 you can make your instance callable with the __call__ method: class A(object): def __init__(self): self.var=0 def __call__(self,val=None): self.var=val a = A() a(5) print a.var # gives 5 egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 -- http://mail.python.org/mailman/listinfo/python-list
Tiff Image Reader/writer
Hi I am looking for a simple tiff Image reader/writer in python.Can anyone point me to the right one. -- http://mail.python.org/mailman/listinfo/python-list
Re: \r\n or \n notepad editor end line ???
Steven D'Aprano wrote: When you read a Windows text file using r mode, what happens to the \r immediately before the newline? Do you have to handle it yourself? Or will Python cleverly suppress it so you don't have to worry about it? And when you write a text file under Python using w mode, will the people who come along afterwards to edit the file in Notepad curse your name? Notepad expects \r\n EOL characters, and gets cranky if the \r is missing. This is Python. Fire up the interactive interpreter and try it out! It will take all of two or three minutes... How does this behaviour differ from universal newlines? If you open a text file created with a different line-ending convention than that used on your own platform, you may get interesting results. If you use rU instead, you will receive only \n line endings and not have anything to worry about. (For example, reading a Windows text file on Linux will give you lines that have \r\n endings in them... not what you really want. Using rU will give you just \n line endings whether you are on Linux or Windows.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyparsing-1.3.1 released
Pyparsing is a pure-Python class library for quickly and easily constructing recursive-descent parsers. Pyparsing takes a building-block approach to parser construction, as opposed to code generation methods (such as lex/yacc) or pattern definition strings (such as regular expressions). Version 1.3.1 includes some minor enhancements, plus some performance improvements that can really improve performance for grammars that use the Combine class (often used in specifying floating point numbers). The 1.3.1 change notes are listed below. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul McGuire Version 1.3.1 - June 12, 2005 - - Added markInputline() method to ParseException, to display the input text line location of the parsing exception. (Thanks, Stefan Behnel!) - Added setDefaultKeywordChars(), so that Keyword definitions using a custom keyword character set do not all need to add the keywordChars constructor argument (similar to setDefaultWhitespaceChars()). (suggested by rzhanka on the SourceForge pyparsing forum.) - Simplified passing debug actions to setDebugAction(). You can now pass 'None' for a debug action if you want to take the default debug behavior. To suppress a particular debug action, you can pass the pyparsing method nullDebugAction. - Refactored parse exception classes, moved all behavior to ParseBaseException, and the former ParseException is now a subclass of ParseBaseException. Added a second subclass, ParseFatalException, as a subclass of ParseBaseException. User-defined parse actions can raise ParseFatalException if a data inconsistency is detected (such as a begin-tag/end-tag mismatch), and this will stop all parsing immediately. (Inspired by e-mail thread with Michele Petrazzo - thanks, Michelle!) - Added helper methods makeXMLTags and makeHTMLTags, that simplify the definition of XML or HTML tag parse expressions for a given tagname. Both functions return a pair of parse expressions, one for the opening tag (that is, 'tagname') and one for the closing tag ('/tagname'). The opening tagame also recognizes any attribute definitions that have been included in the opening tag, as well as an empty tag (one with a trailing '/', as in 'BODY/' which is equivalent to 'BODY/BODY'). makeXMLTags uses stricter XML syntax for attributes, requiring that they be enclosed in double quote characters - makeHTMLTags is more lenient, and accepts single-quoted strings or any contiguous string of characters up to the next whitespace character or '' character. Attributes can be retrieved as dictionary or attribute values of the returned results from the opening tag. - Added example SimpleCalc.py, a refinement on fourFn.py that adds an interactive session and support for variables. (Thanks, Steven Siew!) - Added performance improvement, up to 20% reduction! (Found while working with Wolfgang Borgert on performance tuning of his TTCN3 parser.) - And another performance improvement, up to 25%, when using scanString! (Found while working with Henrik Westlund on his C header file scanner.) - Updated UML diagrams to reflect latest class/method changes. -- http://mail.python.org/mailman/listinfo/python-list
program call graph
Hi, After much googling, I still cannot find any tool/module for producing a (static) call graph of a program. I have got nearly to my aim with trace.py, though it must actually run the program and the output would have to be parsed after; and doxygen + pythfilter.py, which should work, but did not (pythfilter having some parsing problems). I would greatly appreciate your hints/suggestions. Thanks, Robert -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyparsing-1.3.1 released
(sorry if this is a double-post - I tried posting this last night but I think GoogleGroups ate it) Pyparsing is a pure-Python class library for quickly and easily constructing recursive-descent parsers. Pyparsing takes a building-block approach to parser construction, as opposed to code generation methods (such as lex/yacc) or pattern definition strings (such as regular expressions). Version 1.3.1 includes some minor enhancements, plus some performance improvements that can really improve parsing speed for grammars that use the Combine class (often used in specifying floating point numbers). The 1.3.1 change notes are listed below. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul McGuire Version 1.3.1 - June 12, 2005 - - Added markInputline() method to ParseException, to display the input text line location of the parsing exception. (Thanks, Stefan Behnel!) - Added setDefaultKeywordChars(), so that Keyword definitions using a custom keyword character set do not all need to add the keywordChars constructor argument (similar to setDefaultWhitespaceChars()). (suggested by rzhanka on the SourceForge pyparsing forum.) - Simplified passing debug actions to setDebugAction(). You can now pass 'None' for a debug action if you want to take the default debug behavior. To suppress a particular debug action, you can pass the pyparsing method nullDebugAction. - Refactored parse exception classes, moved all behavior to ParseBaseException, and the former ParseException is now a subclass of ParseBaseException. Added a second subclass, ParseFatalException, as a subclass of ParseBaseException. User-defined parse actions can raise ParseFatalException if a data inconsistency is detected (such as a begin-tag/end-tag mismatch), and this will stop all parsing immediately. (Inspired by e-mail thread with Michele Petrazzo - thanks, Michelle!) - Added helper methods makeXMLTags and makeHTMLTags, that simplify the definition of XML or HTML tag parse expressions for a given tagname. Both functions return a pair of parse expressions, one for the opening tag (that is, 'tagname') and one for the closing tag ('/tagname'). The opening tagame also recognizes any attribute definitions that have been included in the opening tag, as well as an empty tag (one with a trailing '/', as in 'BODY/' which is equivalent to 'BODY/BODY'). makeXMLTags uses stricter XML syntax for attributes, requiring that they be enclosed in double quote characters - makeHTMLTags is more lenient, and accepts single-quoted strings or any contiguous string of characters up to the next whitespace character or '' character. Attributes can be retrieved as dictionary or attribute values of the returned results from the opening tag. - Added example SimpleCalc.py, a refinement on fourFn.py that adds an interactive session and support for variables. (Thanks, Steven Siew!) - Added performance improvement, up to 20% reduction! (Found while working with Wolfgang Borgert on performance tuning of his TTCN3 parser.) - And another performance improvement, up to 25%, when using scanString! (Found while working with Henrik Westlund on his C header file scanner.) - Updated UML diagrams to reflect latest class/method changes. -- http://mail.python.org/mailman/listinfo/python-list
string formatting using the % operator
I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Show current ip on Linux
Hi, Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine man :-) My question is : How can i rwite a script that show my current ip. If i have more than one network card, the script must then show all used ip. It's important that this will work on a linux. i Have rwite some piece of code that realy work under Windows XP, but the same script wil not work on Linux. Verry thanks to all vulunteers. -- David Van Mosselbeen - DVM http://dvm.zapto.org: --- Fedora Core 3 User -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
William Gill wrote: I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? try this : sql += 'WHERE name LIKE %%%s%%' % searchterm -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? %%%s%% % here you go '%here you go%' Cheers, - harold - -- If your only tool is a hammer, every problem looks like a nail. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Show current ip on Linux
David Van Mosselbeen wrote: Hi, Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine man :-) My question is : How can i rwite a script that show my current ip. If i have more than one network card, the script must then show all used ip. It's important that this will work on a linux. i Have rwite some piece of code that realy work under Windows XP, but the same script wil not work on Linux. Verry thanks to all vulunteers. How about use the shell command ifconfig | grep inet ? -- Qiangning Hong _ ( zhen so zhen when I do a chroot /path /bin/bash, i can ) ( see the processes ) ( ) ( outside of the chroot zhen and i can kill those processes ) ( * klieber claps for zhen zhen oh go die ) - o \___ v__v o \ O ) (OO) ||w | (__) || || \/\ -- http://mail.python.org/mailman/listinfo/python-list
Re: Tiff Image Reader/writer
On 13 Jun 2005 07:55:04 -0700, PyPK [EMAIL PROTECTED] wrote: Hi I am looking for a simple tiff Image reader/writer in python.Can anyone point me to the right one. I don't know what your definition of simple is, but check out the Python Imaging Library (PIL) at effbot.org. Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
[OT ?] (Pythonic) detection word protected files
Hi, This is certainly off topic, but as my problem must have a pythonic answer. I'm building an utility that makes a catalog of M$ word files in a giant directory tree. The password protected files must be marked, and I didn't find how to guess which files are password protected and which ones are not. I can't use the COM interface for this because the utility must run on a Linux Samba server. I didn't find anything satisfying in M$ related sites (like msdn) or forums or google. Any hint ? Many thanks by advance. -- Gilles -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
On Mon, 13 Jun 2005 15:12:54 GMT, William Gill [EMAIL PROTECTED] wrote: I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Let the DB-API do more work for you: cursor = connection.cursor( ) sql = SELECT column2, columns3 FROM table WHERE name LIKE %s values = ('%%%s%%' % searchterm,) # note that this is a tuple cursor.execute( sql, values ) HTH, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
Tkinter app structure
Hi there, I've just started my first project with Tkinter. I've already coded all the data handling classes and have a nice interface to work with (it happens to be a wrapper around the DOM of a large(ish) XML document but thats probably not important ;-) I'm new to Tkinter so I've started in a fairly random place: the main menu. I noticed that the event mechanism was based on callbacks so, in a flash of inspiration, I decided to create a new module called 'commands.py' which would contain all my callback methods (meaning I could use them for a toolbar as well, if I ever add one) and which acts as an intermediary between the Tkinter classes and my data hanlding classes. I've also created a 'main.py' module which holds the Tk object (called 'root'), the top level data object (called 'data') and the main UI object (called 'mwnd', an instance of a class inherited from Frame called 'MainWindow'). * The main.py module imports: from dataclasses import * from mainwindow import * from Tkinter import * * The mainwindow.py module imports: from Tkinter import * from commands import * * The commands.py modules imports: import main import tkMessageBox * And the dataclasses.py module imports only unrelated modules This set up should allow me to be able to access main.data and main.root from the commands.py module and the command callback functions (defined in commands.py) from mainwindow.py. main.py looks like this: 1: from dataclasses import * 2: from mainwindow import * 3: from Tkinter import * 4: 5: data = Database() 6: 7: root = Tk() 8: mwnd = MainWindow(root) 9: root.mainloop() However, when I execute it I get the following error: Traceback (most recent call last): File ./main.py, line 2, in ? from mainwindow import * File mainwindow.py, line 2, in ? from commands import * File commands.py, line 4, in ? import main File main.py, line 8, in ? mwnd = MainWindow(root) NameError: name 'MainWindow' is not defined (where 'mainwindow.py' line 2 is from commands import *, commands.py line 4 is import main and the name MainWindow is the name of the class defined in the mainwindow.py module) Whats going wrong? Is it a 'circular import'? Is there a better way that I could organise these modules? Cheers, Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: Show current ip on Linux
Previously, on Jun 13, Qiangning Hong said: # David Van Mosselbeen wrote: # Hi, # Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine # man :-) # # My question is : How can i rwite a script that show my current ip. If i have # more than one network card, the script must then show all used ip. # # It's important that this will work on a linux. i Have rwite some piece of # code that realy work under Windows XP, but the same script wil not work on # Linux. # # Verry thanks to all vulunteers. # # # How about use the shell command ifconfig | grep inet ? # I think you mean ifconfig -a|grep 'inet ' He needs to see all the interfaces, no options will only print a help message. 'inet ' will get get rid of the inet6 addresses assuming he doesn't need those. # # -- # Qiangning Hong # # _ # ( zhen so zhen when I do a chroot /path /bin/bash, i can ) # ( see the processes ) # ( ) # ( outside of the chroot zhen and i can kill those processes ) # ( * klieber claps for zhen zhen oh go die ) # - #o \___ # v__v o \ O ) # (OO) ||w | # (__) || || \/\ # # -- # http://mail.python.org/mailman/listinfo/python-list # --- James Tanis [EMAIL PROTECTED] http://pycoder.org -- http://mail.python.org/mailman/listinfo/python-list
Re: separate IE instances?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Sorry about that I had an instance of ie running in the background that was version 0 didn't see the problem tell this morining when my computer started to not work. it should be hwnds[1] should be hwnds[0]. I woud enumerate them like in the code below. If you have ie as your default browser you can use a shellExecute(0,None,some url here, None, None, 1) To open directley to that page. Here is a more complete script: import win32api, time from win32com.client import Dispatch a = win32api.ShellExecute(0,None,iexplore.exe, www.ishpeck.net,None,1) b = win32api.ShellExecute(0,None,iexplore.exe, www.google.com,None,1) internetExplorerClassIdentity='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hwnds = Dispatch(internetExplorerClassIdentity) # way I showed you before dosn't work verry well if more then one ie is open #ieObj = hwnds[0] #ieObj.Navigate(http://www.google.com/search?hl=enlr=q=python;) time.sleep(30) for i in range(hwnds.Count): if hwnds[i].LocationURL.lower().find(ishpeck) -1: ieObj1 = hwnds[i] if hwnds[i].LocationURL.lower().find(google) -1: ieObj2 = hwnds[i] ieObj1.Navigate(http://www.google.com/search?hl=enlr=q=python;) ieObj2.Navigate(http://groups-beta.google.com/group/comp.lang.python/browse_thr ead/thread/ba1395566452dba6/343672a01d5b2cdc?hl=en#343672a01d5b2cdc) The thing to note is that hwnds brings back a list of all Internet Explorer objects running on your machine. This *includes* things that might not be obvious at first, like a simple Windows Explorer window (or windows) you have running (since it uses IE in the background). Printing hwnds.LocationName and hwnds.LocationURL in a loop will show you exactly what processes are using IE at the time you run it. Given that the returned list will vary each time you run your program you'll definitely have to iterate through each hwnds item and check if it is the browser session you want as shown in the above code. JC -- http://mail.python.org/mailman/listinfo/python-list
Re: case/switch statement?
Peter Hansen wrote: Chinook wrote: On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote: Case statements are actually more suitable in many cases even when performance is not a goal for reasons of *readability*. When reading an if statement, you have to scan down through effective each statement attempting to find the case in which you are interested. Some cases can be compound. The nested ifs can get confused with the surrounding ones (in Python or a language with explicit block delimiters). The cases are often not written in any particular order, or they are ordered *for* performance reasons, but in ways that make it harder to scan. The problem I do see is your apples and oranges argument. You are equating at the extreme, compound if conditions with _simple_ case statement conditionals. Yet you are leaving out of your argument the transition from the former to the latter. If mapping one to the other is simple then the readability is no harder with if statements. I dispute that, and believe you've misunderstood my core point. It's not anything to do with equivalence between the two approaches. It's that if you see a set of if/else statements, you have to look at all of them to understand completely what's happening. (I mean the structure of the if/else... the conditionals, not the contents of the blocks.) With a case statement, on the other hand, you *know* that it must be just simple conditionals (a series of x == some_constant tests), so you don't need to look at all the cases, just the one that interests you. So it's not a comparison between two ways of writing the same thing, it's about the fact that with a case statement there are many things you *cannot* write, so reading one is much easier than reading a similarly sized compound if/else. While this is how case statements *tend* to be used, it is of course trivially possible to rewrite any if-then as a case: case condition: value True: ... value False: ... This would, of course, be a perversion of the purpose of the case statement, and I agree with you that in *normal* usage the case statement is easier to read because once you see the opening clause you know a) that only one of the following cases will be executed, and b) that control flow will resume after the case construct. So despite my nitpicking I do agree with you that there's a margin of readability that it might be useful to include in Python to avoid the sometimes-lengthy if-elif-elif-elif-elif-elif strings one sometimes sees - particularly so if any of the cases require conditionals, as nested conditionals are probably among the more difficult sequences to read. This is much like saying that a short function is easier to read than a long one. The long one can obviously do much more, so it's an apples and oranges comparison in that sense. But clearly if the short one fits all on one screen and the long one does not, the short one is basically much easier to grok. That's all I'm saying. And I'm agreeing. In my experience I've also seen where case statements promote overly long and partially repetitive code blocks, which would be better constructed in a top-down fashion. Admittedly, if statements could be used in a similar way but I've not seen the same level of abuse with such. That's true. Indeed any language can be abused, but Python is more concerned with making it easy to write good programs than difficult to write bad ones. So arguably, if the translation is pretty much one to one then the argument is mute :~) moot Well, if the argument never said anything perhaps it *was* mute too? :-) Sort of, except my point here would be that a case statement is then the better choice in many cases because it communicates to the reader that the entire thing *is* simple, while the if/else/if/else does not. -Peter Precisely. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT ?] (Pythonic) detection word protected files
Perhaps you can use OpenOffice and it's python UNO Bindings? I only know about their existence, but perhaps this will be a starting point: http://udk.openoffice.org/ HTH, Gerald Gilles Lenfant schrieb: Hi, This is certainly off topic, but as my problem must have a pythonic answer. I'm building an utility that makes a catalog of M$ word files in a giant directory tree. The password protected files must be marked, and I didn't find how to guess which files are password protected and which ones are not. I can't use the COM interface for this because the utility must run on a Linux Samba server. I didn't find anything satisfying in M$ related sites (like msdn) or forums or google. Any hint ? Many thanks by advance. -- Gilles -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 -- http://mail.python.org/mailman/listinfo/python-list
RE: [OT ?] (Pythonic) detection word protected files
[Gilles Lenfant] | I'm building an utility that makes a catalog of M$ word files | in a giant | directory tree. The password protected files must be marked, and I | didn't find how to guess which files are password protected and which | ones are not. | | I can't use the COM interface for this because the utility | must run on a | Linux Samba server. | | I didn't find anything satisfying in M$ related sites (like msdn) or | forums or google. This page looks like it might be useful: http://wvware.sourceforge.net/wvInfo.html TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling a generator the pythonic way
Thomas Lotze wrote: Peter Hansen wrote: Thomas Lotze wrote: I can see two possibilities to do this: either the current file position has to be read from somewhere (say, a mutable object passed to the generator) after each yield, [...] The third approach, which is certain to be cleanest for this situation, is to have a custom class which stores the state information you need, and have the generator simply be a method in that class. Which is, as far as the generator code is concerned, basically the same as passing a mutable object to a (possibly standalone) generator. The object will likely be called self, and the value is stored in an attribute of it. Probably this is indeed the best way as it doesn't require the programmer to remember any side-effects. It does, however, require a lot of attribute access, which does cost some cycles. Hmm, you could probably make your program run even quicker if you took out all the code :-) Don't assume that there will be a perceptible impact on performance until you have written it they easy way. I'll leave you to Google for quotes from Donald Knuth about premature optimization. A related problem is skipping whitespace. Sometimes you don't care about whitespace tokens, sometimes you do. Using generators, you can either set a state variable, say on the object the generator is an attribute of, before each call that requires a deviation from the default, or you can have a second generator for filtering the output of the first. Again, both solutions are ugly (the second more so than the first). One uses side-effects instead of passing parameters, which is what one really wants, while the other is dumb and slow (filtering can be done without taking a second look at things). And, again, your obsession with performance obscure the far more important issue: which solution is easiest to write and maintain. If the user then turns up short of cycles they can always elect to migrate to a faster computer: this will almost inevitably be cheaper than paying you to speed the program up. All of this makes me wonder whether more elaborate generator semantics (maybe even allowing for passing arguments in the next() call) would not be useful. And yes, I have read the recent postings on PEP 343 - sigh. Sigh indeed. But if you allow next() calls to take arguments you are effectively arguing for the introduction of full coroutines into the language, and I suspect there would be pretty limited support for that. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
extending Python base class in C
Hi all, I once read that it is possible to use a python base class for a C extension class. To be precise, I want to achieve the following behavior: class PythonClass : pass class CClass(PythonClass) : this class should be implemented as C extension pass Unfortunately, google could not find me the right reference. Does anyone know how to do it, or where I can find relevant information? Thanks, - harold - -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
Xavier Décoret a écrit : I would like to know if there is for python's classes an equivalent of the operator= that can be overidden. Let's say I have a=A() and I want to write a=5 and I want this to change some internal value of a instead of making a point to a new object (an int 5) In other word, I would like to be able to use a=5 instead of a.set(5) Is that possible? Thanks anybody for the answers. It confirms what I understood of Python. What I wanted to do is something like this: def change(x,v): x = v class A(object): def __init__(self,v): self.x = v a = A(3) print a.x # displays 3 change(a.x,4) print a.x # still displays 3 It may seem weird, but I ensure there is a reason for doing this. In C++ (the language I am mot familiar with), I could define f to take a pointer to member function of a class, a pointer and a value and achieve what I want. In python, I cannot that way becauswe when change(a.x,4) is executed, a.x is replaced by ist value (returned by __getattribute__). Finally, here is how I hold the situation: class Handle: def __init__(self,v): self.__v = v def __call__(self): x = self.__v while callable(x): x=x() return x def set(self,v): self.__v = v class HandledProperty(object): def __init__(self,name=): self.name = name def __get__(self,o,t): return o.__dict__[self] def __set__(self,o,v): o.__dict__[self] = Handle(v) class A(object): x = HandledProperty(x) def __init__(self,v): self.x = v def change(x,v): x.set(v) a = A(3) print a.x() # displays 3 (notice the () in the call) change(a.x,4) print a.x() # still displays 4 -- http://mail.python.org/mailman/listinfo/python-list
RE: [python-win32] NTService detecting if the Windows System is Idle
-Original Message- From: Hughes, Chad O Sent: Monday, June 13, 2005 9:09 AM To: 'Fred Dixon' Subject: RE: [python-win32] NTService detecting if the Windows System is Idle There may be important processes running in the background (headless process with no user interaction) that need resources while the user may or may not be using the computer, possible when the user is logged out. I would use the system resource usage itself to define the idleness of your system. There are a great number of things that can be measured and you can even have general system measurements as well as process specific measurements. For example: lets say that you have your thresholds set to some logical value, and you have some process (call it processA) that is important. You can dynamically redefine your thresholds for when processA is running and then dynamically readjust them when it is not. Moreover, you can make your thresholds be a function of your general system usage combined with process specific usage. For example, you can dynamically adjust your thresholds based on linear functions of the usage of a list of processes and your system. This is a very flexible approach. My example is just a starting point. Do you fallow this? -Original Message- From: Fred Dixon [mailto:[EMAIL PROTECTED] Sent: Sunday, June 12, 2005 12:30 PM To: Hughes, Chad O Subject: Re: [python-win32] NTService detecting if the Windows System is Idle why not just run it when the screen saver is active On 6/10/05, Hughes, Chad O [EMAIL PROTECTED] wrote: I think this example is what you want to do. It is not a service, but you can turn it into one. import win32pdh from time import sleep import threading pdhQuery = win32pdh.OpenQuery(None, 0) class PDH_COUNTER_PATH_ELEMENTS(list): def __init__(self, l = None): if not l: l = ['127.0.0.1',None,None,None,-1,None] list.__init__(self,l) self.__machineName = self[0] self.__objectName = self[1] self.__instanceName = self[2] self.__parantInstance = self[3] self.__instanceIndex = self[4] self.__counterName = self[5] def __setMachineName(self,value): self.__machineName = value self[0] = value def __setObjectName(self,value): self.__objectName = value self[1] = value def __setInstanceName(self,value): self.__instanceName = value self[2] = value def __setParentInstance(self,value): self.__parentInstance = value self[3] = value def __setInstanceIndex(self,value): self.__instanceIndex = value self[4] = value def __setCounterName(self,value): self.__counterName = value self[5] = value def __getMachineName(self): return self.__machineName def __getObjectName(self): return self.__objectName def __getInstanceName(self): return self.__instanceName def __getParentInstance(self): return self.__parentInstance def __getInstanceIndex(self): return self.__instanceIndex def __getCounterName(self): return self.__counterName machineName = property(__getMachineName, __setMachineName) objectName = property(__getObjectName, __setObjectName) instanceName = property(__getInstanceName, __setInstanceName) instanceIndex = property(__getInstanceIndex, __setInstanceIndex) parentInstanceIndex = property(__getParentInstance, __setParentInstance) counterName = property(__getCounterName, __setCounterName) def makeCopy(self): return PDH_COUNTER_PATH_ELEMENTS(self) def __repr__(self): return 'machineName = %s\nobjectName = %s\nInstanceName = %s\nparentInstance = %s\ninstanceIndex = %s\ncounterName = %s'%tuple(self) class WorkerThread(threading.Thread): def __init__(self): threading.Thread.__init__(self, target = self.__runLoop) self.__pauseEvent = threading.Event() #when wait is called after clear the thread will pause until set self.__pauseEvent.clear() self.__stayAlive = True def stop(self): self.__stayAlive = False #loop until runLoop is exited while self.isAlive(): self.__pauseEvent.set() def pause(self): self.__pauseEvent.clear() def resume(self): self.__pauseEvent.set() def __runLoop(self): while self.__stayAlive: self.__pauseEvent.wait() #do what ever you want to do while the CPU is idle #example print that cpu is idle print 'The CPU is idle' #make paths cpe = PDH_COUNTER_PATH_ELEMENTS(( '127.0.0.1', Processor, '_Total', None, -1, % Idle Time )) #you can replace _Total with a CPU id. #For example: replace it with 0 for the first CPU #Look up Perfmon for more details procPath = win32pdh.MakeCounterPath(cpe) procCounter = win32pdh.AddCounter(pdhQuery, procPath, 0) #For Windows to get a good statistic you must collect once first. #That way Windows can form a delta on the CPU usage. win32pdh.CollectQueryData(pdhQuery) sleep(.1) #Lets say that
Re: searching for IDE
[Grumman wrote] alexrait1 wrote: I need an IDE for python that has the ability to show the filds of a class when I write . Just the way it works in eclipse/JBuilder with java or visual studio with c++ For now I treid eric3 and IDLE they don't do this... The ActiveState python editor (pythonwin?) does this. To be clear: ActivePython (ActiveState's distro of Python) includes the PyWin32 extensions by default on Windows. PyWin32 is an open source set of extensions for Python on Windows. The PyWin32 extensions include a Python editor called Pythonwin. http://www.activestate.com/Products/ActivePython/ http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/about.html ActiveState also has a product called Komodo that is an IDE for a number of dynamic languages: Python, Perl, PHP, Tcl, etc. http://www.activestate.com/Products/Komodo/ For Visual Studio users, ActiveState also has a VS.NET plugin for Python (Visual Python), and plugins for Perl and XSLT as well. http://www.activestate.com/Products/Visual_Python/ Cheers, Trent -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
implicit variable declaration and access
Is there any reflective facility in python that I can use to define a variable with a name stored in another variable ? like I have : x = myVarName what can I do to declare a new variable with the name of the string stored in x. And how can I access that implicitly later ? -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
Dan Sommers wrote: On Mon, 13 Jun 2005 15:12:54 GMT, William Gill [EMAIL PROTECTED] wrote: I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Let the DB-API do more work for you: cursor = connection.cursor( ) sql = SELECT column2, columns3 FROM table WHERE name LIKE %s values = ('%%%s%%' % searchterm,) # note that this is a tuple cursor.execute( sql, values ) HTH, Dan I can't tell you how many times I looked at the table of format codes and missed this. Thanks everyone! -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Mon, 13 Jun 2005, Roy Smith wrote: O(2) behavior Um ... Lisp, of course, expanded my mind in ways that only Lisp can (the same could be said for many things I tried back in those days). Surely you're not saying you experimented with ... APL? I think it's probably just as important for a CS major to play with those mind-altering languages as it is to worry about bytes and pointers and memory locations. But you can't start everywhere, and if you've got to start someplace, Python let's you concentrate on the real universal fundamentals of data structures, algorithms, and control flow without getting bogged down in details. Ah, so you've cleaned yourself up with Guido's Twelve-Step Plan. Amen to that, brother! tom -- Why do we do it? - Exactly! -- http://mail.python.org/mailman/listinfo/python-list
Re: What is different with Python ?
On Monday 13 June 2005 12:55 am, Andrea Griffini wrote: On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith [EMAIL PROTECTED] wrote: How far down do you have to go? What makes bytes of memory, data busses, and CPUs the right level of abstraction? They're things that can be IMO genuinely accept as obvious. Hah! Try explaining them to my non-programmer mother or my 9-year-old son. On the other hand, telling them that Python attaches a label (or name) to an object (which can be anything) was a cinch. Both want to program, but are currently still struggling with basic concepts. Interestingly, my son had no problem at all with the name versus variable distinction -- that seems to be a case where my C experience caused me problems, but it's a non-issue coming from a tabula rasa perspective. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree Namespace Prefixes
Fredrik Lundh wrote: Chris Spencer wrote: If an XML parser reads in and then writes out a document without having altered it, then the new document should be the same as the original. says who? Good question. There is no One True Answer even within the XML standards. It all boils down to how you define the same. Which parts of the XML document are meaningful content that needs to be preserved and which ones are mere encoding variations that may be omitted from the internal representation? Some relevant references which may be used as guidelines: * http://www.w3.org/TR/xml-infoset The XML infoset defines 11 types of information items including document type declaration, notations and other features. It does not appear to be suitable for a lightweight API like ElementTree. * http://www.w3.org/TR/xpath-datamodel The XPath data model uses a subset of the XML infoset with only seven node types. http://www.w3.org/TR/xml-c14n The canonical XML recommendation is meant to describe a process but it also effectively defines a data model: anything preserved by the canonicalization process is part of the model. Anything not preserved is not part of the model. In theory, this definition should be equivalent to the xpath data model since canonical XML is defined in terms of the xpath data model. In practice, the XPath data model defines properties not required for producing canonical XML (e.g. unparsed entities associated with document note). I like this alternative black box definition because provides a simple touchstone for determining what is or isn't part of the model. I think it would be a good goal for ElementTree to aim for compliance with the canonical XML data model. It's already quite close. It's possible to use the canonical XML data model without being a canonical XML processor but it would be nice if parse() followed by write() actually passed the canonical XML test vectors. It's the easiest way to demonstrate compliance conclusively. So what changes are required to make ElementTree canonical? 1. PI nodes are already supported for output. Need an option to preserve them on parsing 2. Comment nodes are already support for output. Need an option to preserve them on parsing (canonical XML also defines a no comments canonical form) 3. Preserve Comments and PIs outside the root element (store them as children of the ElementTree object?) 4. Sorting of attributes by canonical order 5. Minor formatting and spacing issues in opening tags oh, and one more thing... 6. preserve namespace prefixes ;-) (see http://www.w3.org/TR/xml-c14n#NoNSPrefixRewriting for rationale) -- http://mail.python.org/mailman/listinfo/python-list
Re: implicit variable declaration and access
Ali Razavi wrote: Is there any reflective facility in python that I can use to define a variable with a name stored in another variable ? like I have : x = myVarName what can I do to declare a new variable with the name of the string stored in x. And how can I access that implicitly later ? Got it! use higher order functions like Lisp! code = x + '= 0' exec(code) code = 'print ' + x exec(code) -- http://mail.python.org/mailman/listinfo/python-list
Re: case/switch statement?
On Sunday 12 June 2005 07:33 am, Dan Sommers wrote: There is no case statement in Python. If you don't care about readability, one alternative is to use a dictionary: case = {5: do_this, 6: do_that} case.get(x, do_something_else)() I find this very readable. YMMV. Yeah, and I find this even more so: case = { 5: do_this, 6: do_that, } case.get(x, do_default)() Which is looking pretty close to a case statement, anyway. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
Dan Sommers wrote: Let the DB-API do more work for you: cursor = connection.cursor( ) sql = SELECT column2, columns3 FROM table WHERE name LIKE %s values = ('%%%s%%' % searchterm,) # note that this is a tuple It looks like this might be a rare case where not using the % operator might make it easier to see what's going on: values = ('%' + searchterm + '%',) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter app structure
On Mon, 13 Jun 2005 16:45:11 +0100, Richard Lewis [EMAIL PROTECTED] said: Whats going wrong? Is it a 'circular import'? Is there a better way that I could organise these modules? I've got a hack which I'm not happy with: I've got rid of the main.py module and put its code into the same module as the MainWindow class is defined in. I don't like this because I want to be able to have a top level module which creates a user interface object (from a class which lives somewhere else) and a data object (from a class which lives somewhere else) and begins the event loop all in a very transparent and easy to read way. As it is now, the entry level code is tucked away at the bottom of a large user interface defining class and doesn't logically belong there. Richard :-( -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
Xavier Décoret wrote: What I wanted to do is something like this: def change(x,v): x = v class A(object): def __init__(self,v): self.x = v a = A(3) print a.x # displays 3 change(a.x,4) print a.x # still displays 3 How about this? def change(x, v): x.x = v Then call it with change(a, 4) And print a.x will return 4 as you wish. It may seem weird, but I ensure there is a reason for doing this. In C++ (the language I am mot familiar with), I could define f to take a pointer to member function of a class, a pointer and a value and achieve what I want. In Python the closest match to this might be to pass the reference to the object, plus the *name* of the attribute, as a string. def change(obj, attr, v): setattr(obj, attr, v) This, of course, is now a useless function since that's what setattr already does... So: a = A(3) print a.x # displays 3 setattr(a, 'x', 4) print a.x # displays 4 -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: implicit variable declaration and access
Ali Razavi wrote: Ali Razavi wrote: Is there any reflective facility in python that I can use to define a variable with a name stored in another variable ? Got it! use higher order functions like Lisp! No, you use higher order functions like Python. :) code = x + '= 0' exec(code) You should generally stay away from exec for lots of reasons. I won't elaborate but a search of this group would be informative. If you want to affect the globals (which you probably don't) you can do this: x = 'my_var' globals()[x] = 7 my_var 7 If you want to set an attribute on a particular object (which is more likely), you can do this: class C: ... pass ... c = C() setattr(c, x, 8) c.my_var 8 code = 'print ' + x exec(code) Getting the value would be like this, respectively: print globals()[x] 7 getattr(c, x) 8 HTH -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
harold fellermann [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] if you write a=A() an instance of class A is created and bound to the local identifier 'a'. I think it perhaps better to think of the label 'a' being bound to the object rather than vice versa. For one, a label can only be bound (stuck to, like a stick note) to one object at a time while one object can have many labels (and other references) stuck to it. If you later write a=5 the object 5 is reassigned to the same identifier, Or one could say that the label 'a' is removed from the A() object and reassigned to the 5 object. Since the 5 object may have numerous other connections, and since those connections are unaffected by the new connection to 'a', whereas the previous assignment of 'a' is broken, I think it better to say that 'a' is being reassigned, not 5. deleting whatever value was stored there before. In memory-oriented languages, such as C, names refer to chunks of memory where values are stored and deleted. Assigning a new value to a variable puts a new value in that chunk of memory, necessarily overwriting the old. In object-oriented Python, objects have values and possibly multiple associations with names and slots. If, but only if, 'a' was the last association of its last assigned-to object, then that object is eligible for deletion. In other words: identifiers don't have types. This and the following I agree with. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 19:23, Terry Reedy wrote: harold fellermann [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] if you write a=A() an instance of class A is created and bound to the local identifier 'a'. I think it perhaps better to think of the label 'a' being bound to the object rather than vice versa. For one, a label can only be bound (stuck to, like a stick note) to one object at a time while one object can have many labels (and other references) stuck to it. If you later write a=5 the object 5 is reassigned to the same identifier, Or one could say that the label 'a' is removed from the A() object and reassigned to the 5 object. Since the 5 object may have numerous other connections, and since those connections are unaffected by the new connection to 'a', whereas the previous assignment of 'a' is broken, I think it better to say that 'a' is being reassigned, not 5. yeah. I have never seen it this way, but you are right! Binding the identifier/label to the object is a much better perspective. thanks for the lesson :) - harold - -- Ceci n'est pas une signature. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess module and blocking
Robin Becker [EMAIL PROTECTED] writes on Sun, 12 Jun 2005 09:22:52 +: I'm using a polling loop in a thread that looks approximately like this while 1: p = find_a_process() rc = p.poll() if rc is not None: out, err = p.communicate() #deal with output etc sleep(1) I notice that under both win32 and freebsd that things are fine provided that the subprocess doesn't write too much to stdout/stderr. However, the subprocess seems to lock often if too much is written (under freebsd I see a process state of POLL). I assume that the subprocess is filling up the pipe and then failing to wake up again. I had expected that subprocess would take care of this for me, You just found out that this is not the case. The warning attached to communicates docstring might have you averted: Note: the data read is buffered in memory... do not use for large size. If subprocess would do what you expect, it would need to buffer the output (to make room in the pipes again). But, for large data, this could have dramatic consequences. Thus, you should use select on the pipes to find out when to read data. Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: implicit variable declaration and access
Benji York [EMAIL PROTECTED] writes: [snap] code = x + '= 0' exec(code) You should generally stay away from exec for lots of reasons. Code 'refactorizability' is one of them. -- http://mail.python.org/mailman/listinfo/python-list
Re: case/switch statement?
Terry Yeah, and I find this even more so: Terry case = { Terry 5: do_this, Terry 6: do_that, Terry } Terry case.get(x, do_default)() Terry Which is looking pretty close to a case statement, anyway. Sure, modulo namespace issues. Skip -- http://mail.python.org/mailman/listinfo/python-list