Re: modifying small chunks from long string
MackS wrote:
> This program is meant to process relatively long strings (10-20 MB) by
> selectively modifying small chunks one at a time.
...
> Can I get over this performance problem without reimplementing the
> whole thing using a barebones list object?
Is that a problem? Are you using string methods?
Some possibilities are:
array.array('c')
UserString.MutableString
cStringIO
depending on exactly what you are trying to do, but if
it is just straight forward replacement, (i.e. you
never actually change the length of the string) I'd
guess the list idiom would be simplest.
If you have enough memory, just keep two copies of the
string, the original and the modified:
size = 1024*1024*20 # 20 MB
original = "A" * size
copy = [None] * size
for i in range(size):
copy[i] = original[i].lower()
copy = ''.join(copy)
This takes 530 seconds (8 minutes) on my
not-especially-powerful system. Ouch. How does that
compare to your code?
If you can operate on moderately sized chunks of text
at a time rather than one character at a time, you'll
see some performance increase.
Also the above code not only has a 20MB string, plus a
20MB list, it also carries around a list of 20+ million
int objects. If I was paying more attention before I
hit the enter key, I would have used xrange instead of
range and saved a lot of memory.
It also has to assemble the new 20MB string before
garbage-collecting the character list. It is possible
that the above test code has well in excess of 100MB of
data at its peak.
With those problems in mind, I try this:
from __future__ import division
size = 1024*1024*20 # 20 MB
original = "A" * size
copy = []
blocksize = 1024
for i in xrange(size//blocksize):
copy.append( \
original[i*blocksize:(i+1)*blocksize].lower() )
copy = ''.join(copy)
This makes a BIG difference: from 8 minutes down to 0.5
seconds. That's a speed-up by a factor of about one
thousand.
I was so amazed at the speed increase I re-wrote the
code with a couple of simple tests, then ran it again.
Same result. Unless I've made some stupid mistake, I
think this is the way to go.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: modifying small chunks from long string
Replying to myself... the first sign of madness *wink* Steven D'Aprano wrote: > size = 1024*1024*20 # 20 MB > original = "A" * size > copy = [None] * size > for i in range(size): > copy[i] = original[i].lower() > copy = ''.join(copy) Do you notice the premature optimization? Rather than appending new data to an initially empty list, I thought I would "optimize" my code by pre-allocating all the memory I would need for the list. You can see how well it didn't work: > This takes 530 seconds (8 minutes) The more sensible algorithm, without the unneeded pre-allocation of the copy list, runs 1000 times faster. That's the difference between optimization by wild guessing and optimization by actually writing good code :-) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Op 2005-11-10, Mike Meyer schreef <[EMAIL PROTECTED]>: > [Context recovered from top posting.] > > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: >> Daniel Crespo wrote: >>> Well, I hope that newcomers to Python don't confuse himselves :) >> This mutable/immutable object and name/variable is confusing. > > Only if you have to overcome a conviction that variables behave in a > different way. If you've never seen them behave another way, or have > already gotten used to this model from another language (it dates back > to the 60s, if not the late 50s), then it's no problem. I'm sure the > problem exists in the opposite direction, except that few people > travel that route. > > Most OO languages do the name/variable thing, but some of the popular > ones aren't consistent about it, giving some types "special" status, > so that sometimes "a = b" causes b to be copied onto a, and sometimes > it causes a to become a pointer to b. I find a consistent approach is > preferable. But what about a consistent approach, that allows choice. Like having an assignment operator (let use @= for it) next to a (re)bind operator. We could then have something like the following. a = 5 b = a a @= 7 b ==> would result in 7. I think such option is usefull and I sometimes miss it in python. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Antoon Pardon <[EMAIL PROTECTED]> writes: > We could then have something like the following. > > a = 5 > b = a > a @= 7 > b ==> would result in 7. Ouch! :-((( Can't you live with a = [5] b = a a[0] = 7 so b[0] is now 7. -- http://mail.python.org/mailman/listinfo/python-list
Re: PySizer 0.1
Claudio Grondi wrote: > A small hint about the Web-site: > At least to me, the links to the documentation as e.g. > > http://pysizer.8325.org/doc/auto/home/nick/sizer-trunk/doc/auto/scanner.html > are broken (no big thing, because the distro has it anyway). > Oops. That should be fixed now. -- http://mail.python.org/mailman/listinfo/python-list
Clone an object
Hello, how can I clone a class instance? I have trouble finding that in the documentation... thanks and best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: Clone an object
http://docs.python.org/lib/module-copy.html I would assume you want deep/shallow copy. Yves Glodt wrote: > Hello, > > how can I clone a class instance? > I have trouble finding that in the documentation... > > thanks and best regards, > Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: gmpy/decimal interoperation
Alex Martelli <[EMAIL PROTECTED]> wrote:
> As things stand now (gmpy 1.01), an instance d of decimal.Decimal cannot
> transparently become an instance of any of gmpy.{mpz, mpq, mpf}, nor
> vice versa (the conversions are all possible, but a bit laborious, e.g.
> by explicitly going through string-forms).
>
> I'm thinking about possible ways to fix this, in whole or in part, but,
> before I spend more time on this, I was wondering if there's anybody
> else who'd be interested
I can't ever imaging mixing the two. I use GMPY when I want fast
inifinite precision artithmetic. I'd use decimal if I wanted to do
decimal arithmetic on currency or something like that (or perhaps if I
hadn't discovered GMPY in which case I wouldn't be mixing with GMPY!)
> if so, maybe we can discuss which conversions should happen
> implicitly
None I'd say! Perhaps make a less laborious manual conversion
function, but I don't think implicit conversion is that useful since
decimal and gmpy are solving quite different problems.
Implicit conversions also opens the can of worms - what is the
preferred promotion type? decimal + mpf == decimal? mpf? mpq?
IMHO of course!
--
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list
HTTP Keep-Alive with urllib2
Someone once asked about this an got no answer: http://groups.google.dk/group/comp.lang.python/browse_frm/thread/c3cc0b8d7e9cbc2/ff11efce3b1776cf?lnk=st&q=python+http+%22keep+alive%22&rnum=84&hl=da#ff11efce3b1776cf Maybe I am luckier :) Does anyone know how to do Keep-Alive with urllib2, that is, how to get a persistent HTTP connection, instead of a new connection being opened for every request? /David -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid "f.close" (no parens) bug?
Peter <[EMAIL PROTECTED]> wrote: > First off, please explain what you are talking about better next time. > > Second, What on earth are you talking about? > > "f" is a file object, correct? > > Are you trying to close a file by typing f.close or is the file closing > when you type f.close? I would guess that this person is coming to python from perl. In perl, you are allowed to miss the parens off a method call if it takes no arguments, so f.close is equivalent to f.close(). I used to make this mistake all the time. However it is one pychecker catches, so install pychecker and run it on all your programs is the answer! -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: generate HTML
[ss2003] > I am stuck at above after doing a lot of f.write for every line of HTML > . Any betterways to do this in python? See the "Templating Engines" section of http://wiki.python.org/moin/WebProgramming - I hope you have a few hours to spare! 8-) -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
generate HTML
hi
i have fucntion that generates a HTML page
def genpage(arg1,arg2):
print ''' BLAH BLAH.%s %s
''' % (arg1, arg2)
print ''' blah blah... %s %s
''' % (arg1,arg2)'
The func is something like that, alot of open''' and closing ''' triple
quotes. anyway, i wish to print all these into a HTML output file so
that when i click on it, it shows me the html page. How can i do that?
i tried
f = open("output.html","w")
f.write ( 'print '''http://mail.python.org/mailman/listinfo/python-list
Re: HOW do you stop a print???
"john boy" <[EMAIL PROTECTED]> wrote: > ok...I am running the following program: > > def printMultiples (n): > i = 1 > while i <= 6: > print n*i, ' \t ', > i = i + 1 > i = 1 > while i <= 6: > printMultiples(i) > i = i + 1 > > this is supposed to return a simple multiplication table, but for > some reason it does not want to stop printing after 6 columns... > instead it prints from left to right for a total of 10 columns... > I need some sort of a "stop print" after the first 6 columns if "stop print" means "start a new line", a plain "print" will do what you want: def printMultiples (n): i = 1 while i <= 6: print n*i, ' \t ', i = i + 1 print (you may also want to read up on the for-in loop statement; the tutorial has more information on this) -- http://mail.python.org/mailman/listinfo/python-list
Re: circle and point
is there any python code doing this: there are two line segments (2x+y-1=0 with the coordinates of two ending points are (1,-1) and (-1,3); x+y+6=0 with the coordinates of two ending points are (-3,-3) and (-4,-2);). They extend and when they meet each other, stop extending. how can i use python to implement this in Tkinter?-- Thanks!Ben Bush -- http://mail.python.org/mailman/listinfo/python-list
Re: D foreach
[EMAIL PROTECTED] wrote: > The Digital Mars D compiler is a kind of "improved c++", it contains a > "foreach" statement: > http://www.digitalmars.com/d/statement.html#foreach > > Usage example: > foreach(int i, inout int p; v1) p = i; > > Is equal to Python: > for i in xrange(len(v)): v[i] = i [...] > So the variable p contains (scans) the elements of the given iterable > object, but if you assign p with a value, that value becomes copied > inside the mutable iterable too. Those are little examples, but I think > it can be quite useful in more complex code. 1. It would be difficult to implement. Python would require the concept of 'reference to variable', which has lots of repercussions for reference counting, garbage collection etc. Requiring iterators to return references would also break all existing iterators. It would also be required that the assignment operator is overloadable and this is another box of Pandora no one likes to open (well, no one except C++ programmemrs). Or the compiler would have to detect 'assignment to iterator variable' and issue an 'update_current' to the iterator. 2. It violates the Zen of Python 'Explicit is better than implicit' (although the definition of 'explict' varies wildly in the Python community) 3. For specific collections like lists and dictionaries, you could write a wrapper so that it is possible to write for ref in wrapper (mycollection): print ref.value ref.value = newvalue Daniel -- http://mail.python.org/mailman/listinfo/python-list
extend
is there any python code doing this: there are two line segments (2x+y-1=0 with the coordinates of two ending points are (1,-1) and (-1,3); x+y+6=0 with the coordinates of two ending points are (-3,-3) and (-4,-2);). They extend and when they meet each other, stop extending. how can i use python to implement this in Tkinter?-- Thanks!Ben Bush -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Op 2005-11-14, Paul Rubin schreef : > Antoon Pardon <[EMAIL PROTECTED]> writes: >> We could then have something like the following. >> >> a = 5 >> b = a >> a @= 7 >> b ==> would result in 7. > > Ouch! :-((( > > Can't you live with > > a = [5] > b = a > a[0] = 7 > > so b[0] is now 7. And what do I have to do, in case of the following: a = [3, 5] b = a[0] b @= 7 a ==> would result in [7, 5] This may seem contrived, but in combination with parameters it could be usefull. Something like: a = [3, 5] def treat(b): lots of code b @= new_value f(a[0]) a ==> would result in [7, 5] -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of tuples from query question
David Pratt wrote:
> My code so far. I guess my problem is how to generate a tuple
> dynamically when it is immutable?
you can use tuple() to convert lists to tuples.
>>> x = []
>>> x.append(1)
>>> x.append(2)
>>> x.append(3)
>>> tuple(x)
(1, 2, 3)
but doesn't fetchall already returns tuples, btw? isn't something
like
d = {}
for index, record in cursor.fetchall():
d[index+1] = record
an easier way to get the dictionary you want?
fwiw, if all you need is something that returns the right thing if you
do d[index], you could even do:
d = [None] + list(cursor.fetchall())
(or you could wrap the fetchall() result in a trivial wrapper class that
adjusts the index on the fly)
--
http://mail.python.org/mailman/listinfo/python-list
multiple inharitance super() question
Hi, Before 2.2 I could initialize multiple super classes like this: class B(A,AA): def __init__(self, args): A.__init__(self,args) AA.__init__(self,args) Tutorials say that since python 2.2 superclasses should be initialized with the super() construct. class A(object): def __init__(self, args): ... class B(A): def __init__(self, args): super(B, self).__init__(args) BUT what happens if B extends from A and AA like: class A(object): def __init__(self, args): ... class AA(object): def __init__(self, args): ... class B(A,AA): def __init__(self, args): super(B, self).__init__(args) How can I tell that B.__init__() should initialize A and AA? Or is the new super() so clever to call A.__init__() and AA.__init__() internally? thanks, Alex Greif http://www.fotobuch-xxl.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: SciPy python 2.4 wintel binaries
Hi Peter, I'm aware of the Enthought distribution, which really is my preferred 2.3 Python distribution. Problem is that many programs I'm working on would require both 2.4 & SciPy What kind of puzzles me is that SciPy.core is available for wintel 2.4, is that an indication a full SciPy distribution is coming along? Cheers, -jelle -- http://mail.python.org/mailman/listinfo/python-list
problem with from win32com.client import Dispatch
Hi all
Am trying to read an html page using win32com in the following way.
from win32com.client import Dispatch
ie = Dispatch("InternetExplorer.Application")
ie.Navigate("https://secure.authorize.net/";)
doc =ie.Document
print doc.body.innerHTML
with this code am easily able to read the mentioned page from the
pythonwin interactive window, but the same code if I write it in some
*.py file, am not able to read the page.
The following error it throws when I compile the file.
Traceback (most recent call last):
File
"C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\Python23\Lib\site-packages\Script1.py", line 14, in ?
ie.Quit()
File "C:\Python23\Lib\site-packages\win32com\client\__init__.py",
line 456, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Python23\Lib\site-packages\win32com\client\__init__.py",
line 446, in _ApplyTypes_
return self._get_good_object_(
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147467259), None)
if any body has the answer for this please help me in this.
Thanks and regards
Yogi
--
http://mail.python.org/mailman/listinfo/python-list
compare list
I have four lists: lisA=[1,2,3,4,5,6,9] lisB=[1,6,5] lisC=[5,6,3] lisD=[11,14,12,15]how can I write a function to compare lisB, lisC and lisD with lisA, if they share two continuous elements (the order does not matter), then return 1, otherwise return 0. For example, lisA, lisB and lisC have 5,6 or 6,5 so these comparison will return 1 but the comparison between lisD and lisA return 0. -- Thanks!Ben Bush -- http://mail.python.org/mailman/listinfo/python-list
problem with from win32com.client import Dispatch
Hi all
Am trying to read an html page using win32com in the
following way.
from win32com.client import Dispatch
ie = Dispatch("InternetExplorer.Application")
ie.Navigate("https://secure.authorize.net/")
doc =ie.Document
print doc.body.innerHTML
with this code am easily
able to read the mentioned page from the pythonwin interactive window, but the same code if I write
it in some *.py file, am not able to read
the page.
The following error it throws when I compile the file.
Traceback (most recent call last):
File
"C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\Python23\Lib\site-packages\Script1.py",
line 14, in ?
ie.Quit()
File
"C:\Python23\Lib\site-packages\win32com\client\__init__.py", line
456, in __getattr__
return self._ApplyTypes_(*args)
File
"C:\Python23\Lib\site-packages\win32com\client\__init__.py", line
446, in _ApplyTypes_
return self._get_good_object_(
com_error: (-2147352567, 'Exception occurred.', (0, None,
None, None, 0, -2147467259), None)
if any body has the answer for this please help me in this.
Thanks and regards
Yogi
-
Disclaimer
-
"This message(including attachment if any)is confidential and may be
privileged.Before opening attachments please check them
for viruses and defects.MindTree Consulting Private Limited (MindTree)will not
be responsible for any viruses or defects or
any forwarded attachments emanating either from within MindTree or outside.If
you have received this message by mistake please notify the sender by return
e-mail and delete this message from your system. Any unauthorized use or
dissemination of this message in whole or in part is strictly prohibited.
Please note that e-mails are susceptible to change and MindTree shall not be
liable for any improper, untimely or incomplete transmission."
---
http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Mike Meyer wrote: > > I have considered distributing my program as open source but with > > encrypted data. Unfortunately anyone can just read the source to > > determine the decryption method and password. Maybe I could put that > > into an extension module, but that just moves the weak link along the > > chain. > > This isn't a Python problem, it's a problem with what you're doing. Try > Alex's solution, and put the data on a network server that goes > through whatever authentication you want it to. To be fair, I don't think I have accused Python of having a problem, just mentioned that this is an area where Python is less appropriate than other languages which have a significant degree of obfuscation as a side-effect of their use. I already explained elsewhere that putting the data on the network is not always appropriate. I know people love web services and the like these days, but they are not the answer to everything. Even in situations where it is practical to keep all the data server-side, it still just moves the problem rather than solving it, in that instead of people copying the data they now copy the authentication for the data. Anecdotal evidence from experiences with online registration for Half-Life 2 and Windows XP would suggest that this method ends up annoying more legitimate customers than the usual copy-protection does. > It is? Is the Python disassembler so much advanced over the state of > the art of binary disassemblers, then? Or maybe it's the Python > decompilers that are so advanced? Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be pretty advanced. I don't know if you can download it any more to test this claim though. > As far as I can tell, the only real > difference between Python bytecodes and x86 (for instance) binaries is > that Python bytecodes keep the variable names around so it can do > run-timme lookups. That's not that big a difference. It makes a lot of difference when you're hunting around for something or trying to understand a bit of code. Python bytecode (or at least, the output from dis) is also a lot more straightforward than x86 or 68K assembly to decipher. > > No, certainly not. But if you can mitigate your losses easily enough - > > without infringing upon anyone else's rights, I must add - then why not > > do so. > > Elsewhere in the thread, you said: > > > I'd just like to make it non-trivial to make or use additional copies. > > How do you do that without infringing my fair use rights? Yes, I suppose my terminology there was wrong. The term I should probably have used was 'distribute usable additional copies'. Generally speaking I believe in the "like a book" interpretation of rights... you should have the right to give it away, sell it to someone, lend it, excerpt parts for review or criticism, but not to distribute additional copies that essentially duplicate the original. On the other hand though, what you term a 'fair use right' is not necessarily viewed that way under law. The relevant part of the law (at least in the US) says "it is not an infringement for the owner of a copy of a computer program to make or authorize the making of another copy or adaptation of that computer program provided [...] that such new copy or adaptation is for archival purposes only", which is quite distinct, legally speaking, from saying "you have the right to make a copy or adaptation for archival purposes". However, this is drifting more into the legal area which I am less interested in. Really I'd just like to be able to use Python for my work and am interested in finding the best way of doing so. -- Ben Sizer. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inharitance super() question
Alex Greif wrote: > BUT what happens if B extends from A and AA like: > > class A(object): > def __init__(self, args): > ... > > class AA(object): > def __init__(self, args): > ... > > class B(A,AA): > def __init__(self, args): > super(B, self).__init__(args) > > > How can I tell that B.__init__() should initialize A and AA? > Or is the new super() so clever to call A.__init__() and AA.__init__() > internally? Yes but only if you put a super() call into A/AA.__init__(). class A(object): def __init__(self, args): print "init A" super(A, self).__init__(args) class AA(object): def __init__(self, args): print "init AA" super(AA, self).__init__(args) class B(A, AA): def __init__(self, args): print "init B" super(B, self).__init__(args) if __name__ == "__main__": B(42) The most significant constraint of that layout is that all __init__() methods need compatible signatures. Of course explicit invocation of baseclass initializers will continue to work... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: gmpy/decimal interoperation
Alex Martelli wrote:
> As things stand now (gmpy 1.01), an instance d of decimal.Decimal cannot
> transparently become an instance of any of gmpy.{mpz, mpq, mpf}, nor
> vice versa (the conversions are all possible, but a bit laborious, e.g.
> by explicitly going through string-forms).
>
> I'm thinking about possible ways to fix this, in whole or in part, but,
> before I spend more time on this, I was wondering if there's anybody
> else who'd be interested -- if so, maybe we can discuss which
> conversions should happen implicitly (e.g., if you try to sum a Decimal
> and an mpz, maybe the latter should implicitly become a Decimal, just
> like an int would, so that the result is a Decimal) and which ones
> should only happen on explicit request (e.g., gmpy.mpf(d) should produce
> an mpf instance, just as calling gmpy.mpf on an int instance would).
>
>
> Alex
This is a bit off topic but I would like to know how you would go about
doing an implicit operation with an mpz and Decimal becoming a Decimal.
I would like to use something like this to make the float and complex
types more interoperable with mpq and cmpq in my clnum module
(http://calcrpnpy.sourceforge.net/clnumManual.html). In those cases, I
would like the mpq to degrade to float and the cmpq to degrade to
complex (right now they just raise exceptions). Seems like you need to
either modify the target type to recognize the new one or the code has
to get very complex to handle all the combinations.
Ray
--
http://mail.python.org/mailman/listinfo/python-list
Re: want some python ide
Hi, look for SciTE http://www.scintilla.org/SciTE.html it is small, fast and lightweight Alex Greif http://www.fotobuch-xxl.de/ D H wrote: > [EMAIL PROTECTED] wrote: > > i want some python ide use pygtk > > eric3 is good for me ,but i like gtk,so i want some pygtk ide look like > > eric3 > > wing is a good python ide,but i can not download it > > some other python ide(must use pygtk) > > thx > > > > You can just use a text editor like jedit with gazpacho or glade > http://gazpacho.sicem.biz/ > They are not as easy to use at QT Designer though for building interfaces. -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python web-dav management system
> Zope has WebDAV support and is written in Python. You could > use Zope or perhaps use "parts" of it (since it is open source). I wouldn't use Zope as file storage. The ZODB is inefficient for storing big files. -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: extend
On 11/14/05, Ben Bush <[EMAIL PROTECTED]> wrote: > is there any python code doing this: > there are two line segments (2x+y-1=0 with the coordinates of two ending > points are (1,-1) and (-1,3); > x+y+6=0 with the coordinates of two ending points are (-3,-3) and > (-4,-2);). They extend and when they meet each other, stop extending. > how can i use python to implement this in Tkinter? > > -- > Thanks! > Ben Bush > -- the comp.graphics.algorithms FAQ may be of use to you: http://cgafaq.info/wiki/Main_Page > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: SciPy python 2.4 wintel binaries
Is http://heanet.dl.sourceforge.net/sourceforge/scipy/scipy-0.4.3.win32-py2.4.exe not what are you looking for? Claudio "jelle" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hi Peter, > > I'm aware of the Enthought distribution, which really is my preferred > 2.3 Python distribution. > Problem is that many programs I'm working on would require both 2.4 & > SciPy > > What kind of puzzles me is that SciPy.core is available for wintel 2.4, > is that an indication a full SciPy distribution is coming along? > > Cheers, > > -jelle > -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of tuples from query question
Hi Fredrik. Many thanks for your reply and for the tuple tip. The
cursor.fetchall returns a list of lists in this instance with each list
in the main list containing the field values. With the tip, I
simplified my code to:
vlist_dict = {}
record_count = 0
for record in cursor.fetchall():
record_count += 1
vlist_dict[record_count] = tuple(record)
print vlist_dict
That's much better!
Regards
David
On Monday, November 14, 2005, at 07:58 AM, Fredrik Lundh wrote:
>
> but doesn't fetchall already returns tuples, btw? isn't something
> like
>
> d = {}
> for index, record in cursor.fetchall():
> d[index+1] = record
>
> an easier way to get the dictionary you want?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of tuples from query question
David Pratt wrote:
> With the tip, I
> simplified my code to:
>
> vlist_dict = {}
> record_count = 0
> for record in cursor.fetchall():
> record_count += 1
> vlist_dict[record_count] = tuple(record)
> print vlist_dict
I missed your original post, so forgive me if I'm missing the point
here. But if you're indexing the dictionary with integers, I expect you
could just use a list instead, which I think could make your code look
like this:
vlist = [tuple(record) for record in cursor.fetchall() ]
print vlist
In Python there is rarely any need to manually increment index values
within a loop. If you do need the record count here, len(vlist) would
be equivalent.
--
Ben Sizer
--
http://mail.python.org/mailman/listinfo/python-list
Re: Inserting Records into SQL Server - is there a faster interface than ADO
The utility is designed to run in the background and maintain/update a parallel copy of a production system database. We are using the stored procedure to do a If Exist, update, else Insert processing for each record. The originating database is a series of keyed ISAM files. So we need to read each record, perform some simple data conversions and then update the SQL database. We are using Python to read the originating database and perform the record conversion and then posting the results back to SQL Server. We designed our utility to run a night so that the SQL server is up to date the next day and ready for reporting. Thanks for your tips on BCP. I will investigate further as it looks like it might be useful for the initial loading of the data and perhaps some changes to the our utility program to minimize the amount of data that needs to be read/processed. Geoff. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Book
The ones that were best for me: -Python 2.1 Bible (Dave Brueck and Stephen Tanner) (dated but good to learn) -Python Cookbook (Alex Martelli, Anna Martelli Ravenscroft & David Ascher) If you write for Windows: Python Programming on Win32 (Mark Hammond & Andy Robinson) Larry Bates David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? > > /David -- http://mail.python.org/mailman/listinfo/python-list
Re: gmpy/decimal interoperation
Raymond L. Buvel <[EMAIL PROTECTED]> wrote: ... > This is a bit off topic but I would like to know how you would go about > doing an implicit operation with an mpz and Decimal becoming a Decimal. I would tweak Decimal.__new__ to accept an mpz and perform an int() on it before proceeding as it does now, for example. > I would like to use something like this to make the float and complex > types more interoperable with mpq and cmpq in my clnum module > (http://calcrpnpy.sourceforge.net/clnumManual.html). In those cases, I > would like the mpq to degrade to float and the cmpq to degrade to > complex (right now they just raise exceptions). Seems like you need to > either modify the target type to recognize the new one or the code has > to get very complex to handle all the combinations. Modifying the target type is indeed what I had in mind (for Decimal). As long as the target-type is Python-coded, you can substitute its __new__ with a wrapped version. Unfortunately, float and complex aren't; but fortunately, Python does have for these cases appropriate special methods/slot that your SOURCE type can implement. In gmpy, I have float 'upgraded' to mpq (with a Stern-Brocot heuristic), but it wouldn't be any harder to have the mpq 'degrade' to float instead. Alex -- http://mail.python.org/mailman/listinfo/python-list
Pregunta sobre python
Hola, me llamo Andres de la cuadra, soy un usuario de python en chile y me gustaría saber como puedo cerrer un programa a través de python. Yo se que con la librería os puedo ejecutar programas, pero no e encontrado una librería para poder cerrarlos Gracias -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Antoon Pardon <[EMAIL PROTECTED]> writes: > Op 2005-11-10, Mike Meyer schreef <[EMAIL PROTECTED]>: >> [Context recovered from top posting.] >> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: >>> Daniel Crespo wrote: Well, I hope that newcomers to Python don't confuse himselves :) >>> This mutable/immutable object and name/variable is confusing. >> Only if you have to overcome a conviction that variables behave in a >> different way. If you've never seen them behave another way, or have >> already gotten used to this model from another language (it dates back >> to the 60s, if not the late 50s), then it's no problem. I'm sure the >> problem exists in the opposite direction, except that few people >> travel that route. >> Most OO languages do the name/variable thing, but some of the popular >> ones aren't consistent about it, giving some types "special" status, >> so that sometimes "a = b" causes b to be copied onto a, and sometimes >> it causes a to become a pointer to b. I find a consistent approach is >> preferable. > But what about a consistent approach, that allows choice. It's been done in other languages. But it requires more care than one would think. > Like having an assignment operator (let use @= for it) next to a > (re)bind operator. > > We could then have something like the following. > > a = 5 > b = a > a @= 7 > b ==> would result in 7. You've just overwritten the object referred to by the token "5" in the source code with the value 7, so you get: print 5 7 Not exactly a desirable outcome, but some language implementations have allowed this kind of thing in the past. You either have to make all objects mutable, or disallow assignment to immutable objects, which sort of defeats the purpose. Another approach is to have a special object type if you want to allow assignment to the object it refers to. That's what Python does now, it just doesn't have a syntax just to support that. If it did, your example might look like: a := 5 b = @a a := 7 @b ==> would result in 7 http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inserting Records into SQL Server - is there a faster interface than ADO
> We are using the stored procedure to do a If Exist, update, else Insert > processing for > each record. Consider loading the data in batches into a temporary table and then use a single insert statement to insert new records and a single update statement to update existing ones. This way, you are not forcing the database to do it one by one and give it a chance to aggressively optimize your queries and update the indexes in bulk. You'd be surprized at the difference this can make! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pregunta sobre python
Andres de la Cuadra wrote: > Hola, me llamo Andres de la cuadra, soy un usuario de python en chile y me > gustaría saber como puedo cerrer un programa a través de python. Yo se que > con la librería os puedo ejecutar programas, pero no e encontrado una > librería para poder cerrarlos Hola Andres, puedes cerrer un programa con os.kill, pero depende de tu plataforma, por ejemplo en linux (no se para windows): os.kill(pid_del_proceso, 9) p.s. Vas a tener mas excito si escribes en ingles, esta es une lista en ingles ;-) > Gracias > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
On 14 Nov 2005 11:20:53 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: >Op 2005-11-14, Paul Rubin schreef : >> Antoon Pardon <[EMAIL PROTECTED]> writes: >>> We could then have something like the following. >>> >>> a = 5 >>> b = a >>> a @= 7 >>> b ==> would result in 7. >> >> Ouch! :-((( >> >> Can't you live with >> >> a = [5] >> b = a >> a[0] = 7 >> >> so b[0] is now 7. > >And what do I have to do, in case of the following: > >a = [3, 5] >b = a[0] >b @= 7 >a ==> would result in [7, 5] > >This may seem contrived, but in combination with >parameters it could be usefull. > >Something like: > >a = [3, 5] > >def treat(b): > lots of code > b @= new_value > >f(a[0]) >a ==> would result in [7, 5] > >-- You may be interested in reviewing http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3 before continuing this topic ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with from win32com.client import Dispatch
Hello,
If you want some goood examples of reading Web pages and automating
this process
I have a class that wraps all these functions.
http://pamie.sourceforge.net
But for your problem:
You are trying to read the page before it is completely loaded
either add a wait function or a simple sleep ( see below)
from win32com.client import Dispatch
import time
ie = Dispatch("InternetExplorer.Application")
ie.Navigate("https://secure.authorize.net/";)
# ie.Visible = True
time.sleep(1)
doc = ie.Document
print doc.body.innerHTML
or with a wait function
from win32com.client import Dispatch
import time
def wait(ie):
while ie.Busy:
time.sleep(0.5)
while ie.Document.readyState != "complete":
time.sleep(0.5)
ie = Dispatch("InternetExplorer.Application")
ie.Navigate("https://secure.authorize.net/";)
# ie.Visible = True
wait(ie)
doc = ie.Document
print doc.body.innerHTML
Enjoy
Robert Marchetti
--
http://mail.python.org/mailman/listinfo/python-list
DB API specification of .rowcount and/or execute
Hi,
Should execute() be allowed to execute multiple operations?
e.g.
from dbi import *
conn = connect(database="test")
curs = conn.cursor()
curs.execute("""
INSERT INTO test_table VALUES (1, 'one');
INSERT INTO test_table VALUES(2, 'two');
""")
If so, then given this execution should rowcount contain the value 2?
What if both a select statement and an insert/update statement exist in
a single call to execute?
Perhaps only the rows affected/returned by the last operation in a
given execute() should be given by rowcount?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pregunta sobre python
Yves Glodt wrote:
>
>
> puedes cerrer un programa con os.kill, pero depende de tu plataforma,
> por ejemplo en linux (no se para windows):
>
> os.kill(pid_del_proceso, 9)
>
>>
Y tambien, algunas platformas necesita el mandato "sudo", como esto:
os.system('echo su_contraseña | sudo -S kill pid')
--
Cheers,
Kevin Walzer, PhD
WordTech Software - "Tame the Terminal"
http://www.wordtech-software.com
sw at wordtech-software.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Book
David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? > > /David A couple of years ago I was in the same boat you're in now. I learned from _Python in a Nutshell_ by Alex Martelli and still use it as my main reference. (It only covers up to version 2.2 so a new edition would be most welcome.) I also use the on-line Python docs and I second Larry Bates' comments re. the cookbook and the Windows book, both of which I also use occasionally. -- Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: CherryPy not playing nicely with win32com?
> Just an idea: because in CherryPy it is running in multithreading mode? > If you are using threads together with COM stuff, you will have to > add pythoncom.CoInitialize() and pythoncom.CoUninitialize() calls > in your code -- for each thread. That worked perfectly. Thanks a million! I used to hate COM just because of our huge VB project. Now I can hate it for this too! -- http://mail.python.org/mailman/listinfo/python-list
Re: DB API specification of .rowcount and/or execute
[EMAIL PROTECTED] wrote: > Hi, > > Should execute() be allowed to execute multiple operations? [...] You best ask such questions on the DB-SIG. I say "no" and I think most people there will agree. Most DB-API modules will accept multiple statements, but that's an implementation artifact, and not intended by the DB-API. FWIW I specifically implemented a check in pysqlite that will raise a Warning if you use multiple statements in execute(many) and provided a nonstandard executescript() method for those who really want to execute multiple statements. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: generate HTML
[EMAIL PROTECTED] wrote:
> hi
> i have fucntion that generates a HTML page
>
> def genpage(arg1,arg2):
>print ''' BLAH BLAH.%s %s
> ''' % (arg1, arg2)
>
>print ''' blah blah... %s %s
>
> ''' % (arg1,arg2)'
>
> The func is something like that, alot of open''' and closing ''' triple
> quotes. anyway, i wish to print all these into a HTML output file so
> that when i click on it, it shows me the html page. How can i do that?
>
> i tried
> f = open("output.html","w")
> f.write ( 'print '''
> I am stuck at above after doing a lot of f.write for every line of HTML
> . Any betterways to do this in python?
>
> something like here documents in a shell script where it can also be
> directed to a file.
> thanks
>
Why not just redirect the output of your Python script from the shell?
E.g.:
python generate_html.py > output.html
--
http://mail.python.org/mailman/listinfo/python-list
RE: py2exe and pyGTK (was "Error")
danger wrote: > hi everybody, i have a problem with py2exe that gives me this error: > > ImportError: could not import pango > ImportError: could not import pango > Traceback (most recent call last): > File "acqua.py", line 40, in ? > File "gtk\__init__.pyc", line 113, in ? > AttributeError: 'module' object has no attribute 'Font' > > does anybody knows how to solve it? Does http://www.anti-particle.com/py2exe.shtml help? Jimmy -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying small chunks from long string
On 13 Nov 2005 22:57:50 -0800, "MackS" <[EMAIL PROTECTED]> wrote:
>Hello everyone
>
>I am faced with the following problem. For the first time I've asked
>myself "might this actually be easier to code in C rather than in
>python?", and I am not looking at device drivers. : )
>
>This program is meant to process relatively long strings (10-20 MB) by
>selectively modifying small chunks one at a time. Eg, it locates
>approx. 1000-2000 characters and modifies them. Currently I was doing
>this using a string object but it is getting very slow: although I only
>modify a tiny bit of the string at a time, a new entire string gets
>created whenever I "merge" it with the rest. Eg,
>
>shortstr = longstr[beg:end]
>
># edit shortstr...
>
>longstr = longstr[:beg] + shortstr + longstr[end:] # new huge string is
>created!!
>
The usual way is to accumulate the edited short pieces of the new version of
longstr
in a list and then join them once, if you really need the new longstr in a
single piece
for something. I.e., (untested sketch)
chunks_of_new_longstr = []
for chunk in chunker(longstr):
#edit chunk (your shortstr)
newlong.append(chunk) # or do several appends of pieces from the
editing of a chunk
longstr = ''.join(chunks_of_new_longstr)
But if you don't really need it except to write it to output and the next thing
would be
open('longstr.txt','wb').write(longstr) # might want 'w' instead of 'wb'
for plain text data
then don't bother joining into a new longstr but do
open('longstr.txt','wb').writelines(chunks_of_new_longstr)
instead. But if you are going to do that, why not just
fout = open('longstr.txt','wb')
before the loop, and
fout.write(chunk)
in place of
newlong.append(chunk)
Of course, if longstr is coming from a file, maybe you can have
the chunker operate on a file instead of a longstr in memory.
>Can I get over this performance problem without reimplementing the
>whole thing using a barebones list object? I though I was being "smart"
>by avoiding editing the long list, but then it struck me that I am
>creating a second object of the same size when I put the modified
>shorter string in place...
>
I imagine you should be able to change a very few lines to switch between
ways of getting your input stream of editable chunks and accumulating your
output.
OTOH, this is all guesswork without more context ;-)
Regards,
Bengt Richter
--
http://mail.python.org/mailman/listinfo/python-list
screen capture
I need to take a screen shot of the computer screen. I am trying to use PIL and I saw there is ImageGrab...however it only works on Windows. Is there a platform-independent ability to work around this? thanks -- http://mail.python.org/mailman/listinfo/python-list
ANN: rest2web 0.4.0alpha
rest2web 0.4.0 alpha is now available.
http://www.voidspace.org.uk/python/rest2web/
What's New ?
==
See
http://www.voidspace.org.uk/python/rest2web/reference/changelog.html#version-0-4-0-alpha-2005-11-11
Lots of bugfixes and new features since the 0.3.0 release.
Includes a new gallery plugin (which will also function as a standalone
HTML gallery generator).
http://www.voidspace.org.uk/python/rest2web/reference/gallery.html
There is also an experimental windows executable version.
The documentation has been greatly improved, including a tutorial which
should get anyone up to scratch on the basics very quickly.
http://www.voidspace.org.uk/python/rest2web/tutorial.html
What is rest2web
=
**rest2web** is a tool for autogenerating wesites, or parts of
websites. It's main features are :
* Integrated with docutils.
* Automatically builds index pages and navigation links (sidebars and
{acro;breadcrumbs;Weird name for navigation links ?}).
* Embedded code in templates for unlimited expressiveness.
* Flexible macro system.
* Uses relative links, so sites can be viewed from the filesystem.
* Unicode internally - so you don't have to be. {sm;:-p}
* Includes features for multiple translations of sites.
* Built-in gallery creator plugin.
* The basic system is very easy to use.
* Lots of powerful (optional) features.
The content can be stored as HTML, or in reST format; in which case the
HTML will be generated using docutils. **rest2web** inserts each page
into a template, and automatically creates index pages for sections,
and navigation links.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Ben Finney a écrit : > Michael <[EMAIL PROTECTED]> wrote: > >>Ben Finney wrote: >> >>>I've yet to see a convincing argument against simply assigning >>>values to names, then using those names. >> >>If you have a name, you can redefine a name, therefore the value a >>name refers to is mutable. > > > Since there are mutable and immutable values, it might be clearer to > say "the binding of a name to a value can be changed". Yes? > > In that case, I don't see why someone who wants such a binding to be > unchanging can't simply avoid changing it. Where's the case for having > Python enforce this? > The problem is not about having something constant ! The main point with symbols is to get human-readable values. Let say you have a symbol "opened" and a symbol "closed". The state of a file may be one of the two. If you have these symbols, you can ask for the state at any point and get something readable. If you use constants valued, typically, to integers, the state of your file will we 0 or 1, which does not mean anything. Now, if you're using an object with more than two states, and moreover if the number of states is likely to increase during developpement, it's much more convenient to directly get the *meaning* of the value rather than the value itself (which does not mean anything). The key point that, I think, you misunderstand is that symbols are not *variables* they are *values*. > >>Conversely consider "NAME" to be a symbol. I can't modify "NAME". It >>always means the same as "NAME" and "NAME", but is never the same as >>"FRED". What's tricky is I can't have namespaceOne."NAME" [1] and >>namespaceTwo."NAME" as different "NAME"s even though logically >>there's no reason I couldn't treat "NAME" differently inside each. > > > So you want to mark such objects as being in a namespace, where they > compare the same within that namespace but not outside. Why is > separate syntax necessary for this? A data type that is informed of > its "space", and refuses comparison with values from other spaces, > would suffice. > > class Xenophobe(object): > def __init__(self, space, value): > self.__space = space > self.__value = value > > def __str__(self): > return str(self.__value) > > def __cmp__(self, other): > if not isinstance(other, Xenophobe): > raise AssertionError, \ > "Can only compare Xenophobes to each other" > if not other.__space == self.__space: > raise AssertionError, \ > "Can only compare Xenophobes from the same space" > return cmp(self.__value, other.__value) > > With the bonus that you could pass such values around between > different names, and they'd *still* compare, or not, as you choose > when you first create them. > > Replace the AssertionError with some appropriate return value, if you > want such comparisons to succeed. > Well, I think a new syntax will promote the use of symbols. And as I think they are good practice (much better than meaningless constants) they should be promoted. Needless to say that in every language I know implementing symbols (or something close to symbols), there is an easy-to-use syntax associated. > >>However it might be useful to note that these two values (or >>symbols) are actually different, even if you remove their >>namespaces. > > > The above Xenophobe implementation creates objects that know their > "space" forever. > > >>To me, the use of a symbol implies a desire for a constant, and then >>to only use that constant rather than the value. In certain >>situations it's the fact that constant A is not the same as constant >>B that's important (eg modelling state machines). > > > Since the actual value can't be easily accessed, the only purpose of a > Xenophobe is too be created and compared to others. > > >>Often you can use strings for that sort of thing, but unfortunately >>even python's strings can't be used as symbols that are always the >>same thing in all ways. For example, we can force the id of >>identical strings to be different: > > > Hold up -- what in your stated use case requires *identity* to be the > same? You said you just wanted to compare them to each other. > > Besides, Python *does* preserve identity for short strings... > > >s = "h"*1 >x = "h"*1 >id(s), id(x) >> >>(135049832, 135059864) > > > ... which is sufficient for unique values, if you're not actively > fighting the system as above. If the use case is for brief, identical > values, we have those: short strings. Well, one *big* difference between short string and symbols is that the identity between short strings are implementation dependant, while between symbols it has to be in all implementations as you will rely on this identity. Then, once more, strings are just one possible implementation for symbols and I wouldn't like to tie that much symbols to strings
Re: Dictionary of tuples from query question
David Pratt wrote:
> Hi Fredrik. Many thanks for your reply and for the tuple tip. The
> cursor.fetchall returns a list of lists in this instance with each list
> in the main list containing the field values. With the tip, I
> simplified my code to:
>
> vlist_dict = {}
> record_count = 0
> for record in cursor.fetchall():
> record_count += 1
> vlist_dict[record_count] = tuple(record)
> print vlist_dict
>
> That's much better!
I meant to write
d = {}
for index, record in enumerate(cursor.fetchall()):
d[index+1] = tuple(record)
which can be shorted to
d = dict((k+1, tuple(v)) for k, v in enumerate(x))
in recent versions of Python.
--
http://mail.python.org/mailman/listinfo/python-list
newbie help needed
I am running the following program: def print Multiples (n, high): i = 1 while i <= high: print n*i, ' \t' , i = i + 1 print def printMultTable (high): i = 1 while i <= high: print Multiples (i, high) i = i + 1 printMultiples(8,8) printMultTable(8) Basically this program prints the correct multiplication table but instead of having just 8 rows it has 9 with the top row consisting of multiples of 8 then below the top row is a normal multiplication table...How can I get rid of the top row? Yahoo! FareChase - Search multiple travel sites in one click. -- http://mail.python.org/mailman/listinfo/python-list
How to write an API for a Python application?
Hello I would like to create an API for a piece of Python code. The API is for use by non Python code. It should support interaction in both directions, both accessing functions on the API and the ability for the API to raise events on its clients. What is the best way to do that? I though of doing it as a python COM server but I am not familiar with COM and I saw that implementing a COM server with events in python is not trivial. Is there a better (or simpler) solution?What are the common ways for doing that? Any answer would be greatly appreciated. Regards Gary -- http://mail.python.org/mailman/listinfo/python-list
Webware for Python 0.9 released
Webware 0.9 has been released. Webware for Python is a suite of Python packages and tools for developing object-oriented, web-based applications. The suite uses well known design patterns and includes a fast Application Server, Servlets, Python Server Pages (PSP), Object-Relational Mapping, Task Scheduling, Session Management, and many other features. Webware is very modular and easily extended. Webware for Python is well proven and platform-independent. It is compatible with multiple web servers, database servers and operating systems. The new release includes numerous enhancements, additions and bug fixes over the previous release. We can list only a few of them here: * easier installation * improved documentation * improved examples * bug fixes * a built-in HTTP server for immediate "playing", * a debug app server compatible with WingIDE and other debuggers * support for the Kid templating language * support for PostgreSQL * better support for recent versions of Python including properties, the object type and the datetime module Check out the Webware for Python home page at http://w4py.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Bengt Richter wrote: > You may be interested in reviewing > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3 > > before continuing this topic ;-) Interesting indeed, I mean the argument of why python does it this way. I see the equivalent of telling someone who's language read right to left about English : "What ? you don't know all good language should be read left to right". -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie help needed
"john boy" <[EMAIL PROTECTED]> wrote: > I am running the following program: > > def print Multiples (n, high): > i = 1 > while i <= high: > print n*i, ' \t' , > i = i + 1 > print > def printMultTable (high): > i = 1 > while i <= high: > print Multiples (i, high) > i = i + 1 > printMultiples(8,8) > printMultTable(8) > How can I get rid of the top row? by not calling "printMultiples" before you call "printMultTable", perhaps? that is, changing printMultiples(8,8) printMultTable(8) to printMultTable(8) should do the trick. -- http://mail.python.org/mailman/listinfo/python-list
mp3 wav editing in python
Hi, Is there a python based tool to cut mp3 and wav file at a start and end time? I'm looking for a python script that can output a new wav or mp3 file based on star and endpoint. Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Book
David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? I think most of the best books have been mentioned, but I thought that I'd add some comments. After all, different people have different ways of learning, and like different book styles. Both Martelli's "Python in a Nutshell" and Beazley's "Python Essential Reference" are mainly reference books. In a way, the standard library manual contains the same information, but Martelli's and Beazley's books explain things much better, and at least Martelli goes into a number of things outside the standard library. They have brief Python tutorials, but don't go into things like writing any larger programs involving things from several libraries etc. They are excellent if you want a high information density. The Python Cookbook mainly contains stuff from the Python Cookbook web site, but it's carefully selected, well edited (although a redundant line of code in my recipe remains) and in each chapter there is an initial discussion which is interesting. It's a great source of good Python code examples with explanations. If you prefer books that are more in Tutorial style, you might want to look at Dive Into Python (try it out in the web version first) or Magnus Hetland's new book (which is basically an update of his previous book with a different title.) I think the Python 2.1 Bible was good too, but it's a bit old by now. Then there are a lot of other books that are more narrow in scope, like Holden's Web Programming book, Ascher & Robinson's Windows book etc, but most of them are a few years old, and things change rapidly when it comes to libraries and tools in various niches. Many of these books are still very good and useful, but it takes some familarity with the Python world to know what to use in these books, and what to find more current information for. I hope you'll have a great time with Python! -- http://mail.python.org/mailman/listinfo/python-list
Not enough arguments for format string
I'm getting an error in a Python script I'm writing: "not enough
arguments for format string." The error comes at the end of the
os.system command, referenced below. Any ideas?
---
import EasyDialogs
import os
import sys
password = EasyDialogs.AskPassword("To launch Ethereal, please enter
your password:")
binpath = os.path.join(os.path.dirname(sys.argv[0]),
'/opt/local/bin/ethereal')
os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
DISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath)
TypeError: not enough arguments for format string
--
Cheers,
Kevin Walzer, PhD
WordTech Software - "Tame the Terminal"
http://www.wordtech-software.com
sw at wordtech-software.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Not enough arguments for format string
Hey Kevin,
I think I see your issue. So from http://docs.python.org/lib/typesseq-strings.html:
If format requires a single argument, values may be a
single non-tuple object. Otherwise, values must be a tuple with
exactly the number of items specified by the format string, or a
single mapping object (for example, a dictionary).On 11/14/05, Kevin Walzer <[EMAIL PROTECTED]
> wrote:
os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; exportDISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath)
So the line above should be:
os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
DISPLAY; echo %s | sudo -S %s; sudo -k' % (password binpath))
try that.
johnnie
--
http://mail.python.org/mailman/listinfo/python-list
Re: Not enough arguments for format string
Missing a comma there :)
On 14/11/05, johnnie pittman <[EMAIL PROTECTED]> wrote:
> So the line above should be:
>
> os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
> DISPLAY; echo %s | sudo -S %s; sudo -k' % (password binpath))
>
> try that.
os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
DISPLAY; echo %s | sudo -S %s; sudo -k' % (password, binpath))
--
http://mail.python.org/mailman/listinfo/python-list
Re: Not enough arguments for format string
Kevin Walzer a écrit :
> I'm getting an error in a Python script I'm writing: "not enough
> arguments for format string." The error comes at the end of the
> os.system command, referenced below. Any ideas?
>
> ---
>
> import EasyDialogs
> import os
> import sys
>
>
> password = EasyDialogs.AskPassword("To launch Ethereal, please enter
> your password:")
> binpath = os.path.join(os.path.dirname(sys.argv[0]),
> '/opt/local/bin/ethereal')
>
> os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
> DISPLAY; echo %s | sudo -S %s; sudo -k' %password %binpath)
>
> TypeError: not enough arguments for format string
>
>
Well, just try :
os.system('open -a X11.app; cd ~/; printenv; DISPLAY=:0.0; export
DISPLAY; echo %s | sudo -S %s; sudo -k' % (password, binpath) )
The reason is, you have 2 "%s" in yor string, thus after the "%"
operator, you need a 2-element tuple ! If you have either more or less
element, you'll get a TypeError ! In your code above you put a single
element ...
Pierre
--
http://mail.python.org/mailman/listinfo/python-list
replacing multiple instances of commas beginning at specific position
I have a comma delimited text file that has multiple instances of multiple commas. Each file will contain approximatley 300 lines. For example: one, two, threefour,fivesix one, two, three,four,,eighteen, and so on. There is one time when multiple commas are allowed. Just prior to the letters ADMNSRC there should be one instance of 4 commas. ( ,eightADMNSRC,thirteen, ). The text ADMNSRC is NOT in the same place on each line. What would be the best approach to replace all instances of multiple commas with just one comma, except for the 4 commas prior to ADMNSRC? Any help would be greatly appreciated. TIA, Kevin -- http://mail.python.org/mailman/listinfo/python-list
how do i use "tkinter.createfilehandler" with a regular c program?
I am trying to write a GUI with tkinter that displays the stdout from a
regular C/C++ program in a text widget.
The idea i was trying to use was as follows:
1) use "popen" to execute the C/C++ program
2) then use "tkinter.createfilehandler" to create a callback that would
be called when the C/C++ program creates output on stdout.
Somehow, I can't get this to work. here is what I have tried so far:
import sys,os
from Tkinter import *
root = Tk()
mainFrame = Frame(root)
textBox = Text(mainFrame)
textBox.pack(fill=BOTH, expand=YES)
mainFrame.pack(fill=BOTH, expand=YES)
fh = os.popen('/homes/jschamba/tof/pcan/pcanloop')
def readfh(filehandle, stateMask):
global textBox
newText = filehandle.read()
textBox.insert(END, newText)
tkinter.createfilehandler(fh, tkinter.READABLE, readfh)
root.mainloop()
I don't see any of the stdout from my program appear in the textbox.
Does anyone have a short example that I could use as an inspiration for
this task?
I guess what my ultimate goal would be is to create something similar to
the "expectk" call "expect_background", which does exactly what i just
described, i.e. wait for output from a shell/C/C++ program and then do
something in response to this output like insert it into a text widget.
In expect, the following program seems to work:
#!/usr/bin/expectk -f
# disable terminal output
log_user 0
spawn -noecho /homes/jschamba/tof/pcan/pcanloop
set shell $spawn_id
text .shell -relief sunken -bd 1 -width 90 -height 24 -yscrollcommand
{.scroll set}
scrollbar .scroll -command {.shell yview}
pack .scroll -side right -fill y
pack .shell -side bottom -expand true -fill both
expect_background {
-i $shell -re "\[^\x0d]+" {
.shell insert end $expect_out(0,string)
.shell yview -pickplace insert
}
}
Jo
--
Dr Joachim Schambach
The University of Texas at Austin
Department of Physics
1 University Station C1600
Austin, Texas 78712-0264, USA
Phone: (512) 471-1303; FAX: (814) 295-5111
e-mail: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
SnakeCard products source code
Dear all, The source code is available in the download section: www.snakecard.com Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying small chunks from long string
In article <[EMAIL PROTECTED]>,
"MackS" <[EMAIL PROTECTED]> wrote:
> Hello everyone
>
> I am faced with the following problem. For the first time I've asked
> myself "might this actually be easier to code in C rather than in
> python?", and I am not looking at device drivers. : )
>
> This program is meant to process relatively long strings (10-20 MB) by
> selectively modifying small chunks one at a time. Eg, it locates
> approx. 1000-2000 characters and modifies them. Currently I was doing
> this using a string object but it is getting very slow: although I only
> modify a tiny bit of the string at a time, a new entire string gets
> created whenever I "merge" it with the rest. Eg,
>
> shortstr = longstr[beg:end]
>
> # edit shortstr...
>
> longstr = longstr[:beg] + shortstr + longstr[end:] # new huge string is
> created!!
>
> Can I get over this performance problem without reimplementing the
> whole thing using a barebones list object? I though I was being "smart"
> by avoiding editing the long list, but then it struck me that I am
> creating a second object of the same size when I put the modified
> shorter string in place...
A couple of minutes experimenting with array.array at the python command
line indicates that it will work fine for you. Quite snappy on a 16 MB
array, including a slice assignment of 1 KB near the beginning.
Array.array is probably better than lists for speed, and uses less
memory. It is the way to go if you are going to be randomly editing all
over the place but don't need to convert to string often.
MutableString warns that it is very slow. It seems to work by having a
string data item that it keeps replacing. I didn't try it.
> shortstr = longstr[beg:end]
>
> # edit shortstr...
>
> longstr = longstr[:beg] + shortstr + longstr[end:] # new huge string is
> created!!
Replace this with slice assignment:
longarray = array.array('c',longstr) # once only at beginning!
shortstring = longarray[beg:end].tostring() # or just edit an array
# edit shortstring (or shortarray)
longarray[beg:end] = array.array('c',shortstr)
longstring = longarray.tostring() # if needed
TonyN.:'[EMAIL PROTECTED]
'
--
http://mail.python.org/mailman/listinfo/python-list
Re: mp3 wav editing in python
yb wrote:
> Hi,
>
> Is there a python based tool to cut mp3 and wav file at a start and end
> time? I'm looking for a python script that can output a new wav or mp3
> file based on star and endpoint.
>
> Thank you
>
there is a wave module
>>> import wave
>>> dir(wave)
['Chunk', 'Error', 'WAVE_FORMAT_PCM', 'Wave_read', 'Wave_write',
'__all__', '__builtin__', '__builtins__', '__doc__', '__file__',
'__name__', '_array_fmts', 'big_endian', 'open', 'openfp', 'struct']
>>> wav= wave.open("/musik/musik/wav/Co - 1.wav")
>>> wav
>>> dir(wav)
['__del__', '__doc__', '__init__', '__module__', '_compname',
'_comptype', '_convert', '_data_chunk', '_data_seek_needed', '_file',
'_fmt_chunk_read', '_framerate', '_framesize', '_i_opened_the_file',
'_nchannels', '_nframes', '_read_fmt_chunk', '_sampwidth', '_soundpos',
'close', 'getcompname', 'getcomptype', 'getfp', 'getframerate',
'getmark', 'getmarkers', 'getnchannels', 'getnframes', 'getparams',
'getsampwidth', 'initfp', 'readframes', 'rewind', 'setpos', 'tell']
>>> wav.getnchannels()
2
>>>
and so on, this is what google gave me
http://scipy.mit.edu/tutorials/wave.pdf
I did some wave ploting with matplotlib module, so I think
it's feasible to cut and write wave files too
as for mp3, I don't know of any modules
I think mainly because of license issue
you could decode mp3 to wav and process whatever you want to process
but to encode them back into mp3 is a problem
maybe you could use lame or bladeenc as a command line tool
or use ogg instead
http://www.andrewchatham.com/pyogg/
there are de/encoders freely available
this may also be interessting to you
http://pymedia.org/
hth, Daniel
--
http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
On Mon, 14 Nov 2005 09:53:34 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:
>Antoon Pardon <[EMAIL PROTECTED]> writes:
>> Op 2005-11-10, Mike Meyer schreef <[EMAIL PROTECTED]>:
>>> [Context recovered from top posting.]
>>> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
Daniel Crespo wrote:
> Well, I hope that newcomers to Python don't confuse himselves :)
This mutable/immutable object and name/variable is confusing.
>>> Only if you have to overcome a conviction that variables behave in a
>>> different way. If you've never seen them behave another way, or have
>>> already gotten used to this model from another language (it dates back
>>> to the 60s, if not the late 50s), then it's no problem. I'm sure the
>>> problem exists in the opposite direction, except that few people
>>> travel that route.
>>> Most OO languages do the name/variable thing, but some of the popular
>>> ones aren't consistent about it, giving some types "special" status,
>>> so that sometimes "a = b" causes b to be copied onto a, and sometimes
>>> it causes a to become a pointer to b. I find a consistent approach is
>>> preferable.
>> But what about a consistent approach, that allows choice.
>
>It's been done in other languages. But it requires more care than one
>would think.
>
>> Like having an assignment operator (let use @= for it) next to a
>> (re)bind operator.
>>
>> We could then have something like the following.
>>
>> a = 5
>> b = a
>> a @= 7
>> b ==> would result in 7.
>
>You've just overwritten the object referred to by the token "5" in the
>source code with the value 7, so you get:
>
>print 5
>7
>
>Not exactly a desirable outcome, but some language implementations
>have allowed this kind of thing in the past. You either have to make
>all objects mutable, or disallow assignment to immutable objects,
>which sort of defeats the purpose.
>
>Another approach is to have a special object type if you want to allow
>assignment to the object it refers to. That's what Python does now, it
>just doesn't have a syntax just to support that. If it did, your
>example might look like:
>
>a := 5
>b = @a
>a := 7
>@b ==> would result in 7
>
If you are willing to keep your "variables" in a namespace, it's easy
to make "pointers" that you can dereference like @b, except
-- given a preliminary:
(see PNS from
http://groups.google.com/group/comp.lang.python/msg/54a7ab01906683ca )
>>> from pns import PNS
>>> class NS(object):
... def __call__(self, name): return PNS(self, name)
...
>>> ns = NS()
-- and then you have to spell it a little differently:
>>> ns.a = 5# a := 5
>>> b = ns('a') # b = @a
>>> ns.a = 7# a := 7
>>> b.v # @b
7
For another slant, laundering all ns assignments through pickle dumps/loads
to get a fresh value so as not to share references, and simulate value
assignment sematics (I think? ;-/)
http://groups.google.com/group/comp.lang.python/msg/f29cf8e25b42d5cb
with a different spelling for pointer use (ns['a'] instead of ns('a') above,
and b[:] instead of b.v)
The class also gave you a way to spell the typical C address/pointer/deref ops.
It's based on a name space class that gives you a name space object (say ns)
for the "variables" that you can get "pointers" to like ptr = &var and which
you can pass around and use with dereferencing like *ptr for either assignment
or on the right hand side. Once you have a names space ns = NSHorne() you can
set variables in the ordinary way as attributes, or get "pointers" and use
them via *p semantics
>>> from ns_horne import NSHorne
>>> ns = NSHorne()
>>> ns.x = 'x value'
>>> ptr = ns['x']
>>> ptr[:]
'x value'
Now make a function that will use the pointer
>>> def set(p, v):
... p[:] = v
...
>>> set(ptr, 123)
Check indirect result
>>> ns.x
123
>>> ptr[:]
123
>>> ptr[:] += 321
>>> ns.x
444
Pseudo-value-semantics:
>>> from ns_horne import NSHorne
>>> ns = NSHorne()
>>> ns.z = [1,2]
>>> pz = ns['z']
>>> pz[:]
[1, 2]
>>> ns.z2 = pz[:]
>>> ns.z
[1, 2]
>>> ns.z2
[1, 2]
>>> pz[:][0]='z via pz'
>>> ns.z
['z via pz', 2]
>>> ns.z2
[1, 2]
>>> pz[:]
['z via pz', 2]
Or value semantics without confusing with pointer stuff:
>>> ns.z3 = ns.z2
now equal values, but not the same objects:
>>> ns.z3, ns.z2
([1, 2], [1, 2])
>>> ns.z2[1]='z2 via ns.z2'
>>> ns.z3
[1, 2]
>>> ns.z2
[1, 'z2 via ns.z2']
Regards,
Bengt Richter
--
http://mail.python.org/mailman/listinfo/python-list
Re: replacing multiple instances of commas beginning at specific position
On Nov 14, striker wrote:
> I have a comma delimited text file that has multiple instances of
> multiple commas. Each file will contain approximatley 300 lines.
> For example:
>
> one, two, threefour,fivesix
> one, two, three,four,,eighteen, and so on.
>
> There is one time when multiple commas are allowed. Just prior to
> the letters ADMNSRC there should be one instance of 4 commas. (
> ,eightADMNSRC,thirteen, ). The text ADMNSRC is NOT in the same
> place on each line.
>
> What would be the best approach to replace all instances of multiple
> commas with just one comma, except for the 4 commas prior to
> ADMNSRC?
One possible approach:
#! /usr/bin/env python
import re
# This list simulates the actual opened file.
infile = [
'one, two, three,four,,ADMNSRCeighteen,',
'one, two, three,four,five,six'
]
# Placeholder for resultant list.
result = []
for item in infile:
# Use a regex to just reduce *all* multi-commas to singles.
item = re.sub(r',{2,}', r',', item)
# Add back the desired commas for special case.
item = item.replace('ADMNSRC', ',,,ADMNSRC')
# Remove spaces??
item = item.replace(' ', '')
# Add to resultant list.
result.append(item)
--
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
--
http://mail.python.org/mailman/listinfo/python-list
Re: replacing multiple instances of commas beginning at specific position
striker wrote:
> I have a comma delimited text file that has multiple instances of
> multiple commas. Each file will contain approximatley 300 lines. For
> example:
>
> one, two, threefour,fivesix
> one, two, three,four,,eighteen, and so on.
>
> There is one time when multiple commas are allowed. Just prior to the
> letters ADMNSRC there should be one instance of 4 commas. (
> ,eightADMNSRC,thirteen, ). The text ADMNSRC is NOT in the same
> place on each line.
>
> What would be the best approach to replace all instances of multiple
> commas with just one comma, except for the 4 commas prior to ADMNSRC?
Seems like a typical use case for the re module...
-> now you've got *2* problems- !-)
--
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: generate HTML
Jeffrey Schwab wrote:
> [EMAIL PROTECTED] wrote:
...
>> def genpage(arg1,arg2):
>>print ''' BLAH BLAH.%s %s
>> ''' % (arg1, arg2)
...
>> i wish to print all these into a HTML output file so that
>> when i click on it, it shows me the html page. How can i do that?
> ...
> Why not just redirect the output of your Python script from the shell?
> E.g.:
>
> python generate_html.py > output.html
Or you can even do the following Python dance:
def gen_to_file(filename, arg1, arg2):
import sys
former, sys.stdout = sys.stdout, open("output.html", "w")
try:
genpage(arg1, arg2)
finally:
htmlfile, sys.stdout = sys.stdout, former
htmlfile.close()
print 'file %r written' % filename
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of tuples from query question
Thanks Fredrik for your help. Really short and efficient - very nice!
Regards,
David
On Monday, November 14, 2005, at 12:12 PM, Fredrik Lundh wrote:
> I meant to write
>
> d = {}
> for index, record in enumerate(cursor.fetchall()):
> d[index+1] = tuple(record)
>
> which can be shorted to
>
> d = dict((k+1, tuple(v)) for k, v in enumerate(x))
>
> in recent versions of Python.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Pierre Barbier de Reuille wrote: > Please, note that I am entirely open for every points on this proposal > (which I do not dare yet to call PEP). I still don't see why you can't just use strings. The only two issues I see you might have with them are a) two identical strings might not be identical by id(), b) they aren't local in scope. The objection a) is minor. One, all of your examples use equality for testing already, and two, short strings are interned and identical in most cases anyway (they only differ if you go to lengths to create them, or they aren't sufficiently "variable like") - at most you would have to standardize the rules. The objection b) is a little harder to dismiss. But I'm not sure if you've completely thought what it means for a symbol to be "local to a module". What happens when you assign a variable containing a symbol to a variable in another module? For that matter, what does it mean to be "in a module". Which module is a class instance (and associated sybols) "in" if the class is defined in one module, instantiated in another, and then passed as a return value to a third? What about from ... imports? If you need a symbol "from another class" what's the mechanism of obtaining it? Can you import symbols? Since you advocate storing symbols internally as integers, I suppose you would have a program-global table to keep symbols from different modules from having the same internal representation. How do you pickle a symbol and have it go to a different Python program, which may have a massive symbol table of it's own? It's been said before, and I'll say it again - the key to successful Python language changes is compelling use cases. Find an existing Python program or library (the stdlib is best) which would be markedly improved by your language change. Not only will Guido be more likely to be convinced, but what you're proposing will likely be clearer to everyone else, if it's grounded in practical use cases. -- http://mail.python.org/mailman/listinfo/python-list
more newbie help needed
using the following program: fruit = "banana" index = 0 while index < len (fruit): letter = fruit[index-1] print letter index= index -1 this program is supposed to spell "banana" backwards and in a vertical patern...it does thisbut after spelling "banana" it gives an error message: refering to line 4: letter = fruit[index-1] states that it is an IndexError and the string index is out of range Anybody know how to fix this? Yahoo! FareChase - Search multiple travel sites in one click. -- http://mail.python.org/mailman/listinfo/python-list
Making a persistent HTTP connection
I use urllib2 to do some simple HTTP communication with a web server. In one "session", I do maybe 10-15 requests. It seems that urllib2 opens op a connection every time I do a request. Can I somehow make it use _one_ persistent connection where I can do multiple GET->"receive data" passes before the connection is closed? /David -- http://mail.python.org/mailman/listinfo/python-list
Tix BUG? Where to submit?
I've been developing a piece of software using Tix. In particular, I'm using the HList widget. I was attempting to use the info_bbox() mentod of that class to get the bounding box of a list entry. I'm using the release version Python 2.4.2. When I look in Tix.py I see that info_bbox() is not available. Well, I don't know much about the library, Tk or Tix but it appears that all the other methods are implemented. Using those as templates I attempted to add the function just to see what would happen. I added the folloing to Tix.py line 961. def info_bbox( self, entry ): coords = self.tk.call( self._w, 'info', 'bbox', entry ).split( ' ') return map( int, coords ) Surprising to myself, this was all that it took to make this work. So I'm not sure why this method was left out. Could it have been an oversight? Anyway, where would I subit this report to have it considered that this be added to Tix? Thanks for your help. Ron Provost -- http://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
john boy wrote: > using the following program: > > fruit = "banana" > index = 0 > while index < len (fruit): > letter = fruit[index-1] > print letter > index= index -1 > > this program is supposed to spell "banana" backwards and in a vertical > patern...it does thisbut after spelling "banana" it gives an error > message: > refering to line 4: letter = fruit[index-1] > states that it is an IndexError and the string index is out of range > Anybody know how to fix this? > Change the termination condition on your loop. If you print out the values of index as the loop goes round you'll see you are printing characters whose index values are -1, -2, ..., -6 Unfortunately -7 is less than -6, so your loop keeps on going, with the results you observe. Note, however, that there are more pythonic ways to perform this task. You might try: for index in range(len(fruit)): letter = fruit[-index-1] print letter as one example. I'm sure other readers will have their own ways to do this, many of them more elegant. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
"john boy" <[EMAIL PROTECTED]> wrote: > using the following program: > > fruit = "banana" > index = 0 > while index < len (fruit): > letter = fruit[index-1] > print letter > index= index -1 > after spelling "banana" it gives an error message: > refering to line 4: letter = fruit[index-1] > states that it is an IndexError and the string index is out of range > Anybody know how to fix this? add "print index" before the "letter =" line to see what your program is doing, and what index is when you get the error. then read this: http://docs.python.org/tut/node5.html#SECTION00512 -- http://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
> Note, however, that there are more pythonic ways to perform this task. > You might try: > > for index in range(len(fruit)): >letter = fruit[-index-1] >print letter Or, if you're *really* just trying to reverse the string, then the following might read more easily (although it's probably longer): fruit="banana" fruit = list(fruit) fruit.reverse() fruit = ''.join(fruit) print fruit It turns the string into a list, reverses it, joins it back together (back into a string), then prints it. Craig -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
"Ben Sizer" <[EMAIL PROTECTED]> writes: >> It is? Is the Python disassembler so much advanced over the state of >> the art of binary disassemblers, then? Or maybe it's the Python >> decompilers that are so advanced? > Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be > pretty advanced. I don't know if you can download it any more to test > this claim though. No, it doesn't claim to be advanced. It claims to be good at what it does. There's no comparison with other decompilers at all. In particular, this doesn't give you any idea whether or not similar products exist for x86 or 68k binaries. Your claim was that it's easier to go from pyc files to code than from binaries to code. To show that, you have to show not only that it's easy to go from pyc files to code, but that it's hard to go from binary files to code. I've dealt with some very powerfull disassemblers and decompilers, but none of them worked on modern architectures. >> As far as I can tell, the only real >> difference between Python bytecodes and x86 (for instance) binaries is >> that Python bytecodes keep the variable names around so it can do >> run-timme lookups. That's not that big a difference. > It makes a lot of difference when you're hunting around for something > or trying to understand a bit of code. Python bytecode (or at least, > the output from dis) is also a lot more straightforward than x86 or 68K > assembly to decipher. I'm not convinced of the former. I'll grant you half of the latter. 68K machine language is fairly straightforward. On the other hand, it's also seems to be irrelevant. What platform are you developing for that's still based on the 68K? >> > I'd just like to make it non-trivial to make or use additional copies. >> How do you do that without infringing my fair use rights? > Yes, I suppose my terminology there was wrong. The term I should > probably have used was 'distribute usable additional copies'. My question still stands, though - and unanswered. > On the other hand though, what you term a 'fair use right' is not > necessarily viewed that way under law. The relevant part of the law (at > least in the US) says "it is not an infringement for the owner of a > copy of a computer program to make or authorize the making of another > copy or adaptation of that computer program provided [...] that such > new copy or adaptation is for archival purposes only", which is quite > distinct, legally speaking, from saying "you have the right to make a > copy or adaptation for archival purposes". I think this just makes explicit that those activies are indeed fair use, which is what non-infringing copying is called, and that you're playing semantic games to salve your conscience. But we can be explicit if you want: How do you do that without requiring that your software be given special consideration in the distaster recovery and preparedness planning? You should be concerned about this, as that special consideration is often "Return that POS". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
Steve Holden wrote: > Note, however, that there are more pythonic ways to perform this task. > You might try: > > for index in range(len(fruit)): > letter = fruit[-index-1] > print letter > > as one example. I'm sure other readers will have their own ways to do > this, many of them more elegant. looks like you've missed some recent additions: for char in reversed(fruit): print char -- http://mail.python.org/mailman/listinfo/python-list
Re: SnakeCard products source code
Thanks for sharing it. I am interested in the GINA part. Philippe C. Martin wrote: > Dear all, > > The source code is available in the download section: www.snakecard.com > > Regards, > > Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: SnakeCard products source code
I have not tested it with longhorn yet, but it works fine with XP-pro and 2000. Regards, Philippe Kris wrote: > Thanks for sharing it. I am interested in the GINA part. > > > Philippe C. Martin wrote: >> Dear all, >> >> The source code is available in the download section: www.snakecard.com >> >> Regards, >> >> Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: how do i use "tkinter.createfilehandler" with a regular c program?
Compared to your program, I
* Made sure that the slave program actually flushed its stdout buffers
* didn't call read(), which will by default continue reading until
it reaches EOF, not merely read the available data
#!/usr/bin/env python
import sys, time, Tkinter, itertools, _tkinter, os
if '-slave' in sys.argv:
for i in itertools.count():
time.sleep(1)
print "This is a line of output:", i
sys.stdout.flush()
raise SystemExit
root = Tkinter.Tk()
root.wm_withdraw()
fh = os.popen('%s -slave' % sys.argv[0])
def reader(*args):
line = fh.readline()
if not line:
print "EOF from slave"
raise SystemExit
print "from slave: %r" % line
_tkinter.createfilehandler(fh, Tkinter.READABLE, reader)
root.mainloop()
pgpGq56Vnc7dS.pgp
Description: PGP signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tix BUG? Where to submit?
Since this is a bug in Python (Tix.py), it should be submitted to the Python Patch tracker at sf.net/projects/python You need a free "sourceforge" account to submit an item to the bug or patch tracker. Jeff pgp1zmMFcYHrz.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
q: console widgets for *nix and windows?
Hi, Can anyone please recommend a widget library for text console, that works not only on *nix systems but windows /as well/? I'm looking for something a bit higher-level than pure curses, preferably with a gui-like set of widgets, event loop, handler methods etc. Thanks in advance for your recommendations. -- Cheers aum -- http://mail.python.org/mailman/listinfo/python-list
Re: q: console widgets for *nix and windows?
On 2005-11-14, aum <[EMAIL PROTECTED]> wrote: > Can anyone please recommend a widget library for text console, > that works not only on *nix systems but windows /as well/? > > I'm looking for something a bit higher-level than pure curses, > preferably with a gui-like set of widgets, event loop, handler > methods etc. http://tvision.sourceforge.net/ -- Grant Edwards grante Yow! I'm using my X-RAY at VISION to obtain a rare visi.comglimpse of the INNER WORKINGS of this POTATO!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Rocco Moretti wrote: > Pierre Barbier de Reuille wrote: >> Please, note that I am entirely open for every points on this proposal >> (which I do not dare yet to call PEP). > > I still don't see why you can't just use strings. As does Guido. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: how do i use "tkinter.createfilehandler" with a regular c program?
In article <[EMAIL PROTECTED]>,
Jo Schambach <[EMAIL PROTECTED]> wrote:
>I am trying to write a GUI with tkinter that displays the stdout from a
>regular C/C++ program in a text widget.
>The idea i was trying to use was as follows:
>
>1) use "popen" to execute the C/C++ program
>2) then use "tkinter.createfilehandler" to create a callback that would
>be called when the C/C++ program creates output on stdout.
>
>Somehow, I can't get this to work. here is what I have tried so far:
>
>import sys,os
>from Tkinter import *
>
>root = Tk()
>mainFrame = Frame(root)
>textBox = Text(mainFrame)
>textBox.pack(fill=BOTH, expand=YES)
>mainFrame.pack(fill=BOTH, expand=YES)
>
>fh = os.popen('/homes/jschamba/tof/pcan/pcanloop')
>
>def readfh(filehandle, stateMask):
>global textBox
>newText = filehandle.read()
>textBox.insert(END, newText)
>
>tkinter.createfilehandler(fh, tkinter.READABLE, readfh)
>root.mainloop()
Changingfilehandle.read() to filehandle.readline() and running a
separate output generator, this seems to work, although the Text
widget fills rapidly:
= test generator - creates a pipe and writes the time once/second
#!/usr/local/bin/python
import os, time
try:
pipe = os.mkfifo('./pipe', 0660)
except OSError, (errno):
if errno == 17:
pass
fh = open('./pipe', 'w')
rh = open('./pipe', 'r') # keep the pipe having a reader
while True:
fh.write("%s\n" % time.asctime(time.localtime()))
fh.flush()
time.sleep(1)
== read the output and put in a Text widget:
#!/usr/bin/python
import sys,os
from Tkinter import *
root = Tk()
mainFrame = Frame(root)
textBox = Text(mainFrame)
textBox.pack(fill=BOTH, expand=YES)
mainFrame.pack(fill=BOTH, expand=YES)
fh = os.popen('/bin/cat /tmp/pipe', 'r', 1)
def readfh(filehandle, stateMask):
global textBox
newText = filehandle.readline()
textBox.insert(END, newText)
tkinter.createfilehandler(fh, tkinter.READABLE, readfh)
root.mainloop()
--
Jim Segrave ([EMAIL PROTECTED])
--
http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
Pierre Barbier de Reuille <[EMAIL PROTECTED]> wrote:
> The problem is not about having something constant !
> The main point with symbols is to get human-readable values.
> Let say you have a symbol "opened" and a symbol "closed". The state
> of a file may be one of the two.
from some_enum_module import Enum
FileState = Enum('open', 'closed')
input_file.state = FileState.closed
> If you have these symbols, you can ask for the state at any point
> and get something readable. If you use constants valued, typically,
> to integers, the state of your file will we 0 or 1, which does not
> mean anything.
str(input_file.state) # -> 'closed'
> Now, if you're using an object with more than two states, and
> moreover if the number of states is likely to increase during
> developpement, it's much more convenient to directly get the
> *meaning* of the value rather than the value itself (which does not
> mean anything).
PixelColour = Enum('red', 'green', 'blue', 'black')
> The key point that, I think, you misunderstand is that symbols are
> not *variables* they are *values*.
So far, I see nothing that requires anything but a special object type
with the behaviour you describe. Which most of the enumerated-type
implementations do quite neatly.
> Well, once more, new syntax for new objects never solve new
> problems, they just make them easier to write.
If you want to promote something, it would be best to implement it and
demonstrate some problems that it solves. You don't seem to be arguing
against a new object type, so perhaps it would be best to simply start
using that type to solve some actual problems.
Since "promotion" is the only argument you've given for new syntax
for this concept, I don't see what is served talking about creating
syntax for something that does not yet exist to be promoted. Once an
implementation exists for examination and is actually useful to some
amount of users for solving actual problems, that's the time to talk
about promoting it.
--
\ "I went to the cinema, it said 'Adults: $5.00, Children $2.50'. |
`\ So I said 'Give me two boys and a girl.'" -- Steven Wright |
_o__) |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list
Re: how do i use "tkinter.createfilehandler" with a regular c program?
Thanks, that seems to work.
maybe one more question on this subject:
how can i use the callback function to the "createfilehandler" call from
within a class?
in other words, what would be the signature of the callback function, if
I made it a member of a class?
The documentation says that the callback is called with the arguments:
callback(filehandle, stateMask)
but a class member function always has the "self" argument as is first
argument. So would the syntax be:
class GUI:
def __init__:
.
def filehandlerCallback(self, filehandle, stateMask):
Jo
[EMAIL PROTECTED] wrote:
> Compared to your program, I
> * Made sure that the slave program actually flushed its stdout buffers
> * didn't call read(), which will by default continue reading until
>it reaches EOF, not merely read the available data
>
> #!/usr/bin/env python
> import sys, time, Tkinter, itertools, _tkinter, os
>
> if '-slave' in sys.argv:
> for i in itertools.count():
> time.sleep(1)
> print "This is a line of output:", i
> sys.stdout.flush()
> raise SystemExit
>
> root = Tkinter.Tk()
> root.wm_withdraw()
>
> fh = os.popen('%s -slave' % sys.argv[0])
>
> def reader(*args):
> line = fh.readline()
> if not line:
> print "EOF from slave"
> raise SystemExit
> print "from slave: %r" % line
>
> _tkinter.createfilehandler(fh, Tkinter.READABLE, reader)
> root.mainloop()
--
Dr Joachim Schambach
The University of Texas at Austin
Department of Physics
1 University Station C1600
Austin, Texas 78712-0264, USA
Phone: (512) 471-1303; FAX: (814) 295-5111
e-mail: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Making a persistent HTTP connection
David Rasmussen wrote: > I use urllib2 to do some simple HTTP communication with a web server. In > one "session", I do maybe 10-15 requests. It seems that urllib2 opens op > a connection every time I do a request. Can I somehow make it use _one_ > persistent connection where I can do multiple GET->"receive data" passes > before the connection is closed? Are you sure HTTP supports that? This would be news to me - which doesn't mean much :) And even if it works - what is the problem with connections being created? Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Making a persistent HTTP connection
Diez B. Roggisch wrote: > David Rasmussen wrote: >> I use urllib2 to do some simple HTTP communication with a web server. In >> one "session", I do maybe 10-15 requests. It seems that urllib2 opens op >> a connection every time I do a request. Can I somehow make it use _one_ >> persistent connection where I can do multiple GET->"receive data" passes >> before the connection is closed? > > Are you sure HTTP supports that? This would be news to me - which > doesn't mean much :) It does (HTTP/1.1 at least) and it's called 'keep-alive'. > And even if it works - what is the problem with connections being created? Performance, network load... -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list
Parse file into array
I was wondering how i could parse the contents of a file into an array. the file would look something like this: gif:image/gif html:text/html jpg:image/jpeg ... As you can see, it contains the mime type and the file extension seperated by commas, 1 per line. I was wondering if it was possible to create and array like this: (Pseudocode) mimetypearray[gif] = "image/gif" mimetypearray[html] = "text/html" mimetypearray[jpg] = "image/jpeg" ... I come from a PHP backround where I know this is possible, but I am new at Python. Please disregard this if it is a stupid question. -- http://mail.python.org/mailman/listinfo/python-list
Re: more newbie help needed
Craig Marshall wrote: > Or, if you're *really* just trying to reverse the string, then the > following might read more easily (although it's probably longer): > fruit = list(fruit) > fruit.reverse() > fruit = ''.join(fruit) same thing, on one line: fruit = "".join(reversed(fruit)) same thing, in one operation: fruit = fruit[::-1] -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
On Mon, 14 Nov 2005 17:15:04 +0100, Pierre Barbier de Reuille wrote:
> The problem is not about having something constant !
> The main point with symbols is to get human-readable values.
> Let say you have a symbol "opened" and a symbol "closed". The state of a
> file may be one of the two.
>
> If you have these symbols, you can ask for the state at any point and
> get something readable. If you use constants valued, typically, to
> integers, the state of your file will we 0 or 1, which does not mean
> anything.
???
Why does the byte string "\x6f\x70\x65\x6e\x65\x64" have intrinsic meaning
when the int 0 doesn't? It certainly doesn't mean anything to non-English
speakers.
If all you want is human readable byte strings, then just use them:
class MyFile:
def open(self):
self.state = "opened"
def close(self):
self.state = "closed"
You don't need special syntax to use strings as symbols, you get them for
free without all the overhead you are proposing.
> Now, if you're using an object with more than two states, and moreover
> if the number of states is likely to increase during developpement, it's
> much more convenient to directly get the *meaning* of the value rather
> than the value itself (which does not mean anything).
How do you expect this to work in practice? You have an object which
has states:
obj = SomeThingComplex()
Now you want to operate on it according to the state. What do you do?
if obj.state is $closed$:
obj.open()
elif obj.state is $opened$:
obj.close()
elif obj.state is $full$:
obj.make_empty()
elif obj.state is $empty$:
obj.make_full()
else:
# some other symbol
raise ValueError("Unexpected state %s") % obj.state
Replace "is" with "==" and $ with " and you have strings. You still need
to know what the object state is, and the way you do that is by comparing
it to something. Whether you call that something a symbol, an enum, a
string, an int, a class, whatever, the comparison still needs to be done.
> The key point that, I think, you misunderstand is that symbols are not
> *variables* they are *values*.
Python doesn't have variables. It has names and objects.
> Well, I think a new syntax will promote the use of symbols. And as I
> think they are good practice (much better than meaningless constants)
> they should be promoted. Needless to say that in every language I know
> implementing symbols (or something close to symbols), there is an
> easy-to-use syntax associated.
Why is $closed$ better practice than "closed"?
Why is "closed" a meaningless constant and $closed$ a good symbol?
> Well, one *big* difference between short string and symbols is that the
> identity between short strings are implementation dependant,
Then don't use identity. Who cares whether the state you are testing
against points to the same chunk of memory or not? What possible
difference will that make, except some unnecessary optimization
_possibly_ saving you one millionth of a second at runtime?
> while
> between symbols it has to be in all implementations as you will rely on
> this identity. Then, once more, strings are just one possible
> implementation for symbols and I wouldn't like to tie that much symbols
> to strings.
And ints are another possible implementation for symbols, or classes, or
enums.
obj.state = 42 is not an ideal implementation, because it is not
self-documenting, and self-documenting code is good code. But in some
contexts, it may be the right thing to do:
class MutablePolygon:
"""Define a polygon object that can grow or lose sides."""
def __init__(self, n):
"""Create a new polygon with n sides."""
self.state = n
def grow_side(self):
self.state += 1
def lose_side(self):
self.state -= 1
Compare that with something like this:
class MutablePolygon:
"""Define a polygon object that can grow or lose sides."""
def __init__(self, n):
"""Create a new polygon with n sides."""
if n == 1:
self.state = $one$
elif n == 2:
self.state = $two$
elif n == 3:
self.state = $three$
elif n ...
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Parse file into array
> I was wondering how i could parse the contents of a file into an array.
> the file would look something like this:
>
> gif:image/gif
> html:text/html
> jpg:image/jpeg
Try something like this:
d = {}
for line in open("input.txt").readlines():
ext, mime = line.strip().split(":")
d[ext] = mime
print d
Craig
--
http://mail.python.org/mailman/listinfo/python-list
Re: Proposal for adding symbols within Python
On 2005-11-14, Rocco Moretti <[EMAIL PROTECTED]> wrote: > >> Please, note that I am entirely open for every points on this proposal >> (which I do not dare yet to call PEP). > > I still don't see why you can't just use strings. Same here. In the situations described, I always use strings and have never felt the need for something else: file.state = 'closed' ... if file.state == 'open': whatever elif file.state == 'error': something_else > The only two issues I see you might have with them are a) two > identical strings might not be identical by id(), b) they > aren't local in scope. > > The objection a) is minor. [...] > > The objection b) is a little harder to dismiss. But I'm not > sure if you've completely thought what it means for a symbol > to be "local to a module". I don't think I even understand what the objection is. What is needed is a code fragment that shows how the use of strings is untenable. -- Grant Edwards grante Yow! And furthermore, at my bowling average is visi.comunimpeachable!!! -- http://mail.python.org/mailman/listinfo/python-list
