Re: Frankenstring
Thomas Lotze wrote:
> It's definitely no help that file-like objects are iterable; I do want
> to get a character, not a complete line, at a time.
Hi,
if i did understand what you mean, what about using mmap? Iterating over
characters in a file like this:
# -*- coding: iso-8859-1 -*-
import os
import mmap
f = open("file.txt", "r+")
size = os.path.getsize("file.txt")
m = mmap.mmap(f.fileno(), size)
for x in m:
print x
m.close()
f.close()
--
http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
Steven Bethard <[EMAIL PROTECTED]> writes: > $ python -m timeit "for x in (i for i in xrange(10)): y = x" > 10 loops, best of 3: 4.75 usec per loop Yowza! One of the features I really liked in Perl has shored Python island somewhere in the 2.4'ies, it seems[1]. Thanks for the tip! PS. In case it wasn't clear what I referred to, it was the ability to run given module as a script. Of course you could supply full path to timeit.py: $ python2.3 /usr/lib/python2.3/timeit.py \ "for x in [i for i in xrange(10)]: y = x" 10 loops, best of 3: 9.96 usec per loop But using -m makes it much more convenient. Footnotes: [1] Well, not exactly equal to -M in Perl, but close enough for timing stuff -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! You shouldn't verb verbs. -- http://mail.python.org/mailman/listinfo/python-list
Reading network interface data in linux
Suppose one wants to fetch the following data from given network interface,
say, eth0:
>>> Ethinf('eth0').addr()
'192.168.1.42/24'
>>> Ethinf('eth0').route('default')
'192.168.1.1'
>>> Ethinf('eth0').duplex()
'full'
>>> Ethinf('eth0').speed()
100
Some statistics:
>>> Ethstat('eth0').rx_bytes()
14325235341223
>>> Ethstat('eth0').tx_bytes()
2513152423
One could implement modules by installing eg. ethtool and reading speed/duplex
information by parsing ethtool output, but it is ugly way to do it, prone to
errors, requires launching a process as well as installation of ethtool.
As for the byte counts, you could get all information ifconfig show by reading
/proc/net/dev (which is more nice to parse), but it seems like those counters
are 32-bit, and they wrap around quite quickly in a 1000 gbit network (~30
seconds).
I was wondering is there really no module implemented which already does those
things?
I've already implemented a proto by doing exactly as I told (parsing ethtool &
/proc/net/dev), but I strive for more elegant solution. I'm willing to join
the effort with someone else, if possible.
--
#!/usr/bin/perl -w
$h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14,
72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26,
69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b}
keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'',
map{lc}($1,substr $2,4,1)),2,4)."\n"; print;
--
http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Thomas Lotze wrote:
> I think I need an iterator over a string of characters pulling them out
> one by one, like a usual iterator over a str does. At the same time the
> thing should allow seeking and telling like a file-like object:
>>> from StringIO import StringIO
>>> class frankenstring(StringIO):
... def next(self):
... c = self.read(1)
... if not c:
... raise StopIteration
... return c
...
>>> f = frankenfile("0123456789")
>>> for c in f:
... print c
... if c == "2":
... break
...
0
1
2
>>> f.tell()
3
>>> f.seek(7)
>>> for c in f:
... print c
...
7
8
9
>>>
A non-intrusive alternative:
>>> def chariter(instream):
... def char(): return instream.read(1)
... return iter(char, "")
...
>>> f = StringIO("0123456789")
>>> for c in chariter(f):
... print c
... if c == "2": break
...
0
1
2
>>> f.tell()
3
Performance is probably not so good, but if you really want to do it in C,
with cStringIO you might be /almost/ there.
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: Slicing every element of a list
Alex Dempsey wrote:
> Recently I tried to slice every element of a list of strings. First I tried:
>
> f = open("export.xls", "r")
http://www.python.org/doc/2.4.1/lib/module-csv.html
(snip, see other posts in this thread)
--
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: Should I use "if" or "try" (as a matter of speed)?
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> My opinion is, no, you don't need to be a C programmer, or an assembly
> programmer, or a hardware level physicist who understands NAND gates, but
> it is very useful to have some understanding of what is going on at the
> low-level implementation.
Yes, I fully agree: in the example presented, it is sufficient to understand
that string concatenation is (relatively) expensive. Yet I'd emphasize that
most often speed is improved by better algorithms, not by low-level
optimisations and language-specific features (if speed is even an issue, that
is).
> The way I see it, programmers need to be somewhat aware of the eventual
> optimization stage in their program, so as to avoid poor design choices
> from the start. But you can't always recognise poor design up front, so
> even more important is careful encapsulation and design, so you
> can make significant implementation changes without needing to throw away
> your work. (Well, that's the theory.)
So true, extra emphasis on encapsulation and independence. Even seasoned
professionals fail to create dazzling products at version 1.0. Good component
design is crucial because you eventually want to do major rewrites later.
--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!
$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
--
http://mail.python.org/mailman/listinfo/python-list
Re: Web App like Google
Thanks for making me aware of the security loophole of the web app i am planning. Godwin Burby -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I use "if" or "try" (as a matter of speed)?
Peter Hansen <[EMAIL PROTECTED]> writes: >> "first make it work, then make it right, then make it fast" ... > The expression describes (most recently, if not originally) the practice in > Test-Driven Development (TDD) of making your code pass the test as quickly as > possible, without worrying about how nice it is. Ack(nowledged). > The "right" part doesn't refer to correctness, but to structure, style, > readability, and all those other nice things that an automated test can't > check. You aren't doing it "wrong" at first, just expediently. Yes, that I understood; if the first version worked, it had to be correct already. But as I said, if you want to make ideas easy to remember, you have to make them short enough, and you can probably assume the reader understands more than what is explicitly stated. I didn't know the expression originates from TDD, that puts it in a bit different light - and makes it more understandable IMO. > And it really does make sense, because at that early stage, you aren't even > absolutely certain that your test is entirely correct, so making your code a > paragon of elegance is a potential waste of time, ^^^ :-D Which is a seductive trap, that.. really, I mean, how many times you've polished a module so much that you would want to publish it in every single article you write about computing as an ideal example, one you care about and nurture like it was your own child (or your fancy-schmancy, model '74 V12-engine, chrome-plated, mean monster-of-a-vehicle car, if you are one of those types)? Then you report your progress to your superior and feel ashamed because the only thing you've worked with in last 3 weeks is that (my) precious(!) module.. hum. But I digress. > and distracting. Once you've been able to pass that test (and all the > others, since you have to make sure all previous tests still pass as well), > then and only then is it sensible > -- and required! -- to refactor the code to make it elegant, concise, clean, > etc. Yep. And thats one of the reasons I really like TDD and unit testing - you know when to stop working with a piece of code. When all the tests pass, stop. > Of course, your point about temptation is sound. Extreme Programming tries > to avoid that problem partly by pairing programmers together, and it is the > responsibility of both partners to encourage^H^H^H^H^H insist that the > refactor "make it right" stage must occur _now_, before we check the code > in. If you skip this step, you're failing to be an agile programmer, and > your code base will become a tar pit even more quickly than it would in a > traditional (non-agile) project... Yup. Too bad I've had the opportunity to work that way (pair programming) only few times, and even then it wasn't XP-style in any other way. It is too often considered waste of labour, I guess. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: Existance of of variable
Am Montag, den 04.07.2005, 20:25 -0400 schrieb Roy Smith: > Steven D'Aprano <[EMAIL PROTECTED]> wrote: > > Should we *really* be encouraging newbies to mess with globals() and > > locals()? Isn't that giving them the tools to shoot their foot off before > > teaching them how to put shoes on? > > Why risk damaging perfectly good footwear? > > But, seriously, I agree with you. The cannonical way to tell if a variable > exists in Python is to try to access it and catch any resulting NameError. Although it should be said that this goes only for variables. obj.value isn't such a beast (even if some newbies might think so), and would throw an AttributeError. Another thing to consider when it comes to footwear: Ruining it once and enduring the resulting discomfort teaches quite well. And leaves a respect for the "magic" features of Python that stays the rest of one's life :) So I think every newbie at some time of his/her learning process should probably have fun with all the cool features of Python (be it globals(), assigning to __builtins__, __getattr__ and derived classes, or what ever ;) ). Playing alone is not enough, but playing and living to maintain the code afterwards is very educative ;) OTOH, perhaps for me it was teaching more, because I have been forced to maintain by first bigger python application almost for a decade. One learns quite a bit about software engineering this way ;) Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Montag, den 04.07.2005, 15:36 -0400 schrieb Jeffrey Maitland: > Hello all, > Ok, first thing to consider is that time.sleep in Python does in reality (on Debian Linux, Python2.3) a select syscall with 3 NULLs to wait the time. (The "real" sleep POSIX call might have stupid interactions with signals, to be specific SIGALRM) Don't have a Python source at the moment (I'm offline at the moment) to check how it's done in Win32. > I am in the process of writing a multithreading program and what I was > wondering is a sleep command in an executing function will affect the > threads below it? Here is a basic example of what I mean. > > def main(): >temp_var = True >while temp_var == True: >if > t = threading.Thread( target = func1, args = "String") #note > this is probably non functional (example purposes for the question > only) > t.start() > temp_var = t.isAlive() >else: >print "This line should display a lot" >sleep(2) > > def func1(s): > print s > > so the question I was wondering is if the sleep will pause the t > thread as well as the main function or is the thread independat of the > main function sleep? Well, your program seems to be non-functional (missing if expression?), but as I said above, the main thread waits via select, so the child process should be able to run in this time (assuming time.sleep releases the GIL, but I'd file it as a bug if it doesn't). Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Dienstag, den 05.07.2005, 08:37 -0700 schrieb Jonathan Ellis: > In many ways, Python is an incredibly bad choice for deeply > multithreaded applications. One big problem is the global interpreter > lock; no matter how many CPUs you have, only one will run python code > at a time. (Many people who don't run on multiple CPUs anyway try to > wave this off as a non-problem, or at least worth the tradeoff in terms > of a simpler C API, but with multicore processors coming from every > direction I think the "let's pretend we don't have a problem" approach > may not work much longer.) Well, it's not a tradeoff in a simpler C API. It's a more complicated thing. Much more complicated. ;) Basically nobody has been able to propose a sensible solution for removing the GIL. Any solution would have to have the following properties: a) must be safe. b) should be probably not slow as a snail ;) The problem with a) is that loosing this property is not a proposition. As it is probably a core benefit of Python. So the ceval function would have to lock any object used it encounters when executing. Trouble: How to deal with deadlocks. And it would entail locking and unlocking heaps of objects on any line of Python code. Basically the current state of art in "threading" programming doesn't include a safe model. General threading programming is unsafe at the moment, and there's nothing to do about that. It requires the developer to carefully add any needed locking by hand. Any error in doing that will give very hard to debug errors that might show up only in very specific hardware configurations. And there is no way to detect these errors automatically, which would be needed to raise a nice exception, which is the standard at the moment in Python. > > If the GIL isn't an issue (and in your case it clearly is), you'll > quickly find that there's little support for debugging multithreaded > applications, and even less for profiling. As I've said above, there is a case that the current "safe computing" model of Python isn't compatible with the current state of art in threading. > > Sometimes running multiple processes is an acceptable workaround; if > not, good luck with the rewrite in Java or something else with real > thread support. (IIRC Jython doesn't have a GIL; that might be an > option too.) Jython might not have a GIL, but it probably will be have really bad performance because it has to lock all kind of objects during executation. > > Python is a great tool but if you really need good threading support > you will have to look elsewhere. Yes and no. For a completely general threading support, Python isn't probably what one wants. OTOH general threading developement is a bit more painful than many application developers want to endure. There are ways to do a more structured threading in Python quite ok: a) rewrite your number crunching thread stuff in C and release the GIL. b) if you've got a task that can live with less communication -> one might fork of some computation and communicate the results via pipe. c) Live with the GIL. While multi-core CPUs are coming, it will a time before the mainstream hardware will get to more than 2 logical CPUs. You get quite a bit of speedup already by delegating all the OS and other background tasks to one CPU core. And one thing one shouldn't forget is that finely multithreaded apps aren't faster magically. If you spend need to add 50% more work for locking, you will not get many benefits from threading on a 2 core box: Assuming a two-core box does have about the processing power of 1.8 cores (because of memory contentation, and other problems. Depending upon use and the exact hardware it might be even worse than that). Now your single-threaded app runs 10seconds. With locking this would be about 15seconds. 15 seconds divided by 1.8 gives 8.33seconds. And that assumes that your application is perfectly threadable and will have no contentation for data between it's threads. And it assumes a favorable 1.8 speedup factor for 2 cores. And the hardware level overhead for more cores goes up, especially if you run multiple threads of one program -> because the fine interaction between this threads raises the contentation for data between the cores/processors. So, yes Python isn't multithreading well. At least not at the moment. But this is basically there isn't currently a theoretical way to provide the environment that Python does safely in a multithreaded app without an incredible performance hit. Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Donnerstag, den 07.07.2005, 22:56 + schrieb Grant Edwards: > Oh. I assumed that CPython used Posix threads on Posix It does. > platforms. At least in my experience under Linux, libpthread > always creates an extra "manager" thread. Though in our case It probably does. But it will probably not show as a Python thread. Without some special interfacing with the Python/C API any thread created in C will not show up in Python. > that thread probably wouldn't be running a Python interpreter. Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Mittwoch, den 06.07.2005, 04:00 + schrieb Dennis Lee Bieber:
> {I'm going to louse up the message tracking here by pasting part of
> your
> follow-up into one response}
>
> 2> Upon further thought, that just can't be the case. There has
> 2> to be multiple instances of the intepreter because the
> 2> interpreter can make C system calls that block (thus blocking
> 2> that instance of the interpreter). Other Python threads within
> 2> the program continue to run, so there must be multiple Python
> 2> intepreters.
>
> From the documentation:
>
> """
> The lock is also released and reacquired around potentially blocking
> I/O
> operations like reading or writing a file, so that other threads can
> run
> while the thread that requests the I/O is waiting for the I/O
> operation
> to complete.
> """
>
> It will take someone who's actually worked on the runtime
> interpreter, or studied the code, to, uhm, "interpret" all the above
> tidbits...
Not really, it's quite trivial. Anything that touches the Python/C API
needs the GIL.
[Python] <--Python/C API --> [Python module in C] <--some API--> [legacy C
code]
Now a well behaved Python C module does release the GIL before doing
anything that might block/take a long time.
The drawback in a Python with threading support that runs just one
thread is the additional locking overhead. OTOH it's only done for
operatations that will probably take a long time anyway. (And long is a
relative term here *g*).
Andreas
signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
--
http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Mittwoch, den 06.07.2005, 14:38 + schrieb Grant Edwards: > > Unfortunately that means you've got to debug a number cruncher > that's written in C. If one is careful, one can use Pyrex :) Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: threads and sleep?
Am Mittwoch, den 06.07.2005, 12:27 -0700 schrieb Jonathan Ellis: > Your sarcasm is cute, I suppose, but think about it for a minute. If > the opposite of what I assert is true, why would even the mainstream > press be running articles along the lines of "multicore CPUs mean > programming will get tougher because locking is hard to get right and Easy ;) They run these articles, because -) they have copied it from the press releases. -) it's partly true. -) it's the current hype in processors. That doesn't change the contrary facts: -) the general threading programming model is very hard to get right. It's basically at the moment where we were with memory management at C level. Painful, and errorprone. Nothing to be happy about. -) There is a spectrum of problems from "requires to be run in sequence" to can be run on as many "work slaves via the internet". Fact is that Python is bad at a certain slice (can benefit from tightly interoperating threads). And that will not change that quickly, because there are certain problems. But Python works quite well for the neighboring segments, and it got a number of solutions for a number of problems in this segment. (Be it Twisted, forking, threads + GIL, etc.) Andreas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Roland Heiber wrote: > if i did understand what you mean, what about using mmap? AIUI (and as a little experimenting seems to confirm), you can't reposition an iterator over an mmap'ed file by seeking. True, you have both iterating by characters and seeking/telling, but the two functionalities don't play together. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Bengt Richter wrote:
> < lotzefile.py >--
Thanks.
[...]
> byte = self.buf[self.pos]
This is the place where the thing is basically a str whose items are
accessed as sequence elements. It has some iterator behaviour and file
management which makes it nice to use, of course, and to most this will
be enough (and it is a lot indeed). But it loses the efficiency of
for c in "asdf": do_something(c)
Actually, relying on string[index] behind the scenes is one of the ways
of implementing frankenstring I labelled "clumsy" in the original
posting ;o)
> I suspect you could get better performance if you made LotzeFile instances
> able to return interators over buffer chunks and get characters from them,
> which would be string iterators supplying the characters rather than the
> custom .next, but the buffer chunks would have to be of some size to make
> that pay. Testing is the only way to find out what the crossing point is,
> if you really have to.
If I understand this correctly, you'd have to switch to using a new iterator
after seeking, which would make this impossible:
f = LotzeFile('something')
for c in iter(f):
do_something(c)
if some_condition:
f.seek(somewhere)
# the next iteration reads from the new position
And it would break telling since the class can't know how many
characters have been read from an iterator once it returned one after
seeking or switching to another buffer chunk.
--
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Peter Otten wrote: class frankenstring(StringIO): > ... def next(self): > ... c = self.read(1) > ... if not c: > ... raise StopIteration > ... return c Repeated read(1) on a file-like object is one of the ways of doing it with existing tools I labelled "clumsy" in the original posting ;o) Thanks anyway. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
reg php equivalent move_uploaded file function in python
Dear all, Is there any php equivalent move_uploaded_file($source_path, "$upload_dir/$name"); function in python to upload a file to server? Kindly give me answer. regards Prabahar __ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Software needed
Where I could find the TWAIN python interface ? I'm quite interested :)12 Jul 2005 08:44:49 -0700, Peter Herndon <[EMAIL PROTECTED]>: "Document Management Software" is a little vague. What do you want itto do? In general though, when someone says "content management" and "Python", the general response is Zope, usually with Plone on top.--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Software needed
[Fuzzy] > There's a Python interface to TWAIN (the scanner protocol) [Alexis] > Where I could find the TWAIN python interface ? Try typing "python twain" into Google. The first hit is: http://twainmodule.sourceforge.net/ "The Python TWAIN module provides an interface to scanners, digital cameras and other devices which implement TWAIN, for the Windows platform. It provides the functionality to allow a Python application to connect to the scanner/camera and to retrieve images from that device." -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Thomas Lotze wrote: > AIUI (and as a little experimenting seems to confirm), you can't > reposition an iterator over an mmap'ed file by seeking. True, you have > both iterating by characters and seeking/telling, but the two > functionalities don't play together. A quick and dirty hack!? Maybe i'm missing what it is that you need ... class MmapWithSeekAndTell(object): def __init__(self, m, size): self._m = m self._pos = 0 self._size = size-1 def __iter__(self): return self def next(self): if self._pos < self._size-1: self._pos += 1 return self._m[self._pos] raise StopIteration def seek(self, offset, whence=0): if whence == 0 and 0 <= offset < self._size: self._pos = offset elif whence == 1 and 0 <= (self._pos + offset) < self._size: self._pos += offset elif whence == 2 and 0<= (self._size - offset) < self._size: self._pos = self._size - offset def tell(self): return self._pos HtH, Roland -- http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Roland Heiber wrote: > class MmapWithSeekAndTell(object): > def __init__(self, m, size): .. where m is a mmap-object and size the filesize ... sorry. -- http://mail.python.org/mailman/listinfo/python-list
Console logging/output for DocXMLRPCServer
Hello,
I have written simple code using DocXMLRPCServer. How do I log method
name on the console after invoking registered
method on server. On the console it just prints message as [hostname -
date/time and "POST /RPC2 HTTP/1.0" 200 -]
code is:
from DocXMLRPCServer import DocXMLRPCServer
def Test(dummy):
print dummy
return 1
if __name__ == '__main__':
server = DocXMLRPCServer(("", 8000, logRequests = 1))
server.register_function(Test)
server.serve_forever()
-
>>> import xmlrpclib
>>> s = xmlrpclib.Server("http://localhost:8000";)
>>> s.Test("Hello")
Output of console after invoking method Test is:
hostname - - [13/Jul/2005 13:28:04] "POST /RPC2 HTTP/1.0" 200 -
Thanks
Sameer
--
http://mail.python.org/mailman/listinfo/python-list
Re: Software needed
Thank you2005/7/13, Richie Hindle <[EMAIL PROTECTED]>: [Fuzzy]> There's a Python interface to TWAIN (the scanner protocol)[Alexis]> Where I could find the TWAIN python interface ?Try typing "python twain" into Google. The first hit is: http://twainmodule.sourceforge.net/ "The Python TWAIN module provides an interface to scanners, digital cameras and other devices which implement TWAIN, for the Windows platform. It provides the functionality to allow a Python application to connect to the scanner/camera and to retrieve images from that device."--Richie Hindle [EMAIL PROTECTED]--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: math.nroot [was Re: A brief question.]
Tim Peters <[EMAIL PROTECTED]> writes: > [Michael Hudson] > > I doubt anyone else is reading this by now, so I've trimmed quotes > > fairly ruthlessly :) > > Damn -- there goes my best hope at learning how large a message gmail > can handle before blowing up . OK, I'll cut even more. Heh. > [Michael] > >>> Can't we use the stuff defined in Appendix F and header of > >>> C99 to help here? I know this stuff is somewhat optional, but it's > >>> available AFAICT on the platforms I actually use (doesn't mean it > >>> works, of course). > > [Tim] > >> It's entirely optional part of C99. > > > Hmm, is optional? I'm not finding those words. I know > > Appendix F is. > > fenv.h is required, but the standard is carefully worded so that > fenv.h may not be of any actual use. For example, a conforming > implementation can define FE_ALL_EXCEPT as 0 (meaning it doesn't > define _any_ of the (optional!) signal-name macros: FE_DIVBYZERO, > etc). That in turn makes feclearexcept() (& so on) pretty much > useless -- you couldn't specify any flags. Makes sense. > >> The most important example of a compiler that doesn't support any of > >> that stuff is Microsoft's, although they have their own MS-specific > >> ways to spell most of it. > > > OK, *that's* a serious issue. > > > > If you had to guess, do you think it likely that MS would ship fenv.h > > in the next interation of VC++? > > Sadly not. If they wanted to do that, they had plenty of time to do > so before VC 7.1 was released (C99 ain't exactly new anymore). As it > says on > > http://en.wikipedia.org/wiki/C_programming_language > > MS and Borland (among others) appear to have no interest in C99. > > In part I expect this is because C doesn't pay their bills nearly so > much as C++ does, and C99 isn't a standard from the C++ world. This also makes sense, in a slightly depressing way. > >>> In what way does C99's fenv.h fail? Is it just insufficiently > >>> available, or is there some conceptual lack? > > >> Just that it's not universally supported. Look at fpectlmodule.c for > >> a sample of the wildly different ways it _is_ spelled across some > >> platforms. > > > C'mon, fpectlmodule.c is _old_. Maybe I'm stupidly optimistic, but > > perhaps in the last near-decade things have got a little better here. > > Ah, but as I've said before, virtually all C compilers on 754 boxes > support _some_ way to get at this stuff. This includes gcc before C99 > and fenv.h -- if the platforms represented in fpectlmodule.c were > happy to use gcc, they all could have used the older gcc spellings > (which are in fpectlmodule.c, BTW, under the __GLIBC__ #ifdef). Um, well, no, not really. The stuff under __GLIBC___ unsurprisingly applies to platforms using the GNU project's implementation of the C library, and GCC is used on many more platforms than just that (e.g. OS X, FreeBSD). This is all part of the "what exactly are you claiming supports 754, again?" game, I guess. Even given that, the glibc section looks mighty Intel specific to me (I don't see why 0x1372 should have any x-architecture meaning). Now that GCC supports, or aims to support, or will one day support C99 I think you're right in that any GCC-using code can use the same spelling. One thing GCC doesn't yet support, it turns out, is the "#pragma STDC FENV_ACCESS ON" gumpf, which means the optimiser is all too willing to reorder feclearexcept(FE_ALL_EXCEPT); r = x * y; fe = fetestexcept(FE_ALL_EXCEPT); into feclearexcept(FE_ALL_EXCEPT); fe = fetestexcept(FE_ALL_EXCEPT); r = x * y; Argh! Declaring r 'volatile' made it work. > But they didn't, so they're using "minority" compilers. I used to > write compilers for a living, but I don't think this is an inside > secret anymore : there are a lot fewer C compiler writers than > there used to be, and a lot fewer companies spending a lot less > money on developing C compilers than there used to be. Indeed. Also, less architectures and less C libraries. > As with other parts of C99, I'd be in favor of following its lead, and > defining Py_ versions of the relevant macros and functions. Makes sense! > >> A maze of #ifdefs could work too, provided we defined a > >> PyWhatever_XYZ API to hide platform spelling details. > > > Hopefully it wouldn't be that bad a maze; frankly GCC & MSVC++ covers > > more than all the cases I care about. > > I'd be happy to settle for just those two at the start, As with > threading too, Python has suffered from trying to support dozens of > unreasonable platforms, confined to the tiny subset of abilities > common to all of them. If, e.g., HP-UX wants a good Python thread or > fp story, let HP contribute some work for a change. I think we have > enough volunteers to work out good gcc and MSVC stories -- although I > expect libm to be an everlasting headache Well, yes. I think a 'thin wrapper' approach like some of the os module stuff makes sense here. Cheers, mwh
Building a function call?
Hiho,
Having a string: "dothat"
and a tuple: (x, y)
1. What's the best way to build a function call like: dothat(x,y)?
Assuming dothat is def'd in the same module,
2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
the right way to have it executed?
If dothat is def'd in another module:
3. what would be the right way to initialize the globals to pass to eval ?
TIA,
Francois
--
http://mail.python.org/mailman/listinfo/python-list
**kwargs?
All your **kwargs are belong to us. *args is documented in the Tutorial. I reckon **kwargs represents a dictionary of arguments. But I don't quite get the semantics of **x. Undefined length tuple of undefined length tuples? Are there other practical use cases for ** (common enough please, I wish I was, but I'm not a scientist). TIA, Francois -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Francois De Serres wrote:
> Hiho,
>
> Having a string: "dothat"
> and a tuple: (x, y)
> 1. What's the best way to build a function call like: dothat(x,y)?
Not the best (not at all) but one way:
def dothat(x,y):
print "Called with:", x, y
c = (1,2)
locals().get("dothat")(*c)
Called with: 1 2
HtH, Roland
--
http://mail.python.org/mailman/listinfo/python-list
Re: **kwargs?
Francois De Serres wrote:
> All your **kwargs are belong to us.
>
> *args is documented in the Tutorial. I reckon **kwargs represents a
> dictionary of arguments. But I don't quite get the semantics of **x.
> Undefined length tuple of undefined length tuples? Are there other
> practical use cases for ** (common enough please, I wish I was, but I'm
> not a scientist).
>
> TIA,
> Francois
Assume d = { 'arg1':'value1','arg2':'value2' }. Then
func(**d)
is the same as:
func(arg1='value1', arg2='value2')
HtH, Roland
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Roland Heiber wrote:
>Francois De Serres wrote:
>
>
>>Hiho,
>>
>>Having a string: "dothat"
>>and a tuple: (x, y)
>>1. What's the best way to build a function call like: dothat(x,y)?
>>
>>
>
>Not the best (not at all) but one way:
>
>
Still pretty interesting, thx.
>def dothat(x,y):
> print "Called with:", x, y
>
>c = (1,2)
>
>locals().get("dothat")(*c)
>
>
>Called with: 1 2
>
>HtH, Roland
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Searching for metadata related tools for use with python
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 I'm interested in various metadata extraction/prosessing/distribution/something tools(including ways of differentiating between files, eg hashing etc) and especially python enabled ones. I'm also considering content-recognition/differentiating eg. image recognition. I'm already aware of these: python-bitzi, python-musicbrainz, mmpython, IMDbPY, python-mhash and imgSeek. If you could point me to other relating resources it would be great. Elmo -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFC1Q3WctNFyQJObrsRAjXbAJ92B53YC9NqtC9nymK07OL+L3mNTwCgmlbb dPfSDsqJzBh+xa3h5L28Qac= =AtAo -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Roland Heiber wrote:
> Not the best (not at all) but one way:
>
> def dothat(x,y):
> print "Called with:", x, y
>
> c = (1,2)
>
> locals().get("dothat")(*c)
As you say, not the best, but in fact not really advisable under any
circumstances. locals() returns "module level" stuff only when executed
_at_ module level (i.e. not inside a function). Otherwise it will
return only the local variables of the frame its in.
Better is this, since it works for the OP's requirements in either
situation.
globals()['dothat'](*c)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: **kwargs?
Francois De Serres wrote: > All your **kwargs are belong to us. > > *args is documented in the Tutorial. I reckon **kwargs represents a > dictionary of arguments. But I don't quite get the semantics of **x. > Undefined length tuple of undefined length tuples? Are there other > practical use cases for ** (common enough please, I wish I was, but I'm > not a scientist). Where did you get "tuples of tuples" for **x ? It doesn't have tuples at all, but is merely a dictionary, as you said in the first place. Are you implying you think **kwargs and **x are somehow magically different? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Francois De Serres wrote:
> Having a string: "dothat"
> and a tuple: (x, y)
> 1. What's the best way to build a function call like: dothat(x,y)?
>
> Assuming dothat is def'd in the same module,
> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
> the right way to have it executed?
>
> If dothat is def'd in another module:
> 3. what would be the right way to initialize the globals to pass to
> eval ?
>
No, none of this is a good place to use eval.
aString = "dothat"
atuple = (x, y)
If aString is the name of a function in the current module:
globals()[aString](*aTuple)
If aString is a function in another module:
import otherModule
vars(otherModule)[aString](*aTuple)
and if you don't know the name of the module in advance:
otherModule = __import__(nameOfOtherModule)
vars(otherModule)[aString](*aTuple)
Better still, collect all the functions you expect to be callable in this
way together in a dictionary and then you can be sure that you only call
something you intended to be callable.
--
http://mail.python.org/mailman/listinfo/python-list
Re: **kwargs?
Peter Hansen wrote: > Francois De Serres wrote: > >> *args is documented in the Tutorial. I reckon **kwargs represents a >> dictionary of arguments. But I don't quite get the semantics of **x. >> Undefined length tuple of undefined length tuples? Are there other >> practical use cases for ** (common enough please, I wish I was, but >> I'm not a scientist). > > Where did you get "tuples of tuples" for **x ? I would guess it is confusion from languages where unary * means dereference and ** means double dereference. To the OP: I'm glad you have been reading the tutorial. If you have further questions the reference manual is a good place to look: http://docs.python.org/ref/function.html Just as you can use a name other than self as the first argument to an unbound method, you can call your *args and **kwargs *x and **y instead, but they will still act just like *args and **kwargs. The stars are magic, not the names. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: reg php equivalent move_uploaded file function in python
praba kar enlightened us with: > Is there any php equivalent move_uploaded_file($source_path, > "$upload_dir/$name"); function in python to upload a file to server? move_uploaded_file does NOT upload a file to a server. > Kindly give me answer. Kindly ask answerable question. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Normally when I want to do what you describe I want to
do it for several functions not just a single one.
You can use a dictionary to hold the function names and
pointers to the functions themselves and then call them
by indexing into the dictionary. This works for me:
def dothat(x,y):
print "x=", x, " y=", y
return
def doanother(x, y, z):
print "x=", x, " y=", y, " z=", z
return
xdict={'dothat': dothat,
'doanother': doanother}
s='dothat'
t=(1,2)
xdict[s](*t)
results in:
x= 1 y= 2
s='another'
t=(1,2, 3)
xdict[s](*t)
results in:
x= 1 y= 2 z=3
Larry Bates
Francois De Serres wrote:
> Hiho,
>
> Having a string: "dothat"
> and a tuple: (x, y)
> 1. What's the best way to build a function call like: dothat(x,y)?
>
> Assuming dothat is def'd in the same module,
> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
> the right way to have it executed?
>
> If dothat is def'd in another module:
> 3. what would be the right way to initialize the globals to pass to eval ?
>
>
> TIA,
> Francois
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Defending Python
Jorey Bump wrote: > > Monty Python's Flying Circus used to begin with "It's..." I had read at one > time that "It's" was one of the original names proposed for the > troupe/show, although I can't seem to find verification. "In fact, one of the titles of the show was 'It's', so he must have been in there fairly early on. On a list of titles I've got scribbled in a notebook was 'It's' and just 'It,' so that's probably where he came from." -- Michael Palin (referring to the "It's" man) in _The First 20 Years of Monty Python_ by Kim "Howard" Johnson (St. Martin's Press, 1989), p.20 -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * [EMAIL PROTECTED] // http://bgporter.inknoise.com/JerseyPorkStore -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Peter Hansen wrote:
>Roland Heiber wrote:
>
>
>>Not the best (not at all) but one way:
>>
>>def dothat(x,y):
>> print "Called with:", x, y
>>
>>c = (1,2)
>>
>>locals().get("dothat")(*c)
>>
>>
>
>As you say, not the best, but in fact not really advisable under any
>circumstances. locals() returns "module level" stuff only when executed
>_at_ module level (i.e. not inside a function). Otherwise it will
>return only the local variables of the frame its in.
>
>Better is this, since it works for the OP's requirements in either
>situation.
>
> globals()['dothat'](*c)
>
>-Peter
>
>
Actually that's part of my dilemma... I guess the function name is
moreoften in globals().
But the parameters in the tuple are
A) formals (that was not clear in my OP, sorry),
B) once bound by another function, I they'll become part of locals().
func = "dothat"
args = (x,y)
localcontext = ()
r = None
while r is None:
try:
r = eval("dothat(x,y)", None, localcontext) #how do I construct
"dothat(x,y)"?
except NameError:
ensure_context(x,y) #find/compute the formals, eg: localcontext
= (('x', 100), ('y', 200))
F.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Duncan Booth wrote:
> Francois De Serres wrote:
>
>>Having a string: "dothat"
>>and a tuple: (x, y)
>>1. What's the best way to build a function call like: dothat(x,y)?
>>
>>Assuming dothat is def'd in the same module,
>>2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
>>the right way to have it executed?
>>
>>If dothat is def'd in another module:
>>3. what would be the right way to initialize the globals to pass to
>>eval ?
>
> No, none of this is a good place to use eval.
>
> aString = "dothat"
> atuple = (x, y)
>
> If aString is the name of a function in the current module:
>
>globals()[aString](*aTuple)
>
> If aString is a function in another module:
>
>import otherModule
>vars(otherModule)[aString](*aTuple)
Ick! Please:
getattr(otherModule, aString)(*aTuple)
--
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: **kwargs?
Michael Hoffman wrote: >Peter Hansen wrote: > > >>Francois De Serres wrote: >> >> >> > > > >>>*args is documented in the Tutorial. I reckon **kwargs represents a >>>dictionary of arguments. But I don't quite get the semantics of **x. >>>Undefined length tuple of undefined length tuples? Are there other >>>practical use cases for ** (common enough please, I wish I was, but >>>I'm not a scientist). >>> >>> >>Where did you get "tuples of tuples" for **x ? >> >> > >I would guess it is confusion from languages where unary * means >dereference and ** means double dereference. > > That was precisely my mistake. >To the OP: I'm glad you have been reading the tutorial. If you have >further questions the reference manual is a good place to look: > >http://docs.python.org/ref/function.html > > Now I see, there's a '**' token, which is not the same as two adjacents '*' tokens. >Just as you can use a name other than self as the first argument to an >unbound method, you can call your *args and **kwargs *x and **y instead, >but they will still act just like *args and **kwargs. > >The stars are magic, not the names. > > Thanks mucho! F. -- http://mail.python.org/mailman/listinfo/python-list
Splitting on a word
Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: ' underlined reference' Optimizing my code, I found that an essential step is: splitting on a word (in this case 'href'). I am asking if there is some alternative (more pythonic...): # SplitMultichar.py import re # string s simulating an html file s='ffy: ytrty python fyt wx dtrtf' p=re.compile(r'\bhref\b',re.I) lHref=p.findall(s) # lHref=['href','HREF'] # for normal html files the lHref list has more elements # (more web references) c='~' # char to be used as delimiter # c=chr(127) # char to be used as delimiter for i in lHref: s=s.replace(i,c) # s ='ffy: ytrty python fyt wx dtrtf' list=s.split(c) # list=['ffy: ytrty python fyt wx dtrtf'] #=- If you save the original s string to xxx.html, any browser can visualize it. To be sure as delimiter I choose chr(127) which surely is not present in the html file. Bye. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Data, Storing into an array, Infinite Backslashes
I ended up using this code to solve my problem.
> for a, b, c, d in s:
> if not query.has_key((a,b)): query[(a,b)] = []
>query[(a,b)].append("%s=%s" % (c, d))
> for (a,b), v in query.items():
>print a, b, ", ".join(v)
I'm relatively new to python/programming in general. I usually write
in php and have produced this website and application
http://my-pbs.sf.net One of the things that makes php easy to program
in is the documentation provided at php.net. It is extremely easy to
find the correct functions to use. Are there any sites you could
recommend that discusses structures of loops and strings? I have an
OReilly book called, "Programming Python" and it focuses to much on
showing examples rather than structure and methods.
Thanks for the help.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Peter Hansen wrote:
>> locals().get("dothat")(*c)
This was just meant as a quick example, not as production-level code ;)
Even with globals(), I think its a bit odd ..., but safer than using
eval() ...
HtH, Roland
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call? (update)
Francois De Serres wrote:
>Hiho,
>
>Having a string: "dothat"
>and a tuple: (x, y)
>1. What's the best way to build a function call like: dothat(x,y)?
>
>Assuming dothat is def'd in the same module,
>2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
>the right way to have it executed?
>
>If dothat is def'd in another module:
>3. what would be the right way to initialize the globals to pass to eval ?
>
>
>TIA,
>Francois
>
>
>
>
Sorry, I was unclear about the fact that the args are formals. I'm
trying to do something like:
func = "dothat"
args = ('x','y')
localcontext = ()
r = None
while r is None:
try:
r = eval("dothat(x,y)", None, localcontext) #how do I construct
"dothat(x,y)"? with 'dothat(%s,%s)' % args?
except NameError:
ensure_context(args) #find/compute the formals, eg: localcontext
= (('x', 100), ('y', 200))
F.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Splitting on a word
[EMAIL PROTECTED] wrote: > Hi all, > I am writing a script to visualize (and print) > the web references hidden in the html files as: > ' underlined reference' > Optimizing my code, I found that an essential step is: > splitting on a word (in this case 'href'). > > I am asking if there is some alternative (more pythonic...): For *this* particular task, certainly. It begins with import BeautifulSoup The rest is left as a (brief) exercise for the reader. :-) As for the more general task of splitting strings using regular expressions, see re.split(). -- 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: Building a function call?
On Wed, 13 Jul 2005 06:16:54 -0700, Robert Kern wrote:
> Duncan Booth wrote:
>> Francois De Serres wrote:
>>
>>>Having a string: "dothat"
>>>and a tuple: (x, y)
>>>1. What's the best way to build a function call like: dothat(x,y)?
[snip]
>> No, none of this is a good place to use eval.
[snip]
>>import otherModule
>>vars(otherModule)[aString](*aTuple)
>
> Ick! Please:
> getattr(otherModule, aString)(*aTuple)
Or, remember that functions are first class objects in Python. Instead of
passing around the function name as a string, pass around a reference to
the function itself. Something like this:
def dothis(x,y):
return x-y
def dothat(x,y):
return x+y
somefunction = dothis
somefunction(3, 2)
=> returns 1
somefunction = dothat
somefunction(3, 2)
=> returns 5
allfunctions = [dothis, dothat]
for func in allfunctions:
print func(3, 2)
=> prints 1 then 5
If you want to collect user-supplied strings and use them to find a
function, you could use eval (terribly risky and unsafe), or you could do
something like this:
funcnames = {}
for func in allfunctions:
funcnames[func.__name__] = func
F = raw_input("Enter the name of a function: ")
try:
funcnames[F](3, 2)
except KeyError:
print "Function '%s' not found!" % F
In my humble opinion, people muck about with eval, locals and globals far
too often. It is unclear, hard to maintain, and frequently a security
risk. These confusing, unsafe practices can usually be avoided by
remembering that functions are first class objects just like ints, strings
and lists.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Aloha,
Thomas Lotze wrote:
> I think I need an iterator over a string of characters pulling them out
> one by one, like a usual iterator over a str does. At the same time the
> thing should allow seeking and telling like a file-like object:
f = frankenstring("0123456789")
for c in f:
> ... print c
> ... if c == "2":
> ... break
> ...
> 0
> 1
> 2
f.tell()
> 3L
f.seek(7)
for c in f:
> ... print c
> ...
> 7
> 8
> 9
> I can think of more than one clumsy way to implement the desired
> behaviour in Python; I'd rather like to know whether there's an
> implementation somewhere that does it fast. (Yes, it's me and speed
> considerations again; this is for a tokenizer at the core of a library,
> and I'd really like it to be fast.)
You can already think my answer, because i'm doing this
at the core of a similar library, but to give others
the chance to discuss.
>>> f = "0123456789"
>>> p = 0
>>> t2 = f.find('2')+1
>>> for c in f[p:t2]:
... print c
...
0
1
2
>>> p = 7
>>> for c in f[p:]:
... print c
...
7
8
9
A string, and a pointer on that string. If you give up the
boundary condition to tell backwards, you can start to eat up
the string via f = f[p:]. There was a performance difference
with that, in fact it was faster ~4% on a python2.2.
I dont't expect any iterator solution to be faster than
that.
Wishing a happy day
LOBI
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call? (update)
Francois De Serres wrote:
> Sorry, I was unclear about the fact that the args are formals. I'm
> trying to do something like:
>
> func = "dothat"
> args = ('x','y')
> localcontext = ()
> r = None
> while r is None:
> try:
> r = eval("dothat(x,y)", None, localcontext) #how do I construct
> "dothat(x,y)"? with 'dothat(%s,%s)' % args?
> except NameError:
> ensure_context(args) #find/compute the formals, eg: localcontext
>= (('x', 100), ('y', 200))
I think when your code ends up in as big a mess as this, you need to take a
step back. Forget about asking us how you get at functions or arguments as
strings, instead tell us what problem you are really trying to solve.
I'm pretty sure that whatever your problem is, the solution won't involve
using 'eval', and it almost certainly won't involve looking up variables
or functions from their names.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Steven D'Aprano wrote:
>On Wed, 13 Jul 2005 06:16:54 -0700, Robert Kern wrote:
>
>
>
>>Duncan Booth wrote:
>>
>>
>>>Francois De Serres wrote:
>>>
>>>
>>>
Having a string: "dothat"
and a tuple: (x, y)
1. What's the best way to build a function call like: dothat(x,y)?
>[snip]
>
>
>>>No, none of this is a good place to use eval.
>>>
>>>
>[snip]
>
>
>>> import otherModule
>>> vars(otherModule)[aString](*aTuple)
>>>
>>>
>>Ick! Please:
>>getattr(otherModule, aString)(*aTuple)
>>
>>
>
>
>Or, remember that functions are first class objects in Python. Instead of
>passing around the function name as a string, pass around a reference to
>the function itself. Something like this:
>
>
>def dothis(x,y):
>return x-y
>
>def dothat(x,y):
>return x+y
>
>somefunction = dothis
>somefunction(3, 2)
>=> returns 1
>
>somefunction = dothat
>somefunction(3, 2)
>=> returns 5
>
>allfunctions = [dothis, dothat]
>for func in allfunctions:
>print func(3, 2)
>=> prints 1 then 5
>
>If you want to collect user-supplied strings and use them to find a
>function, you could use eval (terribly risky and unsafe), or you could do
>something like this:
>
>funcnames = {}
>for func in allfunctions:
>funcnames[func.__name__] = func
>F = raw_input("Enter the name of a function: ")
>try:
>funcnames[F](3, 2)
>except KeyError:
>print "Function '%s' not found!" % F
>
>
>In my humble opinion, people muck about with eval, locals and globals far
>too often. It is unclear, hard to maintain, and frequently a security
>risk. These confusing, unsafe practices can usually be avoided by
>remembering that functions are first class objects just like ints, strings
>and lists.
>
>
>
>
>
I'm aware of the functions being objects, but I really need to work with
strings in that case.
Still, I was not aware that eval() was such a 'rogue', it's not said in
the manuals ;)
Many thanks!
F.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call? (update)
Duncan Booth wrote:
>Francois De Serres wrote:
>
>
>
>>Sorry, I was unclear about the fact that the args are formals. I'm
>>trying to do something like:
>>
>>func = "dothat"
>>args = ('x','y')
>>localcontext = ()
>>r = None
>>while r is None:
>>try:
>>r = eval("dothat(x,y)", None, localcontext) #how do I construct
>>"dothat(x,y)"? with 'dothat(%s,%s)' % args?
>>except NameError:
>>ensure_context(args) #find/compute the formals, eg: localcontext
>>= (('x', 100), ('y', 200))
>>
>>
>
>I think when your code ends up in as big a mess as this, you need to take a
>step back. Forget about asking us how you get at functions or arguments as
>strings, instead tell us what problem you are really trying to solve.
>
>I'm pretty sure that whatever your problem is, the solution won't involve
>using 'eval', and it almost certainly won't involve looking up variables
>or functions from their names.
>
>
Sure? okay, let me take the time to formulate a thorough blueprint of my
context, and I'll come back to you...
F.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Web App like Google
a good text indexer will help, look at lupy, pyndex, xapian etc http://www.pypackage.org/packages/python-pyndex http://www.divmod.org/Home/Projects/Lupy/ -- http://mail.python.org/mailman/listinfo/python-list
Re: breaking out of nested loop
[rbt]
> What is the appropriate way to break out of this while loop if the for
> loop finds a match?
>
> while 1:
> for x in xrange(len(group)):
> try:
> mix = random.sample(group, x)
> make_string = ''.join(mix)
> n = md5.new(make_string)
> match = n.hexdigest()
> if match == target:
> print "Collision!!!"
> print make_string
> Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
> print "Stop", Stop
> break
> else:
> continue
> except Exception, e:
> print e
I would wrap the whole thing in a function definition. When you find a
match, just return from the function. Besides cleanly exiting from
multiple loops, the function approach usually leads to better factoring
(in this case, segregating the search logic from everything else).
Raymond
--
http://mail.python.org/mailman/listinfo/python-list
Re: Splitting on a word
On Wed, 13 Jul 2005 06:19:54 -0700, qwweeeit wrote:
> Hi all,
> I am writing a script to visualize (and print)
> the web references hidden in the html files as:
> ' underlined reference'
> Optimizing my code,
[red rag to bull]
Because it was too slow? Or just to prove what a macho programmer you are?
Is your code even working yet? If it isn't working, you shouldn't be
trying to optimizing buggy code.
> I found that an essential step is:
> splitting on a word (in this case 'href').
Then just do it:
py> ' underlined reference'.split('href')
[' underlined reference']
If you are concerned about case issues, you can either convert the
entire HTML file to lowercase, or you might write a case-insensitive
regular expression to replace any "href" regardless of case with the
lowercase version.
[snip]
> To be sure as delimiter I choose chr(127)
> which surely is not present in the html file.
I wouldn't bet my life on that. I've found some weird characters in HTML
files.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Can JEP alone do the job?
Requirement == A JAVA Server(RMI Sever) has to invoke some Python scripts. These Python scripts in turn have to make some JAVA API calls. The JAVA APIs will be provided by custom Java Classes and Interfaces. I should be able to receive the "Output" from the Python script into my JAVA server. "Output" can either be:- 1) std out from Python (print statements inside Python script) OR 2) Python Objects Questions >From the initial literature study, I think I can achieve this ONLY using JEP? However I also find that there is another Integrator "JPype". My question is what do I miss if I don't use JPype? What extra does JPype have? Basically I want to avoid too many Integration technologies and use ONLY JEP (or possibly ONLY JPype.) Regards, skn -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call?
Roland Heiber wrote: > Even with globals(), I think its a bit odd ..., but safer than using > eval() ... Some would agree and claim that using an import is better: c = (1, 2) thisModule = __import__(__name__) func = getattr(thisModule, 'dothat') func(*c) I don't generally find that more readable than the one with globals(), and I don't offhand recall any serious criticism of globals() on grounds of either readability or style, so I'm unsure why anyone would prefer the alternative. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: reg php equivalent move_uploaded file function in python
praba kar wrote: > Is there any php equivalent > move_uploaded_file($source_path, "$upload_dir/$name"); > function in python to > upload a file to server? As this is a Python forum, most will not know PHP. Perhaps describing what you want in plain English would be more effective in getting useful answers. (For example, what kind of server are you talking about?) -Peter -- http://mail.python.org/mailman/listinfo/python-list
all possible combinations
Say I have a list that has 3 letters in it: ['a', 'b', 'c'] I want to print all the possible 4 digit combinations of those 3 letters: 4^3 = 64 abaa aaba aaab acaa aaca aaac ... What is the most efficient way to do this? -- http://mail.python.org/mailman/listinfo/python-list
Re: set and frozenset unit tests?
Jacob Page wrote: > Oye, there's quite a number of set and frozenset features that aren't > well-documented that I now need to implement. What a fun chore! It would be a great help if you could submit appropriate documentation patches for the areas you don't think are well-documented: http://sourceforge.net/tracker/?group_id=5470&atid=305470 STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: removing list comprehensions in Python 3.0
Edvard Majakari wrote: > Steven Bethard <[EMAIL PROTECTED]> writes: > >>$ python -m timeit "for x in (i for i in xrange(10)): y = x" >>10 loops, best of 3: 4.75 usec per loop > > Yowza! One of the features I really liked in Perl has shored Python island > somewhere in the 2.4'ies, it seems[1]. Thanks for the tip! [snip] > But using -m makes it much more convenient. Yup, it showed up in Python 2.4. Great, isn't it? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, 13 Jul 2005 10:21:19 -0400, rbt wrote: > Say I have a list that has 3 letters in it: > > ['a', 'b', 'c'] > > I want to print all the possible 4 digit combinations of those 3 > letters: > > 4^3 = 64 > > > abaa > aaba > aaab > acaa > aaca > aaac > ... > > What is the most efficient way to do this? Efficient for who? The user? The programmer? The computer? Efficient use of speed or memory or development time? If you want the fastest runtime efficiency, a lookup table of pre-calculated values. That is an O(1) operation, and you don't get any faster than that. If you expect to extend the program to arbitrary lists, pre-calculation isn't practical, so you need an algorithm to calculate permutations (order matters) or combinations (order doesn't matter). If you tell us what you need, I'm sure somebody will be able to help meet those needs. Otherwise, we're just guessing what you want. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
i'll be straight with you and say that this is a homework assignment. ive tried to figure it out on my own but am now out of time. i need to go through a .txt file and get rid of all punctuation. also, every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is ANY number i need to get rid of that also. thanks a bunch. hurry please! jen :) -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Thu, 2005-07-14 at 00:47 +1000, Steven D'Aprano wrote: > On Wed, 13 Jul 2005 10:21:19 -0400, rbt wrote: > > > Say I have a list that has 3 letters in it: > > > > ['a', 'b', 'c'] > > > > I want to print all the possible 4 digit combinations of those 3 > > letters: > > > > 4^3 = 64 > > > > > > abaa > > aaba > > aaab > > acaa > > aaca > > aaac > > ... > > > > What is the most efficient way to do this? > > Efficient for who? The user? The programmer? The computer? Efficient use > of speed or memory or development time? The CPU > > If you want the fastest runtime efficiency, a lookup table of > pre-calculated values. That is an O(1) operation, and you don't get any > faster than that. > > If you expect to extend the program to arbitrary lists, pre-calculation > isn't practical, so you need an algorithm to calculate permutations (order > matters) or combinations (order doesn't matter). My list is not arbitrary. I'm looking for all 'combinations' as I originally posted. Order does not matter to me... just all possibilities. -- http://mail.python.org/mailman/listinfo/python-list
DNS access
im looking for some advice regarding DNS lookup using python is it possible to give parameters like the IP of a DNS server and the DNS query to a python program and obtain the response from the DNS server ? please reply if u hav some idea or interest laksh -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
hey, i have this huge text file and i need to go through and remove all punctuation and every instance of the phrase "fruitloops=$" where $ is any number 0-100" um, and yeah this is homework but i've tried to no avail. thanks guys. cheerio :). jen -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
Use .replace function to replace punctuation (you didn't say exactly what that means but just to get you started): # # Extend this list as needed # punctuations=',.;:()' # # Open input and output files # ifp=open(inputfilename,'r') ofp=open(outputfilename,'w') # # Strip out the punctuation characters # for line in ifp: for punctuation in punctuations: line=line.replace(punctuation,'') ofp.write(line) # # I'll leave the other part for homework but # you will need to use the .find method of the string # ifp.close() ofp.close() Larry Bates Michael Jordan wrote: > i'll be straight with you and say that this is a homework assignment. > ive tried to figure it out on my own but am now out of time. > > i need to go through a .txt file and get rid of all punctuation. also, > every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is > ANY number i need to get rid of that also. thanks a bunch. hurry > please! > > jen :) > -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
> Say I have a list that has 3 letters in it:
>
> ['a', 'b', 'c']
>
> I want to print all the possible 4 digit combinations of those 3
> letters:
>
> 4^3 = 64
>
>
> abaa
> aaba
> aaab
> acaa
> aaca
> aaac
> ...
>
> What is the most efficient way to do this?
Expanding this to 4^4 (256) to test the random.sample function produces
interesting results. It never finds more than 24 combinations out of the
possible 256. This leads to the question... how 'random' is sample ;)
Try it for yourselves:
test = list('1234')
combinations = []
while 1:
combo = random.sample(test, 4)
possibility = ''.join(combo)
if possibility not in combinations:
print possibility
combinations.append(possibility)
continue
else:
continue
--
http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
On 13 Jul 2005 07:49:02 -0700, Michael Jordan <[EMAIL PROTECTED]> wrote:
> hey, i have this huge text file and i need to go through and remove all
> punctuation and every instance of the phrase "fruitloops=$" where $ is
> any number 0-100" um, and yeah this is homework but i've tried to no
> avail. thanks guys. cheerio :). jen
Jen,
This program iterates through one file and outputs all lines to
another file which have the word "homework" in them.
#-- Begin program 1
file_in = file('data.in')
file_out = file('data.out')
for line in file_in:
#line is a string containing one line of the file
if "homework" in line:
file_out.write("homework")
#--- End program 1
Here is a program which turns a string containing the phrase
"number=42" into a variable containing the integer 42:
#-- Begin program 2
#create a string variable called x
x = "number=42"
#split the string at the '=', resulting in ['number', '42']
n = x.split('=')[1]
#turn n from a string into a number, so we could test its value
n = int(n)
if 0 < n < 100:
print "n is between 0 and 100"
else:
print "n is not between 0 and 100"
#-- End program 2
And, finally, a program to remove punctuation from a string:
# Begin program 3
import string
#create a sentence with punctuation
punct = "This. is a, sentence with - punctuation"
#remove the punctuation; make sure the first argument
#to maketrans is the same length as the second, which
#should be all blanks
punct = punct.translate(string.maketrans('.,-', ' '))
#read the docs at
# http://docs.python.org/lib/node109.html
# for more details
#End program 3
Hope this helps; you should be able to put the pieces together to do
what you want to do. If you can't, feel free to ask more questions.
Also, just so you know, there is a list at [email protected] set up
just to answer questions like these.
Peace
Bill Mill
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: automatically assigning names to indexes
George> What 'magic' ? The (x,y,z) notation is used only for 3D George> vectors. (x,y) is also common for 2D and perhaps (t,x,y,z) for George> 4D, with t for time. Don't forget (w,x,y,z) for quaternions... Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, 13 Jul 2005 10:39:41 -0400, rbt wrote: >> > What is the most efficient way to do this? >> >> Efficient for who? The user? The programmer? The computer? Efficient use >> of speed or memory or development time? > > The CPU Ah, then that's easy. Sit down with pencil and paper, write out all 64 combinations yourself, and then type them into a Python list. Then you can access any one of those combinations with a single call. A lookup table is the fastest possible way for the CPU to give you the answer you want. [snip] > My list is not arbitrary. I'm looking for all 'combinations' as I > originally posted. Order does not matter to me... just all possibilities. That's good, since you only need combinations of "a", "b" and "c" the lookup table is quite small and manageable. I was worried that you might have wanted to apply your function to any set of items. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: DNS access
On 13 Jul 2005 07:44:41 -0700, laksh <[EMAIL PROTECTED]> wrote: >im looking for some advice regarding DNS lookup using python > >is it possible to give parameters like the IP of a DNS server and the >DNS query to a python program and obtain the response from the DNS >server ? > Not using the built-in hostname resolution functions. There are a number of third-party DNS libraries: http://devel.it.su.se/projects/python-dns/ http://pydns.sourceforge.net/ http://dustman.net/andy/python/adns-python/ http://twistedmatrix.com/projects/names/ Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, 2005-07-13 at 11:09 -0400, rbt wrote:
> On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
> > Say I have a list that has 3 letters in it:
> >
> > ['a', 'b', 'c']
> >
> > I want to print all the possible 4 digit combinations of those 3
> > letters:
> >
> > 4^3 = 64
> >
> >
> > abaa
> > aaba
> > aaab
> > acaa
> > aaca
> > aaac
> > ...
> >
> > What is the most efficient way to do this?
>
> Expanding this to 4^4 (256) to test the random.sample function produces
> interesting results. It never finds more than 24 combinations out of the
> possible 256. This leads to the question... how 'random' is sample ;)
>
> Try it for yourselves:
>
> test = list('1234')
>
> combinations = []
> while 1:
> combo = random.sample(test, 4)
> possibility = ''.join(combo)
> if possibility not in combinations:
> print possibility
> combinations.append(possibility)
> continue
> else:
> continue
>
Someone pointed out off-list that this is doing permutation, not
combination. Is there a way to make random.sample to do combinations?
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, 13 Jul 2005 11:09:25 -0400, rbt wrote:
> On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
>> Say I have a list that has 3 letters in it:
>>
>> ['a', 'b', 'c']
>>
>> I want to print all the possible 4 digit combinations of those 3
>> letters:
[snip]
> Expanding this to 4^4 (256) to test the random.sample function produces
> interesting results. It never finds more than 24 combinations out of the
> possible 256. This leads to the question... how 'random' is sample ;)
See below.
> Try it for yourselves:
>
> test = list('1234')
>
> combinations = []
> while 1:
> combo = random.sample(test, 4)
> possibility = ''.join(combo)
> if possibility not in combinations:
> print possibility
> combinations.append(possibility)
> continue
> else:
> continue
That's not very efficient code. Why not just write it like this?
combinations = []
while 1:
combo = random.sample(test, 4)
possibility = ''.join(combo)
if possibility not in combinations:
print possibility
combinations.append(possibility)
You don't need either of the two continue statements.
But in fact, random.sample is correct.
You have four items to choose from: "1", "2", "3", "4".
If you choose them with replacement, then there are 4*4*4*4 = 256
possibilities, but that includes duplicates:
[4, 4, 4, 4] is one such possibility.
As the documentation for random.sample clearly says:
"sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence."
Notice the UNIQUE part? You should have realised that just by looking at
the strings as they were printed. None of them have duplicated digits.
Sampling WITHOUT replacement gives 4*3*2*1 = 24 possibilities, exactly as
your code produces.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
rbt wrote:
> On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
>
>>Say I have a list that has 3 letters in it:
>>
>>['a', 'b', 'c']
>>
>>I want to print all the possible 4 digit combinations of those 3
>>letters:
>>
>>4^3 = 64
>>
>>
>>abaa
>>aaba
>>aaab
>>acaa
>>aaca
>>aaac
>>...
>>
>>What is the most efficient way to do this?
>
>
> Expanding this to 4^4 (256) to test the random.sample function produces
> interesting results. It never finds more than 24 combinations out of the
> possible 256. This leads to the question... how 'random' is sample ;)
>
> Try it for yourselves:
>
> test = list('1234')
>
> combinations = []
> while 1:
> combo = random.sample(test, 4)
> possibility = ''.join(combo)
> if possibility not in combinations:
> print possibility
> combinations.append(possibility)
> continue
> else:
> continue
>
There are only 24 possible lists that random.sample(test, 4) can return,
corresponding to the 24 possible orderings of 4 items. i.e.
random.sample() samples without replacement. You need to sample with
replacement.
Duncan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call? (update)
Francois De Serres wrote:
> Francois De Serres wrote:
>> Having a string: "dothat"
>> and a tuple: (x, y)
>> 1. What's the best way to build a function call like: dothat(x,y)?
>>
>> Assuming dothat is def'd in the same module,
>> 2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
>> the right way to have it executed?
You do know that you could do something like:
result = eval('dothat')(100, 200)
That is, eval of the function name gives you a function.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: DNS access
laksh wrote: > > is it possible to give parameters like the IP of a DNS server and the > DNS query to a python program and obtain the response from the DNS > server ? http://pydns.sf.net http://www.dnspython.org/ http://www.google.com/search?hl=en&q=python+dns&btnG=Google+Search Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Help with mass remove in text file
I'm trying to open a text file, remove all instances of the words
"f=x;" and "i=x;" where x can be any number 0-14. Also, I want to
remove all { " or ) or ( or ' } each time one of those characters
occurs respectively. This is what I've been able to piece together...
import os, string
x = ("f=;")
y = ("i=;)
inputFile = open('abcd.txt','r')
data = inputFile.read()
inputFile.close()
search = string.find(data, x)
if search >=1:
data = data.replace(x)
data = data.replace(y)
outputFile = open('abcd.txt','w')
outputFile.write(data)
outputFile.close()
This doesn't work, even to just remove "f=;". Any help would be great.
Thanks,
Reece
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
rbt wrote:
> On Wed, 2005-07-13 at 11:09 -0400, rbt wrote:
>
>>On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
>>
>>>Say I have a list that has 3 letters in it:
>>>
>>>['a', 'b', 'c']
>>>
>>>I want to print all the possible 4 digit combinations of those 3
>>>letters:
>>>
>>>4^3 = 64
>>>
>>>
>>>abaa
>>>aaba
>>>aaab
>>>acaa
>>>aaca
>>>aaac
>>>...
>>>
>>>What is the most efficient way to do this?
>>
>>Expanding this to 4^4 (256) to test the random.sample function produces
>>interesting results. It never finds more than 24 combinations out of the
>>possible 256. This leads to the question... how 'random' is sample ;)
>>
>>Try it for yourselves:
>>
>>test = list('1234')
>>
>>combinations = []
>>while 1:
>>combo = random.sample(test, 4)
>>possibility = ''.join(combo)
>>if possibility not in combinations:
>>print possibility
>>combinations.append(possibility)
>>continue
>>else:
>>continue
>>
>
>
> Someone pointed out off-list that this is doing permutation, not
> combination. Is there a way to make random.sample to do combinations?
>
Probably not in any sensible way. But what you list in your original
post are not distinct combinations. e.g. abaa and aaba are both 3 a's
and 1 b. Maybe you mean that order does matter (and you're actually
looking for all distinct permutations of all combinations)?
Duncan
--
http://mail.python.org/mailman/listinfo/python-list
tkFileDialog.askopenfilename filetypes problem
Hopefully someone can catch what im missing here. Ive googled this and I think
Ive got the filetypes arg written properly, but I get a traceback when calling
this function.
Heres the code followed by its traceback.
def do_ask_fn_1():
z = askopenfilename(title=TITLE, initialdir=Dst_Dir,
filetypes=(('AIFF Files','*.aiff'),
("AU Files", "*.au"),
("RAW Files", "*.raw"),
("SD Files", "*.sd"),
("SND Files", "*.snd"),
("WAV files", "*.wav")
)
)
print z
Exception in Tkinter callback
Traceback (most recent call last):
File "E:\PYTHON~1\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
File "P:\work\Python\PYZoid\PYZoid.pyw", line 213, in do_ask_fn_1
filetypes=[('AIFF Files','*.aiff'),
TypeError: askopenfilename() takes exactly 0 non-keyword arguments (1 given)
Can anyone point to what Ive done wrong? Thanks for any input.
Justin
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
rbt wrote: > Expanding this to 4^4 (256) to test the random.sample function produces > interesting results. It never finds more than 24 combinations out of the > possible 256. This leads to the question... how 'random' is sample ;) sample(population,k): Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. New in version 2.3. Working as designed, I'd say. 4! = 24. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web App like Google
Yes, there's a lot of issues, cross-site scripting, session hijacking, proper authentication, etc. Open Web App Security Project is useful www.owasp.org Also, before you start with NLP and full-on parsers, think about if you can apply a text indexer, stemming and stopping both your user's queries and the database content. Much easier conceptually, easier on db server too. and there's lots of good python packages/python bindings. http://www.xapian.org/ http://www.pypackage.org/packages/python-pyndex http://www.divmod.org/Home/Projects/Lupy/ -- http://mail.python.org/mailman/listinfo/python-list
py2exe => can you go the other way?
I have an executable version of a script that I wrote, but my script and backups got erased. Is it possible to get the python script back from an exe file created with py2exe? Joe Woodward Phoenix Analysis & Design Technologies 7755 s. Research Drive - Suite 110 Tempe, Arizona 85284 (480)813-4884 (480)813-4807 Fax -- http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
On Wed, Jul 13, 2005 at 05:07:33PM +0100, Duncan Smith wrote:
> rbt wrote:
> > On Wed, 2005-07-13 at 11:09 -0400, rbt wrote:
> >
> >>On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
> >>
> >>>Say I have a list that has 3 letters in it:
> >>>
> >>>['a', 'b', 'c']
> >>>
> >>>I want to print all the possible 4 digit combinations of those 3
> >>>letters:
> >>>
> >>>4^3 = 64
> >>>
> >>>
> >>>abaa
> >>>aaba
> >>>aaab
> >>>acaa
> >>>aaca
> >>>aaac
> >>>...
> >>>
> >>>What is the most efficient way to do this?
> >>
> >>Expanding this to 4^4 (256) to test the random.sample function produces
> >>interesting results. It never finds more than 24 combinations out of the
> >>possible 256. This leads to the question... how 'random' is sample ;)
> >>
> >>Try it for yourselves:
> >>
> >>test = list('1234')
> >>
> >>combinations = []
> >>while 1:
> >>combo = random.sample(test, 4)
> >>possibility = ''.join(combo)
> >>if possibility not in combinations:
> >>print possibility
> >>combinations.append(possibility)
> >>continue
> >>else:
> >>continue
> >>
> >
> >
> > Someone pointed out off-list that this is doing permutation, not
> > combination. Is there a way to make random.sample to do combinations?
> >
> Probably not in any sensible way. But what you list in your original
> post are not distinct combinations. e.g. abaa and aaba are both 3 a's
> and 1 b. Maybe you mean that order does matter (and you're actually
> looking for all distinct permutations of all combinations)?
>
This is called a cartesian product, and the easiest way is to do
import probstat # probstat.sourceforge.net
letters = list('abcd')
for (guys) in probstat.Cartesian([letters] * 4):
print ''.join(guys)
It's a C module I wrote to do this stuff a few years ago, still compiles
and runs just fine (at least on linux).
-jackdied
--
http://mail.python.org/mailman/listinfo/python-list
exec method WMI
Hi, I'm trying to use the AddPrinterDriver method of
Win32_PrinterDriver to create a new. print driver. I can't get my
head round how I need to do this. So far I have
import win32com.client
WBEM =
win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\"
+ "." + r"\root\cimv2")
WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege")
drv = WBEM.Get("Win32_PrinterDriver").SpawnInstance_()
drv.Properties_('Name').Value = "Marcs Printer 2550"
drv.Properties_('SupportedPlatform').Value = "Windows NT x86"
drv.Properties_('Version').Value = "3"
drv.Properties_('DriverPath').Value = 'C:\\test\\HPZPP034.DLL'
drv.Properties_('InfName').Value = 'C:\\test\\hpc2550d.inf'
method = drv.Methods_('AddPrinterDriver')
InParms = method.InParameters
InParms.Properties_.Item('DriverInfo').Value = drv
drv.ExecMethod_('AddPrinterDriver',InParms)
I'm using spawninstance to create a new object and then editing the
properties of it. I'm then setting the InParameters for the method to
be the new object. When executing the method I get SWbemObjectEx
object not found.
I think I am not setting the DriverInfo correctly, should it be an
object? The MSDN site doesn't say what DriverInfo should be.
Any help would be grand.
Thanks, MW.
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
Jack Diederich wrote:
> On Wed, Jul 13, 2005 at 05:07:33PM +0100, Duncan Smith wrote:
>
>>rbt wrote:
>>
>>>On Wed, 2005-07-13 at 11:09 -0400, rbt wrote:
>>>
>>>
On Wed, 2005-07-13 at 10:21 -0400, rbt wrote:
>Say I have a list that has 3 letters in it:
>
>['a', 'b', 'c']
>
>I want to print all the possible 4 digit combinations of those 3
>letters:
>
>4^3 = 64
>
>
>abaa
>aaba
>aaab
>acaa
>aaca
>aaac
>...
>
>What is the most efficient way to do this?
Expanding this to 4^4 (256) to test the random.sample function produces
interesting results. It never finds more than 24 combinations out of the
possible 256. This leads to the question... how 'random' is sample ;)
Try it for yourselves:
test = list('1234')
combinations = []
while 1:
combo = random.sample(test, 4)
possibility = ''.join(combo)
if possibility not in combinations:
print possibility
combinations.append(possibility)
continue
else:
continue
>>>
>>>
>>>Someone pointed out off-list that this is doing permutation, not
>>>combination. Is there a way to make random.sample to do combinations?
>>>
>>
>>Probably not in any sensible way. But what you list in your original
>>post are not distinct combinations. e.g. abaa and aaba are both 3 a's
>>and 1 b. Maybe you mean that order does matter (and you're actually
>>looking for all distinct permutations of all combinations)?
>>
>
> This is called a cartesian product, and the easiest way is to do
>
> import probstat # probstat.sourceforge.net
> letters = list('abcd')
> for (guys) in probstat.Cartesian([letters] * 4):
> print ''.join(guys)
>
> It's a C module I wrote to do this stuff a few years ago, still compiles
> and runs just fine (at least on linux).
>
> -jackdied
Yep. probstat also ran on Windows the last time I used it :-).
Duncan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with mass remove in text file
On Wed, 2005-07-13 at 09:00 -0700, [EMAIL PROTECTED] wrote:
> I'm trying to open a text file, remove all instances of the words
> "f=x;" and "i=x;" where x can be any number 0-14. Also, I want to
> remove all { " or ) or ( or ' } each time one of those characters
> occurs respectively. This is what I've been able to piece together...
Does this do what you're wanting?
---
finds = ("{", "}", "(", ")")
lines = file("foo.txt", "r").readlines()
for line in lines:
for find in finds:
if find in line:
line.replace(find, "")
print lines
---
>
> import os, string
> x = ("f=;")
> y = ("i=;)
> inputFile = open('abcd.txt','r')
>data = inputFile.read()
>inputFile.close()
>search = string.find(data, x)
>if search >=1:
> data = data.replace(x)
> data = data.replace(y)
> outputFile = open('abcd.txt','w')
> outputFile.write(data)
> outputFile.close()
>
>
> This doesn't work, even to just remove "f=;". Any help would be great.
>
> Thanks,
> Reece
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: tkFileDialog.askopenfilename filetypes problem
For me this:
z = tkFileDialog.askopenfilename(title='Title',
filetypes=[
('AIFF Files','*.aiff'),
("TXT Files", "*.txt"),
],
initialdir=InputDir)
print z
works fine.
Eugene
"Justin Straube" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hopefully someone can catch what im missing here. Ive googled this and I
think
> Ive got the filetypes arg written properly, but I get a traceback when
calling
> this function.
>
> Heres the code followed by its traceback.
>
> def do_ask_fn_1():
> z = askopenfilename(title=TITLE, initialdir=Dst_Dir,
> filetypes=(('AIFF Files','*.aiff'),
> ("AU Files", "*.au"),
> ("RAW Files", "*.raw"),
> ("SD Files", "*.sd"),
> ("SND Files", "*.snd"),
> ("WAV files", "*.wav")
> )
> )
> print z
>
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>File "E:\PYTHON~1\lib\lib-tk\Tkinter.py", line 1345, in __call__
> return self.func(*args)
>File "P:\work\Python\PYZoid\PYZoid.pyw", line 213, in do_ask_fn_1
> filetypes=[('AIFF Files','*.aiff'),
> TypeError: askopenfilename() takes exactly 0 non-keyword arguments (1
given)
>
> Can anyone point to what Ive done wrong? Thanks for any input.
>
> Justin
--
http://mail.python.org/mailman/listinfo/python-list
Re: Sort files by date
Jeremy Sanders wrote:
> fargo wrote:
>
>
>>I'm looking for some way to sort files by date.
>
>
> you could do something like:
>
> l = [(os.stat(i).st_mtime, i) for i in glob.glob('*')]
> l.sort()
> files = [i[1] for i in l]
>
> Jeremy
>
If you have 2.4 or later:
def mtime(filename):
return os.stat(filename).st_mtime
lst = sorted(glob.glob('*'), key=mtime)
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a function call? (update)
Scott David Daniels wrote:
>Francois De Serres wrote:
>
>
>>Francois De Serres wrote:
>>
>>
>>>Having a string: "dothat"
>>>and a tuple: (x, y)
>>>1. What's the best way to build a function call like: dothat(x,y)?
>>>
>>>Assuming dothat is def'd in the same module,
>>>2. is: eval("dothat(x,y)", None, (('x', 100), ('y', 200)))
>>>the right way to have it executed?
>>>
>>>
>
>You do know that you could do something like:
> result = eval('dothat')(100, 200)
>
>That is, eval of the function name gives you a function.
>
>--Scott David Daniels
>[EMAIL PROTECTED]
>
>
No I did not know. And, that, is smart!
Many thanks,
F.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Frankenstring
Thomas Lotze wrote: > Peter Otten wrote: > > class frankenstring(StringIO): >> ... def next(self): >> ... c = self.read(1) >> ... if not c: >> ... raise StopIteration >> ... return c > > Repeated read(1) on a file-like object is one of the ways of doing it with > existing tools I labelled "clumsy" in the original posting ;o) Not clumsy, just slow. I hope you'll let us know how much faster your final approach turns out to be. By the way, I'll consider anything that doesn't implement seek() and tell() cheating :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
SDXF 1.0 - Stani's DXF Library for Python
SDXF is a Python library to generate DXF files. DXF is an abbreviation
of Data Exchange File, a vector graphics file format. It is supported
by virtually all CAD products (such as AutoCAD, Blender, 3Dstudio,
Maya,Vectorworks...) and vector drawing programs (such as Illustrator,
Flash, ...).
SDXF can generate complex CAD drawings (dxf format) with all kind of
entities (such as 3DFace, Arc, Insert, Circle, Line, Mtext, Point,
Polyline, Rectangle (can be filled), Solid & Text). They can be
structured with Layers, Blocks, Linetypes, Text styles and Views.
Example
import sdxf
d=sdxf.Drawing()
d.append(sdxf.Text('Hello World!',point=(3,0,1)))
d.append(sdxf.Line(points=[(0,0,0),(1,1,1)]))
d.saveas('hello_world.dxf')
For more info&downloads: http://www.stani.be/python/sdxf
--
http://mail.python.org/mailman/listinfo/python-list
Re: Searching through a list of tuples
Scott David Daniels wrote: > iter(elem in lst if elem[3] == x).next() > > Does this look any better? At least it stops when the answer is found. Next time you'll recommend if (a>b) == True: # ... Watch out, you're on a slippery slope here :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'
Ric Da Force <[EMAIL PROTECTED]> wrote: > I have a string such as 'C1, C2, C3'. Without assuming that each bit of > text is of fixed size, what is the easiest way to change this list so that > it reads: > 'C1, C2 and C3' regardless of the length of the string. >>> import re >>> data = "the first bit, then the second, finally the third" >>> re.sub(r"(.*),", r"\1 and", data) 'the first bit, then the second and finally the third' >>> Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end -- http://mail.python.org/mailman/listinfo/python-list
PY2EXE => Is there a way to go backwards? EXE2PY
I have the executable of a script that I wrote, that has been erased. Is there any way to retrieve the uncompiled python script from the executable that was created with py2exe? Thank you, Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: exec method WMI
You probably need to remove the SpawnInstance_() call.
An abstract WMI class as returned by WBEM.Get should work
for the DriverInfo parm, since the concrete Win32_PrinterDriver
instance is what the AddPrinterDriver call is trying to create.
hth
Roger
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hi, I'm trying to use the AddPrinterDriver method of
> Win32_PrinterDriver to create a new. print driver. I can't get my
> head round how I need to do this. So far I have
>
> import win32com.client
> WBEM =
> win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\"
> + "." + r"\root\cimv2")
> WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege")
> drv = WBEM.Get("Win32_PrinterDriver").SpawnInstance_()
> drv.Properties_('Name').Value = "Marcs Printer 2550"
> drv.Properties_('SupportedPlatform').Value = "Windows NT x86"
> drv.Properties_('Version').Value = "3"
> drv.Properties_('DriverPath').Value = 'C:\\test\\HPZPP034.DLL'
> drv.Properties_('InfName').Value = 'C:\\test\\hpc2550d.inf'
> method = drv.Methods_('AddPrinterDriver')
> InParms = method.InParameters
> InParms.Properties_.Item('DriverInfo').Value = drv
> drv.ExecMethod_('AddPrinterDriver',InParms)
>
> I'm using spawninstance to create a new object and then editing the
> properties of it. I'm then setting the InParameters for the method to
> be the new object. When executing the method I get SWbemObjectEx
> object not found.
>
> I think I am not setting the DriverInfo correctly, should it be an
> object? The MSDN site doesn't say what DriverInfo should be.
>
> Any help would be grand.
>
> Thanks, MW.
>
== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
--
http://mail.python.org/mailman/listinfo/python-list
Re: all possible combinations
"rbt" <[EMAIL PROTECTED]> wrote:
> Say I have a list that has 3 letters in it:
>
> ['a', 'b', 'c']
>
> I want to print all the possible 4 digit combinations of those 3
> letters:
>
> 4^3 = 64
It's actually 3^4 = 81 (3 candidates/choice ** 4 choices)
>
> abaa
> aaba
> aaab
> acaa
> aaca
> aaac
> ...
>
> What is the most efficient way to do this?
I don't know if it's *the most* efficient -- and I don't think it really
matters -- but it's fast,
short and sweet:
def iterPermutations(num, seq):
if num:
for rest in iterPermutations(num-1, seq):
for item in seq:
yield rest + [item]
else:
yield []
for comb in iterPermutations(4, list("abc")):
print ''.join(comb)
George
--
http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
Hi, > for punctuation in punctuations: > line=line.replace(punctuation,'') I would use maketrans or even a regex instead. However, If you care about speed, it is well known that in some cases regex take more time than multiple replaces. Even the maketrans could take more time (I don't know; you may benchmark it -> homework) Regards, Josef -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Jul 13)
QOTW: "The posts do share an erroneous, implied assumption that the investment in learning each language is equal. Python has a strong competitive advantage over Java and C++ in terms of learnability. A person can get up to speed in a few days with Python." - Raymond Hettinger "You know, this is the most concise example of feature-creep in a specification that I've ever seen." - Christopher Subich "With Lisp or Forth, a master programmer has unlimited power and expressiveness. With Python, even a regular guy can reach for the stars." - Raymond Hettinger Lisp's macros are undoubtedly a powerful feature, but are they powerful enough to make List development faster than Python development? Do we want macros in Python? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ca05ba71092748a1 List comprehensions are almost identical to generator expressions wrapped in list() calls. Does that mean that list comps will go away in Python 3? Should they? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b050ef55b36dee56 A Bright, Shiny Service: Sparklines: http://www.xml.com/pub/a/2005/06/22/sparklines.html Which is faster, if, or try/except? Which is more Pythonic? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/8026ec36def2af1e Rbt wants to break out of nested loops. He's shown several ways of doing it, but for my money, Raymond's approach is the most elegant: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b127ff7fffcea00 Charlie Calvert wrote a couple of articles that advocate Python, and he's looking for some backup: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/721d749715aa5aaf Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog
Re: DNS access
reverse dns lookup is not really special compared to a regular dns lookup.
you just need to look up a special name:
http://www.dnsstuff.com/info/revdns.htm
to format the ip address properly use something like:
def rev_dns_string(ip_str):
nums = ip_str.split('.').reverse()
nums.extend(('in-addr', 'arpa'))
return '.'.join(nums)
-Chris
On Wed, Jul 13, 2005 at 07:44:41AM -0700, laksh wrote:
> im looking for some advice regarding DNS lookup using python
>
> is it possible to give parameters like the IP of a DNS server and the
> DNS query to a python program and obtain the response from the DNS
> server ?
>
> please reply if u hav some idea or interest
>
> laksh
>
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
