Re: How to set program name in Python? ($0 in Perl)
Thanks Fredrik for the info. It was not a must-have, I was just curious if it was possible. Thanks, Swaroop www.SwaroopCH.info -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: P(x) 0.2 applet builder
>The tarball can be found at http://www.mired.org/downloads/P(x)-0.2.tar.gz >. Something doesn't work wit the link. LB -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: P(x) 0.2 applet builder
>The tarball can be found at http://www.mired.org/downloads/P(x)-0.2.tar.gz >. Something doesn't work with the link. LB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use generators?
Tom Anderson <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > > Exactly - using a queue means you'll do a breadth-first rather than a > depth-first search, which will involve much less depth of recursion. > See: Thanks for the answers but found a easier (admittedly cheating) way around the problemrun the code on my 64bit Linux system at home. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set program name in Python? ($0 in Perl)
Swaroop C H wrote: > Thanks Fredrik for the info. > > It was not a must-have, I was just curious if it was possible. it should be noted that some systems have a setproctitle() function, but the design of that API comes with its own can of quality worms: http://www.cert.org/advisories/CA-2000-13.html -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you use as symbols for Python ?
"Erik Max Francis" <[EMAIL PROTECTED]> wrote:
> Pierre Barbier de Reuille wrote:
>
> > When you need some symbols in your program, what do you use in Python ?
> >
> > For example, an object get a state. This state is more readable if
> > expressed as a symbols, for example "opened", "closed", "error".
> > Typically, in C or C++, I would use an enum for that:
> > enum OBJECT_STATE
> > {
> > opened, closed, error
> > }
>
> OPENED, CLOSED, ERROR = range(3)
>
> object.state = OPENED
Or if you want something closer to real enumerations, there are several
recipes in the cookbook.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 seems to
be pretty good according to the ratings.
George
--
http://mail.python.org/mailman/listinfo/python-list
[curses]: detecting modifier keys?
Hello I am writing a small app to learn how to use the curses module. I would like to know how I can get "composite" key presses, eg, Control+Q. Currently I am looking at the following code snippet: import curses.wrapper def main(stdscr): x = 0 while True: key = stdscr.getch() stdscr.addstr(x,0 ,str(key)) x += 1 return curses.wrapper(main) If I press Control+Q, no numerical code shows on screen. Some other key combinations work (eg, Control+D, Control+A). Using the Alt key always produces two codes in a row: 27 (I suppose this corresponds to the Alt key itself) and the code for the (unmodified) key (eg, Alt+A produces 27 97, while A+B produces 27 98). The tutorial I am following (http://www.amk.ca/python/howto/curses/) doesn't mention if there is a way to capture all modified key presses. Can anyone help me detect eg Control+Q? Thanks for any guidance, Mack -- http://mail.python.org/mailman/listinfo/python-list
Re: getting results into one variable
[EMAIL PROTECTED] wrote: > a = db.execute(stmt) and then expand variable 'a' > > instead of doing > (a,b) = db.execute(stmt) for return of 2 > (a,b,c) = for return of 3 > (a,b,c,d) for return of 4 What do you intend to do with a, b, c,d ? a = f(x) always work. You can later then do a : if len(a) == 1: single value elif len(a) == 2: double value ... -- http://mail.python.org/mailman/listinfo/python-list
RE: Looking Python script to compare two files
[david]
> I want to compare PDF-PDF files and WORD-WORD files.
OK. Well, that's clear enough.
> It seems that the right way is :
> First, extract text from PDF file or Word file.
> Then, use Difflib to compare these text files.
When you say "it seems that the right way is..." I'll
assume that this way meets your requirements. It
wouldn't be the right way if, for example, you
wanted to treat different header levels as different,
or to consider embedded graphics as significant etc.
> Would you please give me some more information
> about the external diff tools?
Well, I could mention the name of the ones
which I might use (WinMerge and GNU diff),
but I'm sure there are many of then around
the place, and you're far better off doing this:
http://www.google.co.uk/search?q=diff+tools
In case you didn't realise, the "difflib" I
referred to is a Python module from the standard
library:
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import difflib
>>> `difflib`
""
>>>
> There some Python scripts that can extract text
> from PDF or WORD file?
Well, I'm sure there are, but my honest opinion is that,
unless you've got some compelling reason to do this in
Python, you're better off using, say:
+ antiword: http://www.winfield.demon.nl/
+ pdf2text from xpdf: http://www.foolabs.com/xpdf/home.html
If you really wanted to go with Python (for the learning
experience, if nothing else) then the most obvious candidates
are:
+ Word: use the pywin32 modules to automate Word and save the document
as text:
http://pywin32.sf.net/
Something like this (assumes doc called c:\temp\test.doc exists):
import win32com.client
word = win32com.client.gencache.EnsureDispatch ("Word.Application")
doc = word.Documents.Open (FileName="c:/temp/test.doc")
doc.SaveAs (FileName="c:/temp/test2.txt",
FileFormat=win32com.client.constants.wdFormatText)
word.Quit ()
del word
text = open ("c:/temp/test2.txt").read ()
print text
+ PDF: David Boddie's pdftools looks like about the only possibility:
(ducks as a thousand people jump on him and point out the alternatives)
http://www.boddie.org.uk/david/Projects/Python/pdftools/
Something like this might do the business. I'm afraid I've
no idea how to determine where the line-breaks are. This
was the first time I'd used pdftools, and the fact that
I could do this much is a credit to its usability!
from pdftools.pdffile import PDFDocument
from pdftools.pdftext import Text
def contents_to_text (contents):
for item in contents:
if isinstance (item, type ([])):
for i in contents_to_text (item):
yield i
elif isinstance (item, Text):
yield item.text
doc = PDFDocument ("c:/temp/test.pdf")
n_pages = doc.count_pages ()
text = []
for n_page in range (1, n_pages+1):
print "Page", n_page
page = doc.read_page (n_page)
contents = page.read_contents ().contents
text.extend (contents_to_text (contents))
print "".join (text)
TJG
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
--
http://mail.python.org/mailman/listinfo/python-list
Re: ANN: P(x) 0.2 applet builder
LB wrote: >>The tarball can be found at >http://www.mired.org/downloads/P(x)-0.2.tar.gz >. > > > Something doesn't work with the link. > > LB > Copy the whole string up to and including the ".gz" at the end and paste that into your browser's location window. I think it's a bit ill-advised to use parens in a URL, and if you do then they shoud really be represented as %xx escapes. 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
getting results into one variable
hi the database "execute" function returns a list of logical results. Each logical result is a list of row tuples, as explained in the documents. everytime i use it to execute various statements, it returns me, for example ([(0,)], [(0,)], [(0,)]) and sometimes , ([(0,)], [(0,)]) or ([(0,)]) in my call, i give eg (a,b,c) = db.execute(stmt) so that it returns me ([(0,)], [(0,)], [(0,)]) in python, can we do something like a = db.execute(stmt) and then expand variable 'a' instead of doing (a,b) = db.execute(stmt) for return of 2 (a,b,c) = for return of 3 (a,b,c,d) for return of 4 thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
bruno at modulix wrote: > Yves Glodt wrote: > (snip) >> ok I see your point, and python's... >> >> (just FYI, and not to start a flamewar ;-): >> In php, the [] means "append to an array object". > > yes, I know this. > >> If the array does not exist yet, it's created. > > Which is what I don't like. It should crash. > >> [] *is* explicit for >> arrays, > > IIRC, you can also use it to sbscript strings, but I wouldn't bet my > life on this. > >> thus for php it's clear what you want.) > > Nope. You may be in the case where you think the array already exists, > and then you (well, I at least...) would prefer that PHP don't try to > second-guess you... If and when I want to create an object, I tell it. > If I dont tell "create me an array", I don't want one to come in existence. > (snip) >> an "undefined" notice, yes, not a warning... ;-) >> > (snip) >> Ok... I thank you for all the explanations. >> >> It helps me to see more far. I (and will continue to) use php for web, >> and wanna standardize on python for all non-web stuff we are doing, > > You might discover that Python is just great for web programming too !-) Which raises another question... :-) Is there a possibility to bring together apache and python in a way that I can embed python into html? Or even, write a smallish webserver in python (using twisted maybe) whose only purpose is to serve pages and execute the embedded code...? >> so I >> might be a frequent guest on this list... > > You're welcome !-) > And if you're a french speaker, there's also french-speaking mailing > list and newsgroups. Merci pour l'info, I am, but for now the volume of this list is enough for me ... :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Yves Glodt wrote: > Which raises another question... :-) > > Is there a possibility to bring together apache and python in a way that > I can embed python into html? What do you mean ? > > Or even, write a smallish webserver in python (using twisted maybe) > whose only purpose is to serve pages and execute the embedded code...? My favorite is TurboGears, a collection of modules and glue that brings together HTTP server(cherrypy), template(Kid) and SQL object store(SQLObject) that can do serious web developement yet don't need to read a book before starting. If you just need the server, cherrypy is pretty good and simple to start. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to modify code while debugging it without having to stop and then restart debugger
Mike Meyer wrote: > In that case, you're using the wrong IDE. I run the Python interpeter > inside of Emacs. I edit my code in another buffer. In the source code > buffer, I hit M-C-x, and the current version of the function I'm > currently editing gets sent to the interpreter. Reload is pretty easy > as well - C-c RETURN, and the module I'm editing gets reloaded. As far as I understand, the OP wanted to do this while single-stepping through the program he's editing. While this might work as a kind of exploration, it's probably not an optimal development strategy. It might be difficult to predict how the program will run the next time if you manipulate it during execution. I think test-driven development as described e.g. in my EPC presentation last year is more rewarding: http://www.thinkware.se/epc2004test/ (See e.g. the log.html) I suppose different languages and tools foster different styles of work, and I can understand that it's frustrating if a favoured style of development isn't really supported by the Python tools--even though few Python programmers bother about single-stepping through their code. In general, it's clearly non-optimal to run code many magnitudes slower than the nominal speed, and I suspect that few people would care to do that unless the structure of the code they work with was messy. I guess it's a bit like driving an old crappy car, and then getting into a new Toyota. I can understand that it seems strange not to have the trunk filled with tools if you're about to take a long trip, but it's probably a mistake to think that this will make the journey with the Toyota more problematic than the trip would have been with a car that you need to repair every now and then. -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Yves Glodt wrote: > Is there a possibility to bring together apache and python in a way that > I can embed python into html? http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html http://www.modpython.org/live/mod_python-3.2.2b/doc-html/pyapi-psp.html#pyapi-psp -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
[EMAIL PROTECTED] wrote: > Yves Glodt wrote: >> Which raises another question... :-) >> >> Is there a possibility to bring together apache and python in a way that >> I can embed python into html? > What do you mean ? I need this (invalid example-html follows): title of page Hello, today is: %s" % (time.ctime()) ?> Should that not be fairly easy to to, even from scratch, with the httplib module...? The advantage would be that I could write a webinterface for my database and reuse the classes I wrote for the command line app. >> Or even, write a smallish webserver in python (using twisted maybe) >> whose only purpose is to serve pages and execute the embedded code...? > My favorite is TurboGears, a collection of modules and glue that brings > together HTTP server(cherrypy), template(Kid) and SQL object > store(SQLObject) that can do serious web developement yet don't need to > read a book before starting. > > If you just need the server, cherrypy is pretty good and simple to > start. Ok gonna look into that, regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: getting results into one variable
[EMAIL PROTECTED] wrote:
That's a nice email address :-)
> hi
> the database "execute" function returns a list of logical results. Each
> logical result is a list of row tuples, as explained in the documents.
>
In a DB-API-compliant module, execution of the query adn retrieval of
the result(s) are actually sepearated: execute() executesthe query (and
on some, but not all, platforms returns the number of rows in the
result). Then you use either fetchone(), fetchmany() or fetchall() to
retrive the results from the cursor.
> everytime i use it to execute various statements, it returns me, for
> example
> ([(0,)], [(0,)], [(0,)]) and sometimes , ([(0,)], [(0,)]) or ([(0,)])
>
What you seem to be saying here is that you are getting a tuple of
lists, each of which contains a (single-element) tuple. What mopdule are
you using to do this, or is it the result of a gedanken-experiment?
> in my call, i give
> eg (a,b,c) = db.execute(stmt) so that it returns me ([(0,)], [(0,)],
> [(0,)])
>
> in python, can we do something like
>
> a = db.execute(stmt) and then expand variable 'a'
>
> instead of doing
> (a,b) = db.execute(stmt) for return of 2
> (a,b,c) = for return of 3
> (a,b,c,d) for return of 4
>
> thanks
>
Yes. Here's a pracical example using the database that generates
www.holdenweb.com:
>>> import mx.ODBC.Windows as db
>>> conn = db.connect("comsite")
>>> curs = conn.cursor()
>>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
>>>
[Note that this returns None for this particular combination of database
module and backend].
>>> rows = curs.fetchall()
>>> rows
[(1, 'Explore Holden Web', 'hd_explore'), (2, 'Student Links',
'hd_students'), (3, 'Other Stuff', 'hd_otherstuff'), (4, 'Recent Python
News', 'hd_pythonnews'),(5, 'Python Links', 'hd_pythonlinks'), (6,
'Python Reading', 'hd_pythonreading'), (7, 'Python Modules',
'hd_pythonreviews')]
>>>
You see here that fetchall() returns a list of tuples - each tuple being
a rows from the query result. It's normal to iterate over this list, and
one way to do this is:
>>> for row in rows:
... print row
...
(1, 'Explore Holden Web', 'hd_explore')
(2, 'Student Links', 'hd_students')
(3, 'Other Stuff', 'hd_otherstuff')
(4, 'Recent Python News', 'hd_pythonnews')
(5, 'Python Links', 'hd_pythonlinks')
(6, 'Python Reading', 'hd_pythonreading')
(7, 'Python Modules', 'hd_pythonreviews')
>>>
Of course you can unpack each row if you want to refer to the columns
individually:
>>> for row in rows:
... id, title, path = row
... print title, id
...
Explore Holden Web 1
Student Links 2
Other Stuff 3
Recent Python News 4
Python Links 5
Python Reading 6
Python Modules 7
>>>
You can save yourself some time by doing the unpacking right in the for
loop:
>>> for id, title, path in rows:
... print id, title
...
1 Explore Holden Web
2 Student Links
3 Other Stuff
4 Recent Python News
5 Python Links
6 Python Reading
7 Python Modules
>>>
Finally, if you only want to use the result once you don't even need to
save it:
>>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
>>> for id, ttl, pth in curs.fetchall():
... print pth, ":", ttl
...
hd_explore : Explore Holden Web
hd_students : Student Links
hd_otherstuff : Other Stuff
hd_pythonnews : Recent Python News
hd_pythonlinks : Python Links
hd_pythonreading : Python Reading
hd_pythonreviews : Python Modules
>>>
You can use fetchone() to return each row as a tuple if that suits you
better, but it may be less efficient because it can lead to inefficient
communication between the database server and the client, particularly
if the result set is large.
>>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
>>> curs.fetchone()
(1, 'Explore Holden Web', 'hd_explore')
>>>
So of course you can unpack the tuple as well:
>>> id, ttl, pth = curs.fetchone()
>>> print "Title:", ttl, "path:", pth, "id:", id
Title: Student Links path: hd_students id: 2
>>>
If the result sets are too large to comfortably hold in memory you can
fetch them N at a time with fetchmany(N), repeating until there's
nothing left to read. And so on, but I hope this gives you the idea.
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: Using python for writing models: How to run models in restricted python mode?
vinjvinj wrote: > Unfortunately this in not an options since all the processes share > objects in memory which are about 1gig for each node. Having a copy of > this in each user process is just not an options. I think I'm going to > use RestrictedPython from zope3 svn which should take care of 70-80 % > of the problem. I wonder whether it is possible to fork() the program, restricting the memory usuage for the forked program. In most unix variants, forked programs share memory until that memory is written to. Of course this may not be useful if there's data going back and forth all the time. -- Jeremy Sanders http://www.jeremysanders.net/ -- http://mail.python.org/mailman/listinfo/python-list
output question 1
I wrote the following code and got the output:a 13 0Noneb 81 3Nonec 8 2Noned 9 2Nonee 1 1Nonewhere are those 'none' from? and how can I remove them? class Point: def __init__(self,x,y,name): self.x = x self.y = y self.name = name def summary(self): print self.name,self.x,self.yif __name__ == '__main__': from string import letters m = 13,81,8,9,1 n = 0,3,2,2,1 q=len(x) points = [ Point(m[i],n[i],letters[i]) for i in range(q) ] i=0 while i print points[i].summary() i=i+1 -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
[EMAIL PROTECTED] wrote: > George Sakkis wrote: > >list(takewhile(p, xrange(1000))) >> >>[0, 1] > > thanks. that is what I am doing now, in a more generic form : > > takewhile(p, (x for x in xrange(1))) How does a useless generator expression make it more generic? -- http://mail.python.org/mailman/listinfo/python-list
Re: output question 1
On 10/11/05, leewang kim <[EMAIL PROTECTED]> wrote: > I wrote the following code and got the output: > a 13 0 > None > b 81 3 (snip) > where are those 'none' from? and how can I remove them? > > class Point: > def __init__(self,x,y,name): > self.x = x > self.y = y > self.name = name > def summary(self): > print self.name,self.x,self.y Here you print your self.name value etc. > if __name__ == '__main__': > from string import letters > m = 13,81,8,9,1 > n = 0,3,2,2,1 > q=len(x) > points = [ Point(m[i],n[i],letters[i]) for i in range(q) ] > i=0 > while i print points[i].summary() Here you print whatever is returned from the summary() method. Since that method doesn't return anything explicitly, None is returned by default, and you are printing that. > i=i+1 One simple fix - change the summary method to returnt the values rather than print them - replace 'print' with 'return' in that method. Another would be not to print the returned values - remove 'print' from your while loop. -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Yves Glodt wrote: > I need this (invalid example-html follows): > > > title of page > > > import time > > print "Hello, today is: %s" % (time.ctime()) > > ?> > > Cheetah template ? But I like Kid better as I don't want python in HTML, Kid IMO strikes the balance between python feature and XHTML so the template is still readable by any XHTML editors. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
Leif K-Brooks wrote: > [EMAIL PROTECTED] wrote: > > George Sakkis wrote: > > > >list(takewhile(p, xrange(1000))) > >> > >>[0, 1] > > > > thanks. that is what I am doing now, in a more generic form : > > > > takewhile(p, (x for x in xrange(1))) > > How does a useless generator expression make it more generic? xrange is only picked as an example. I may be newbie on python but not that dumb if all I want is a list of integer(sorted) that meets certain criteria. takewhile(p, (x for x in some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs))) -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > > How does a useless generator expression make it more generic? > > xrange is only picked as an example. I may be newbie on python but not > that dumb if all I want is a list of integer(sorted) that meets certain > criteria. > > takewhile(p, (x for x in > some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs))) The generator expression is useless in that example too. some_function... has to return an iterator, not a list, if you don't want it to use a pile of memory. And if it returns an iterator, the generator expression is redundant. You can pass the iterator directly to takewhile. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
Paul Rubin wrote: > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > > > How does a useless generator expression make it more generic? > > > > xrange is only picked as an example. I may be newbie on python but not > > that dumb if all I want is a list of integer(sorted) that meets certain > > criteria. > > > > takewhile(p, (x for x in > > some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs))) > > The generator expression is useless in that example too. some_function... > has to return an iterator, not a list, if you don't want it to use a > pile of memory. And if it returns an iterator, the generator > expression is redundant. You can pass the iterator directly to > takewhile. oops, my original code is much more complex than that. it is not the pythonic way of doing things but that is what I like. Try again: takewhile(p, ((exp1(x), exp2(y)) for (x, y) in f())) -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
[EMAIL PROTECTED] wrote: > Leif K-Brooks wrote: > >>[EMAIL PROTECTED] wrote: >> >>>thanks. that is what I am doing now, in a more generic form : >>> >>>takewhile(p, (x for x in xrange(1))) >> >>How does a useless generator expression make it more generic? > > xrange is only picked as an example. I may be newbie on python but not > that dumb if all I want is a list of integer(sorted) that meets certain > criteria. > > takewhile(p, (x for x in > some_function_that_could_potentially_generate_a_long_list_of_elements_but_first_element_that_meets_the_condition_can_come_fast(*args,**kwargs))) Wrapping a function in a generator expression doesn't magically make it lazily evaluated. The whole list has to be generated and returned; using a generator expression instead of a list comprehension just means that it doesn't need to be copied in memory. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
I use "list" in the name in "english"/general sense(say a list in haskell is lazily evaluated), it could be a list or it could be a lazily evaluated iterable. The original post is really just about "when" or may be "until" syntax that makes it a bit shorter to read and hopefuly easier to understand. Leif K-Brooks wrote: > Wrapping a function in a generator expression doesn't magically make it > lazily evaluated. The whole list has to be generated and returned; > using a generator expression instead of a list comprehension just means > that it doesn't need to be copied in memory. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to modify code while debugging it without having to stop and then restart debugger
I used Visual Basic a long time in the past and I know what you mean. The ability to step through code line by line was very useful in a language where you often didn't know what was happening. I particularly loved the ability to hover the mouse over any variable or expression and see the value at that point in the code. As a learning tool it would be excellent for Python, as would the ability to step through the code, hit an error, step back one line, change the line that caused the error and then continue stepping forward again. However I have to say that since using Python, I haven't needed these features as much (though I still would have liked to have them available). Ed On 08/11/05, python <[EMAIL PROTECTED]> wrote: > hello and thanks for reading this, > > i have been a dos/windows user using some form of the basic language for 30 > years now. > i own and run a small programming company and there is one feature that keeps > me in the windows/basic world. > > while i will agree that it has not evolved well, it does have one awesome > feature that i have yet to see replicated in > any linux product that i know about so far. > > > i am a long time windows user and have had a great way to learn new api. > to write some code and then run it. > if there is an error, the debugger will load. > then i can figure out what the eror is, just touch up the ocde and continue > to run the code. > i do not have to stop the code, modify the code, rerun the code. > often an error will only happen after a complex set of conditions and not > have to completely stop the app is a fantastic > way to debug. > > there are several applications that can do this. > in fact, the free version of the visual studio 2005, which is free, have this > ability. > > so how can i use python to debug code and change that code without having to > restart the code. > > thanks so much, > dave > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking Python script to compare two files
Tim Golden wrote: > + PDF: David Boddie's pdftools looks like about the only possibility: > (ducks as a thousand people jump on him and point out the alternatives) I might as well do that! Here are a couple of alternatives: http://www.sourceforge.net/projects/pdfplayground http://www.adaptive-enterprises.com.au/~d/software/pdffile/ Both of these are arguably more "Pythonic" than my solution, and the first is also able to write out modified files. Cameron Laird also maintains a page about PDF conversion tools: http://phaseit.net/claird/comp.text.pdf/PDF_converters.html > http://www.boddie.org.uk/david/Projects/Python/pdftools/ > > Something like this might do the business. I'm afraid I've > no idea how to determine where the line-breaks are. This > was the first time I'd used pdftools, and the fact that > I could do this much is a credit to its usability! Thanks for the compliment! The read_text method in the PDFContents class also lets you extract text from a given page in a document, but you have to remember that text in PDF files isn't always composed as a series of lines or paragraphs, and often doesn't even contain whitespace characters. David -- http://mail.python.org/mailman/listinfo/python-list
Script to export MySQL tables to csv
To anyone that can help I have 2 MySQL databases that contain large amounts of tables. I need to be able to compare the data in the tables with older/newer versions of the tables. I figured the easiest way would be to get the info in csv format and then run a comparison. I can get all the data using MySQL front, but this has to be done tabe-by-table, and is too time consuming. I am new to Python and also new to programming. Can anyone please help. Thanks Jandre -- http://mail.python.org/mailman/listinfo/python-list
iterate over class variables
Hello list, I need to iterate over a class and get all her variable names and values, e.g. considering this example: class testclass: var1 = 'ab' var2 = 'cd' var3 = 'ef' test = testclass() Then I wanna do sonmething like this: for name,value in test: print name print value fails with of course with: "TypeError: iteration over non-sequence" How can I do that? regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote: > Hello list, > > I need to iterate over a class and get all her variable names and > values, e.g. considering this example: > > > class testclass: > var1 = 'ab' > var2 = 'cd' > var3 = 'ef' > > test = testclass() > > > > Then I wanna do sonmething like this: > > for name,value in test: > print name > print value > > fails with of course with: > "TypeError: iteration over non-sequence" > > > How can I do that? sorry for selfreplying, but I found a solution: for key in dir(test): if '__' not in key: value = getattr(test,key) print key, value Does anything speak about this? Is there a better-performing way to do this? > regards, > Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote: > Yves Glodt wrote: >> Hello list, >> >> I need to iterate over a class and get all her variable names and >> values, e.g. considering this example: >> >> >> class testclass: >> var1 = 'ab' >> var2 = 'cd' >> var3 = 'ef' >> >> test = testclass() >> >> >> >> Then I wanna do sonmething like this: >> >> for name,value in test: >> print name >> print value >> >> fails with of course with: >> "TypeError: iteration over non-sequence" >> >> >> How can I do that? > > sorry for selfreplying, but I found a solution: > > for key in dir(test): > if '__' not in key: > value = getattr(test,key) > print key, value > > Does anything speak about this? s/about/against /me: s/more sleep/less party > Is there a better-performing way to do this? > > >> regards, >> Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
[EMAIL PROTECTED] wrote: > Alex Martelli wrote: > >>This becomes a valid list comprehension by writing 'if' instead of >>'when'. > > valid, yes. efficient, I am not sure. > > [ x for x in xrange(1000) if p(x) ] > > means I need to go through the whole range even if p = lambda x: x < 2. If you're looking for efficient, not to mention readable, then this is obviously far superior: [x for x in xrange(2)] or even [0, 1] Yes, I know yours was a contrived example, but there's a time when contrived examples stop showing us anything useful. Do you have a real use case, where you think that the list comprehension form is more readable or somehow better, and yet you are concerned about its failure to magically optimize your case? (I say "readable or somehow better" since you stated in another post "I just try to use list/generator expression when possible" but you didn't explain your reason for doing so. I assume you have some reason other than arbitrary whim.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Hi!
You can iterate over the internal dictionary:
>>> class Test:
... def __init__(self):
... self.x = 5
... self.y = 6
... self.z = "Hallo"
...
>>> x = Test()
>>> print x.__dict__
{'y': 6, 'x': 5, 'z': 'Hallo'}
>>> for key, value in x.__dict__.items():
... print key
... print value
...
y
6
x
5
z
Hallo
>>>
Consider using iteritems() instead of items() when you have a loop.
Hope that helps :)
Daniel
--
http://mail.python.org/mailman/listinfo/python-list
Re: gmpy 1.01 rc near... anybody wanna test>
I tested gmpy cvs as of now on Debian/testing/x86 with python2.3. It compiled perfectly, ran all of its unit tests and also all my test programs - Well done! My test program seemed to run at the same speed with both versions (not suprising really since both are using the same libgmp.so on the system). Thanks and look forward to the release Nick -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
The Eternal Squire wrote: > > 1) The decrypted modules should only reside in RAM, never in virtual > memory. Those RAM locations should be rendered inaccessible to Python > code. I'm starting to understand why FOSS developers are said to be productive above the average: they don't have to mess their brains with stuff like that. > snip > > IMHO, I have never encountered a dishonest developer or business owner > who at the same time possessed anything remotely resembling a rational > business model. > Ah, what was the name of that company in ... mh, was it Redmond? Once you got the model of free and open source software you can't but shake your head at obfuscating people treating their users as enemies. Intellectual property suffers in most cases from a significant lack of the intellectual part. -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote:
> Yves Glodt wrote:
>
>> Hello list,
>>
>> I need to iterate over a class and get all her variable names and
>> values, e.g. considering this example:
>>
>>
>> class testclass:
>> var1 = 'ab'
>> var2 = 'cd'
>> var3 = 'ef'
Take care, these are *class* variables, not instance variables.
>> test = testclass()
>>
>> Then I wanna do sonmething like this:
>>
>> for name,value in test:
>> print name
>> print value
>>
(snip)
>
> sorry for selfreplying, but I found a solution:
>
> for key in dir(test):
> if '__' not in key:
> value = getattr(test,key)
> print key, value
>
> Does anything speak about this?
1/ dir() doesn't necessary returns all the attributes of an object:
"""
dir(...)
dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
"""
But I don't think this is a problem here.
2/ everything being an object, dir() also returns methods (a method
being a - callable - attribute of the object's class).
If you're only interested in data attributes, you may want to try this:
for key in dir(test):
if not key.startswith('__'):
value = getattr(test,key)
if not callable(value):
print key, value
You can also check inspect.getmember()
--
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: Script to export MySQL tables to csv
Jandre wrote: > To anyone that can help > > I have 2 MySQL databases that contain large amounts of tables. I need > to be able to compare the data in the tables with older/newer versions > of the tables. I figured the easiest way would be to get the info in > csv format and then run a comparison. I can get all the data using > MySQL front, but this has to be done tabe-by-table, and is too time > consuming. > > I am new to Python and also new to programming. > Can anyone please help. > Well, it might be a rather extending first programming project, but the delightful news is that you can access MySQL databases directly from Python! What sort of differences will exist? Does a row's content always stay the same once it's been written to a table, or are rows updated as well? Basically if you can say what type of differences you want to see it should be possible to do just what you want. If you haven't already downloaded and installed the MySQLdb module for Python you'll probably need that. Are you running on Windows or a Unix-like system (you'll need to get the appropriate installer from http://sourceforge.net/projects/mysql-python If you have any trouble installing it, get back on this list and someone will help. You're going to have *such* fun! 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: getting results into one variable
[EMAIL PROTECTED] wrote:
> hi
(snip)
>
> in python, can we do something like
>
> a = db.execute(stmt) and then expand variable 'a'
> instead of doing
> (a,b) = db.execute(stmt) for return of 2
> (a,b,c) = for return of 3
> (a,b,c,d) for return of 4
Did you try ?-) Took me about 30'':
>>> def fun(): return 1,2,3
...
>>> a = fun()
>>> a
(1, 2, 3)
>>> def fun2(): return 1,2,3,4,8,9
...
>>> b = fun2()
>>> b
(1, 2, 3, 4, 8, 9)
>>>
It of course works since a function *always* returns a *single* value.
Now this value *can* be a sequence, and this sequence *can* be unpacked
- directly at the return of the function, or latter:
>>> a = fun()
>>> a
(1, 2, 3)
>>> v1, v2, v3 = a
>>> v1
1
>>> v2
2
>>> v3
3
>>>
HTH
--
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: Python as a HTTP Client
``urllib2`` is the standard library module you need. I've written a guide to using it (although it's very easy - but some attributes of the errors it can raise aren't documented) : http://www.voidspace.org.uk/python/articles/urllib2.shtml All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking Python script to compare two files
Thanks for the quick replies! So if I want to use these tools: antiword,pdf2text, can I pack these tools and python script into a windows EXE file? I know there is open source tool which can pack python script and libs and generate the windows EXE file. Yes, this approach can't handle the pictures in the PDF/WORD file. There is a way to play around it? maybe it's very hard. Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
Peter Hansen wrote: > (I say "readable or somehow better" since you stated in another post "I > just try to use list/generator expression when possible" but you didn't > explain your reason for doing so. I assume you have some reason other > than arbitrary whim.) The reason is simple: I found it easier to read for me and using list/generator expression helped me uncover a number of subtle bugs comparing with an imperative approach. on its own : takewhile(lambda x: condition(x), some_generator) is not very much difference than(well, still more things to type) (x for x in some_generator when condition(x)) but when I have a number of them in the same expression, the takewhile/dropwhile becomes to add up. -- http://mail.python.org/mailman/listinfo/python-list
Python as a HTTP Client
I am writing a program that has to do some lightweight HTTP communication with a webserver on the internet. I haven't checked, but I'm sure I could do something lowlevel like opening a socket myself and then send/receive everything myself on this (how do I do that?), but I'd bet that Python have some module which is more high level. Something that would just let me connect using an URL, send a few GETs, and receive the answer as a string/file etc. Does this exist, and where can I read about it? /David -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote:
> I need to iterate over a class and get all her variable names and
> values, e.g. considering this example:
>
> class testclass:
> var1 = 'ab'
> var2 = 'cd'
> var3 = 'ef'
Is the following of any help to you?
>>> class testclass:
... a = 'a'
...
>>> dir(testclass)
['__doc__', '__module__', 'a']
>>> testclass.__dict__
{'a': 'a', '__module__': '__main__', '__doc__': None}
>>> import inspect
>>> inspect.classify_class_attrs(testclass)
[('__doc__', 'data', , None),
('__module
__', 'data', , '__main__'),
('a', 'data'
, , 'a')]
There are other methods in "inspect" which could help you.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list
Problem connecting to SQL Server2000 using SQLRelay in Python
Hi, I want to connect to SQL Server 2000 at remote site in python using SQLRelay at local machine. When i run my query, the following message comes: Debugging to:/usr/local/firstworks/var/sqlrelay/debug/sqlr-listener.11639 and then no result is displayed. The above file contains: 11/10/2005 15:49:41 IST listener [11639] : listener-based authentication succeeded 11/10/2005 15:49:41 IST listener [11639] : incrementing session count... 11/10/2005 15:49:41 IST listener [11639] : 1 11/10/2005 15:49:41 IST listener [11639] : done incrementing session count 11/10/2005 15:49:41 IST listener [11639] : getting a connection... I have also tried to run the query using sqlrsh -id ID command. Then also no result is displayed. I tried with both PySQLRClient and PySQLRDB in SQLRelay to connect to SQL Server in Python Program. Please guide me. Regards, Bharat Nayak -- http://mail.python.org/mailman/listinfo/python-list
Re: Python as a HTTP Client
"[EMAIL PROTECTED]" wrote: >I am writing a program that has to do some lightweight HTTP > communication with a webserver on the internet. I haven't checked, but > I'm sure I could do something lowlevel like opening a socket myself and > then send/receive everything myself on this (how do I do that?), but > I'd bet that Python have some module which is more high level. before proceeding, could you PLEASE spend a few minutes browsing the following chapters http://docs.python.org/tut/node12.html http://docs.python.org/tut/node13.html as well as this page: http://docs.python.org/lib/ -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you use as symbols for Python ?
Pierre Barbier de Reuille wrote:
> When you need some symbols in your program, what do you use in Python ?
>
> For example, an object get a state. This state is more readable if
> expressed as a symbols, for example "opened", "closed", "error".
> Typically, in C or C++, I would use an enum for that:
> enum OBJECT_STATE
> {
> opened, closed, error
> }
>
> In CAML or Haskell I would use the union types:
>
> type ObjectState = Opened | Closed | Error
>
> In Ruby I would use the symbols :
>
> object.state = :opened
> object.state = :closed
> object.state = :error
>
> ... but I don't know what to use in Python !
Depends on the job... If I need to do bitmask operations, I'll use
integer flags. If I want the symbol to be human-readable, I'll use
strings. But everything in Python being an object, you can use whatever
seems appropriate
Since we're in a 'state' exemple, here's a possible state pattern
implementation:
class MyObject(object):
def __init__(self, name):
self.name = name
self.__class__ = ClosedState
state = property(fget=lambda self: self.__class__)
def open(self, arg):
if arg == 1:
self.__class__ = OpenedState
else:
self.__class__ = ErrorState
def close(self):
self.__class__ = ClosedState
class OpenedState(MyObject):pass
class ClosedState(MyObject):pass
class ErrorState(MyObject):pass
m = MyObject('toto')
assert m.state is ClosedState
m.open(1)
assert m.state is OpenedState
m.close()
assert m.state is ClosedState
m.open(2)
assert m.state is ErrorState
I made states 'dummy' objects, but you could make this a real state
pattern implementation by defining default methods in the base class and
overriding appropriate methods in the 'state' subclasses.
HTH
--
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
Python as a HTTP Client
I am writing a program that has to do some lightweight HTTP communication with a webserver on the internet. I haven't checked, but I'm sure I could do something lowlevel like opening a socket myself and then send/receive everything myself on this (how do I do that?), but I'd bet that Python have some module which is more high level. Something that would just let me connect using an URL, send a few GETs, and receive the answer as a string/file etc. Does this exist, and where can I read about it? /David -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you use as symbols for Python ?
Op 2005-11-10, Pierre Barbier de Reuille schreef <[EMAIL PROTECTED]>:
> When you need some symbols in your program, what do you use in Python ?
>
> For example, an object get a state. This state is more readable if
> expressed as a symbols, for example "opened", "closed", "error".
> Typically, in C or C++, I would use an enum for that:
> enum OBJECT_STATE
> {
> opened, closed, error
> }
>
> In CAML or Haskell I would use the union types:
>
> type ObjectState = Opened | Closed | Error
>
> In Ruby I would use the symbols :
>
> object.state = :opened
> object.state = :closed
> object.state = :error
>
> ... but I don't know what to use in Python !
I sometimes just use a class per symbol
class Opened: pass
class Closed: pass
class Error: pass
--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Re: ANN: P(x) 0.2 applet builder
Sorry, I can only obtain a windows with caption: "VRML Console" and text: [ Info] Unable to open input file: http://www.mired.org/downloads/P(x)-0.2.tar.gz [ Info] Compilation error: Unrecognized header string ? LB -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ??
< snip> > I assume the way the computer is going to guess is by trying some > number, and you respond either that it's guessed right, or to go lower, > or to go higher. Yes, that is correct. > > In that case, think of "bisection". Originally, all the computer knows > is that the number is in some range, say 0 to 100. It can then guess > the midpoint, 50. If it's right, yay! Otherwise: if it's told to go > lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in > each case the range was just halved (actually, a bit more than halved). Thank you, I thought that might be the case. So, I will have to settle down and try to write some pseudo-code first. I hope to be back. Norman -- http://mail.python.org/mailman/listinfo/python-list
Re: web interface
I have been looking for an example like this for a while, so thanks to J.P. Calderone. Unfortunately, this kind of solution is pretty much browser-dependent. For instance, I tried it and it worked with Firefox, but not with MSIE 5.01 and it will not work with any browser if you disable Javascript. So, I don't think there is a real solution for this kind of problem as of today (I would love to be wrong, though). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: how to modify code while debugging it without having to stop and then restart debugger
On Wed, 09 Nov 2005 18:04:02 +, Steve Holden wrote:
>>>how can such a dynamic language like python not be able to do this.
>>
>>
>> Do you try to ignore the syntax and grammar of the programming language
>> you are coding in too, or only English?
>>
> That's rather unkind. I'd judge we are plainly dealing with someone who
> is working hard to express questions in a foreign language. Funny,
> perhaps, but definitely unkind. Take two demerits and smack yourself on
> the wrist.
Your judgement is very different from mine. The poster's name is Dave, and
to my eyes his writing is very good English, albeit with lots of typos,
except for refusal to use capital letters where required ("Oh, I'll just
leave out braces in C because I feel like it") and deliberately incorrect
use of punctuation ("I don't feel like using '.' for attribute references,
I'll use '?' instead").
Programmers are supposed to be precise in their use of language --
failure to write what you intend is a bug in natural language just as
much as it is in C, VB, Lisp or Python. It just aggravates me to see
supposedly precise and accurate programmers *deliberately* breaking syntax
and grammar of natural language for no good reason.
(It is, of course, possible to break the rules of natural language for
good reason. Good writers do it all the time.)
there are several applications that can do this.
in fact, the free version of the visual studio 2005, which is free, have
this ability.
>>
>>
>> Just out of curiosity, how much is the free version of Visual Studio 2005?
>>
>>
> I'm not positive, but i think they're currently giving it away.
Hmmm... this free version they give away... how much are they giving it
away for?
*wink* (we could keep this up all day...)
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Script to export MySQL tables to csv
Jandre wrote: > To anyone that can help > > I have 2 MySQL databases that contain large amounts of tables. I need > to be able to compare the data in the tables with older/newer versions > of the tables. I figured the easiest way would be to get the info in > csv format and then run a comparison. I can get all the data using > MySQL front, but this has to be done tabe-by-table, and is too time > consuming. > > I am new to Python and also new to programming. > Can anyone please help. > > Thanks > Jandre > I recently had a need to do exactly what you are describing and found this product to fit the bill nicely. http://www.apexsql.com/sql_tools_diff.asp Sometimes I find it better to buy than to write ;-). Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
On Wed, 09 Nov 2005 15:08:15 -0500, Yu-Xi Lim wrote: > As you said, if you have some novel features, you will need obfuscation. > Copyright doesn't protect the process and patents may take a while. In > the meanwhile, good obfuscation is reasonable protection, imho. > > But I think you failed to note that it may not be a novel feature or > useful functionality. In fact, it might be the opposite: a function the > users want removed. A typical example would be a shareware registration > or nag screen. When the users have to start paying, they might then feel > inclied to "rip off the code", or in this case, rip out the code. Which leads to the important counter-question. Since there is a Python obfuscator, is there a Python un-obfuscator? I am aware that not all obfuscations can be reversed, but some can. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Confusion about __call__ and attribute lookup
I am learning about metaclasses and there is something that confuses me. I understand that if I define a __call__ method for a class, then instances of the class become callable using function syntax: >>> class Foo(object): ... def __call__(self): ... print 'Called Foo' ... >>> f=Foo() >>> f() Called Foo To create a class instance, you call the class. This made me think that the class' class must define __call__, and indeed it does, and calling it as an unbound method also creates a class instance: >>> dir(type) [..., '__call__', ...] >>> f=type.__call__(Foo) >>> f <__main__.Foo object at 0x00A35EB0> But why doesn't Foo.__call__ shadow type.__call__? Normally an instance attribute takes precedence over a class attribute. Is it something special about how function call syntax is handled internally, or do all special methods work this way, or is there something else going on? PS Is there any place in the standard Python docs where the details of attribute lookup are spelled out? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: web interface
On 10 Nov 2005 05:31:29 -0800, Michele Simionato <[EMAIL PROTECTED]> wrote: > > >I have been looking for an example like this for a while, so thanks to >J.P. Calderone. >Unfortunately, this kind of solution is pretty much browser-dependent. >For instance, >I tried it and it worked with Firefox, but not with MSIE 5.01 and it >will not work with any >browser if you disable Javascript. So, I don't think there is a real >solution >for this kind of problem as of today (I would love to be wrong, >though). > It depends on JavaScript, yes. It'll probably work with IE in an upcoming release, though. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
python + ODBC + Oracle + MySQL - money
Hi, I'm fairly new to Python so please pardon any dumbness on my part. I plan to write an app in Python that will run on Linux and would need to connect to Oracle and MySQL. I could use MySQLdb for MySQL and cx_oracle for Oracle, but 2 different APIs in the same app is kind of painful. So I have unixODBC that gives me ODBC on Linux. The best ODBC access for Python I know is mxODBC. But that is not free for commercial use. Could someone tell me if there are other choices I have? Thanks.. -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
bruno at modulix wrote:
> Yves Glodt wrote:
>> Yves Glodt wrote:
>>
>>> Hello list,
>>>
>>> I need to iterate over a class and get all her variable names and
>>> values, e.g. considering this example:
>>>
>>>
>>> class testclass:
>>> var1 = 'ab'
>>> var2 = 'cd'
>>> var3 = 'ef'
>
> Take care, these are *class* variables, not instance variables.
>
>>> test = testclass()
>>>
>>> Then I wanna do sonmething like this:
>>>
>>> for name,value in test:
>>> print name
>>> print value
>>>
> (snip)
>> sorry for selfreplying, but I found a solution:
>>
>> for key in dir(test):
>> if '__' not in key:
>> value = getattr(test,key)
>> print key, value
>>
>> Does anything speak about this?
>
> 1/ dir() doesn't necessary returns all the attributes of an object:
> """
> dir(...)
> dir([object]) -> list of strings
>
> Return an alphabetized list of names comprising (some of) the attributes
> of the given object, and of attributes reachable from it:
> """
>
> But I don't think this is a problem here.
>
> 2/ everything being an object, dir() also returns methods (a method
> being a - callable - attribute of the object's class).
>
> If you're only interested in data attributes, you may want to try this:
>
> for key in dir(test):
> if not key.startswith('__'):
> value = getattr(test,key)
> if not callable(value):
> print key, value
This serves me well so far, thanks to you, Peter and Daniel for the
suggestions!
Yves (still amazed of the responsiveness of this list :-)
> You can also check inspect.getmember()
--
http://mail.python.org/mailman/listinfo/python-list
Python-based Document Management System?
Hi, I'm looking for a Python-based DMS, but I don't know any. The following points are relevant: - suitable for 10..100 users with more than 1 documents - documents are mostly proprietary formats: MS Word, MS Excel, MS PowerPoint, but maybe also: PDF, HTML, DocBook, ... - typical DMS features: access control, archive older versions, search/query, document hierarchy, web frontend I have heard of DocMGR, MyDMS, and OWL, which are all PHP-based. A Python-based DMS would allow me to add new features easily. Thanks for hints! Cheers, WB (please CC me) -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Nov 9)
QOTW: "The lesson for me is to spend much less time on Python discussion and much more on unfinished projects. So even if I never use the new syntax, I will have gained something ;-)" - Terry Reedy "In short, this group is a broad church, and those readers with brains the size of planets should remember that they are just as much in a minority as the readers who appear on the list for the first time this week. The vast majority are here to learn and grow, and I think that's the sort of behaviour we should be encouraging." -- Steve Holden The reasons you like Python probably are put into words in at least one of these threads: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b41ca4ba29b84471/ Tim Golden, ... help make the most of Excel: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bcd29beecba33c98/ Spread your expertise around, face-to-face, just outside Dallas. http://groups.google.com/group/comp.lang.python.announce/msg/b7f6f62db23e1265 Program generators date from the Carboniferous. Or the age of Cobol. Well, from *some* time in the past, as least. . . . Except that they keep turning up nowadays, in such guises as refinable templating systems: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8962903fc5717bfa/ While generators (like program generators, recursion, and many other powerful concepts) are great, they're *best* less often than is commonly realized: http://groups.google.com/group/comp.lang.python/browse_thread/thread/af6560b12bc719a6/ Deprecation of functionalism isn't an idle exercise. The point is not just to *say*, yes, we can live without lambda; Fredrik Lundh, for example, embraces New Python Style's willingness to define and redefine function objects, exactly in contrast to older lambda-oriented codings: http://mail.python.org/pipermail/tkinter-discuss/2005-November/000553.html Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/
Re: Python obfuscation
On Thu, 10 Nov 2005 13:35:00 +0100, yepp wrote: > The Eternal Squire wrote: > >> >> 1) The decrypted modules should only reside in RAM, never in virtual >> memory. Those RAM locations should be rendered inaccessible to Python >> code. > > I'm starting to understand why FOSS developers are said to be productive > above the average: they don't have to mess their brains with stuff like > that. That's not *quite* true. There are FOSS programs that actually do care about security. For instance, if you are encrypting data, you don't want the memory containing the plaintext to be swapped to your swap partition, where raw disk tools can recover it. But as a general rule, you're right. If you, the developer, don't have to think of your users as the enemy, you'd be amazed the amount of make-work you don't have to do. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion about __call__ and attribute lookup
Kent Johnson wrote: > But why doesn't Foo.__call__ shadow type.__call__? Normally an instance > attribute takes precedence over a class attribute. Is it something > special about how function call syntax is handled internally, or do all > special methods work this way, or is there something else going on? New-style classes look up special methods on the class, not on the instance: >>> class Foo(object): ... def __invert__(self): ... return 'foo' ... >>> x = Foo() >>> ~x 'foo' >>> x.__invert__ = 123 >>> x.__invert__() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> ~x # equivalent to type(x).__invert__() 'foo' -- http://mail.python.org/mailman/listinfo/python-list
Re: python + ODBC + Oracle + MySQL - money
Well having two different Databases from one app could be painful, but I think that using Python and a "Divide and Conquer" aproach might be your best GPL way of handling this. Start up a set of python Classes that just does the access to the MySQL database. Get these working, just concentrate on building the Database accesses you will need for your app, and give the functions sensible, and relatively verbose, names. Next take step two, doing that same thing (In a different directory, with a slightly different naming convention for classes maybe), but for the Oracle Database, and test that out and get that up and running. Now you have two apps, one for MySQL and one for Oracle. Now the step that you might not catch on about until you have more expereience using Python. Because of the very slick and intelligent way that Python handles naming and operator overloading you just need to write another set of classes that is you application. This application can just make use of the other two DB apps you just created by calling those classes (Hence why I suggested careful naming, and following some sort of convention for the naming). This will eventually translate into your app, remember you can do all the fancy User Interface work and Program Logic work in the third set of classes (The APP classes). I'm not sure how complicated the app is, but this sounds like a reasonalbe high level aproach. And if you boss asks questions about this methodology just tell him/her know that you got recommend this approach by a Graduate of the University of Toronto with a degree in Computre Engineering. :-P So, hope this helps, feel free to ask more questions, hopefully others will have some more ideas to share. My two cents, Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ??
On Thu, 10 Nov 2005 13:30:05 +, Norman Silverstone wrote:
>> In that case, think of "bisection". Originally, all the computer knows
>> is that the number is in some range, say 0 to 100. It can then guess
>> the midpoint, 50. If it's right, yay! Otherwise: if it's told to go
>> lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in
>> each case the range was just halved (actually, a bit more than halved).
>
> Thank you, I thought that might be the case. So, I will have to settle
> down and try to write some pseudo-code first. I hope to be back.
Heh, you will find that Python is practically executable pseudo-code!
Untested:
def guess_number():
# please don't cheat the poor computer...
print "Guess a number."
lo = 0
hi = 100
while True:
guess = (lo+hi)//2
ans = raw_input("Is it %d? y/n " % guess)
if ans in ('y', 'yes'):
break
ans = raw_input("Too high? y/n ")
if ans in ("y", "yes"):
hi = guess-1
else:
lo = guess+1
This should run, and it will *almost* do what you want.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
On Thu, 10 Nov 2005 06:47:41 +, Donn Cave wrote:
> Quoth Steven D'Aprano <[EMAIL PROTECTED]>:
> ...
> | So when working with ints, strs or other immutable objects, you aren't
> | modifying the objects in place, you are rebinding the name to another
> | object:
> |
> | py> spam = "a tasty meat-like food"
> | py> alias = spam # both names point to the same str object
> | py> spam = "spam spam spam spam" # rebinds name to new str object
> | py> print spam, alias
> | 'spam spam spam spam' 'a tasty meat-like food'
>
> The semantics of assignment are like that, period. If the right hand
> side is an int, a string, a class instance, a list, whatever, doesn't
> matter at all. The question of mutability at this point can be a red
> herring for someone who doesn't already understand these matters.
Yes, but in the context we were discussing, the original poster was
specifically asking to do something that is only possible with mutable
objects.
He wanted to do something like this:
data = [0, None, 2, ["hello"]]
ref = data[-1]
ref.append("world")
and end up with [0, None, 2, ["hello", "world"]]. That will work, because
the last item in data is mutable. But this will NOT work:
data = [0, None, 2, 0]
ref = data[-1]
ref = 1
assert data[-1] == 1
because ints are immutable. So the distinction between modifying a
mutable object in place and assigning is important.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: A Tcl/Tk programmer learns Python--any advice?
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] says... > That is a misconception. There are several really good packages for OO > in Tcl. XOTcl, [incr] Tcl, and my favorite Snit. None of which are core functions. As I stated, there is currently no OO in the core like in python. > > On top of that there is currently being added OO to the core of Tcl as > well. That should all be integrated in when 8.5 comes out in the > spring. Which once again is a confirmation that my statement was correct about missing OO in the current core. > > Tk is getting a native L&F uplift as well. This is just eye candy, Tkinter was long time GUI for python and no reason to move from Tcl to python. Today you can choose about any toolkit for python and Tcl still has rusty old Tk. It is all a question what you want to solve and how you want to solve it. Tcl/Tk was once the best way to write "throwaway" applications with a GUI, and it still is, in my opinion, but then I know too little python so far. (and python can not do "set result [exec someprog << $input]" as far as I know) -- Svenn -- http://mail.python.org/mailman/listinfo/python-list
Re: need an example of Python numarray to C++ and back again, Boost / SWIG?
I looked at Stefan's post - but he remarks that "Unfortunately, Blitz jealously guards its data (restricted pointers), so that it is not so easy to do the conversion in the other direction. If anyone knows an answer to this problem, I'd be glad to hear it" I've previously looked at Phillip Austin's 'num_util' and Paulo J. S. Silva's 'COIN' example, but even from those two, I can't figure out a way to do: Python 2D numarray --> C++ (process array) --> Python 2D numarray. I forgot about "weave" - I had looked there before and will revisit it to see if it will work. But I was intending to do this with a compiled extension. I wish there was a simple example of this in either the SWIG or Boost docs or a faq/howto posted somewhere . . . -Paul Fernando Perez wrote: > PL wrote: > > > I want to pass a 2D array from Python to C++, manipulate it in C++ (for > > example, add 1 to each element) and pass it back to Python. > > > > With these building blocks I will be able to figure out all the rest of > > what I need to do for my project. I am very familiar with Python, but > > less so with C++ and Boost or SWIG. > > > > Does anyone have an example with all steps that I can follow? More > > specifically I am looking for the C++ code, ".i" file for SWIG and/or > > the analagous setup files that Boost would need to do this. > > You may want to look into weave.inline or weave.blitz, from scipy. Typemaps > for > conversion to blitz++ were recently posted on the scipy list: > > http://aspn.activestate.com/ASPN/Mail/Message/numpy-discussion/2883831 > > In particular look at Stefan's post. > > For info on weave, here you can find some old slides and example code: > > http://amath.colorado.edu/faculty/fperez/python/ > > Cheers, > > f -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonising the vim (e.g. syntax popups) -> vimpst
Hi, Roman et al... On Thursday 10 November 2005 00:52, Roman Roelofsen wrote: > The last 5 days I´ve been working on a code-completion/calltips plugin > for vim. It´s working pretty good but not finished yet. I will anounce > the first beta version on this mailling list. I hope during the next > week. > > I recorded a swf-video so that you can take a look at the current > status. Link: http://www.tuxed.de/vimpst/video.tar.gz That is very impressive. I saw a similar plugin which had a big drawback: it didn't know the object type you need context help for. E.g. it offers you help for the .split method even though you are dealing with an object which does not have this method assigned. The great advantage of the IDLE is that it really understands Python. So it knows about object types you work with. I'm curious how you handle that. Perhaps the python features in Vim have that built-in. But Vim scripting looked even evil for me... and I've been working with Perl for a decade. :) Thanks for your contribution. Christoph -- ~ ~ ".signature" [Modified] 1 line --100%--1,48 All -- http://mail.python.org/mailman/listinfo/python-list
IE Temporary Internet Files & Python
A bit off-topic, but Python related.
Below is a script that recursively deletes files from a directory. It
works well on the two directories that I'm currently using it on:
C:\Documents and Settings\user\Cookies
C:\Documents and Settings\user\Temp
However, I'd like to use it on this directory as well:
C:\Documents and Settings\user\Temporary Internet Files
The script does not seem to work when used on Temporary Internet Files.
I've googled around a bit, but haven't found any tips... thought I'd
trouble the list for an answer or at least some explanations.
Feel free to critiqe the script as well. Perhaps it's a programmer error.
rbt
import os
import os.path
userpath = 'C:/Documents and Settings/'
userlist = os.listdir(userpath)
# Make sure that userlist only contains directories, no files.
for u in userlist[:]:
if os.path.isdir(userpath+u):
pass
else:
userlist.remove(u)
def remove_files(target_dir):
fp = file('remove_temp_files.txt', 'a')
for root, dirs, files in os.walk(target_dir):
for f in files:
try:
os.unlink(os.path.join(root, f))
print >> fp, "Removed:", os.path.join(root,f)
except OSError:
pass
fp.close()
# Remove 'Local Settings|Temp' files
for username in userlist:
target_dir = userpath+username+'/Local Settings/Temp/'
#print target_dir
remove_files(target_dir)
# Remove IE Cookies
for username in userlist:
target_dir = userpath+username+'/Cookies/'
#print target_dir
remove_files(target_dir)
---
--
http://mail.python.org/mailman/listinfo/python-list
Re: IE Temporary Internet Files & Python
>The script does not seem to work when used on Temporary Internet Files. > > Doesn't work well? What does it mean? Is there an exception raised? Les -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Op 2005-11-10, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Thu, 10 Nov 2005 06:47:41 +, Donn Cave wrote:
>
>> Quoth Steven D'Aprano <[EMAIL PROTECTED]>:
>> ...
>> | So when working with ints, strs or other immutable objects, you aren't
>> | modifying the objects in place, you are rebinding the name to another
>> | object:
>> |
>> | py> spam = "a tasty meat-like food"
>> | py> alias = spam # both names point to the same str object
>> | py> spam = "spam spam spam spam" # rebinds name to new str object
>> | py> print spam, alias
>> | 'spam spam spam spam' 'a tasty meat-like food'
>>
>> The semantics of assignment are like that, period. If the right hand
>> side is an int, a string, a class instance, a list, whatever, doesn't
>> matter at all. The question of mutability at this point can be a red
>> herring for someone who doesn't already understand these matters.
>
> Yes, but in the context we were discussing, the original poster was
> specifically asking to do something that is only possible with mutable
> objects.
>
> He wanted to do something like this:
>
> data = [0, None, 2, ["hello"]]
> ref = data[-1]
> ref.append("world")
>
> and end up with [0, None, 2, ["hello", "world"]]. That will work, because
> the last item in data is mutable. But this will NOT work:
>
> data = [0, None, 2, 0]
> ref = data[-1]
> ref = 1
> assert data[-1] == 1
>
> because ints are immutable. So the distinction between modifying a
> mutable object in place and assigning is important.
I wonder couldn't this be done with properties?
Write somekind of property so that if you manipulate a.x it would
manipulate data[-1]
--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I use "list" in the name in "english"/general sense(say a list in > haskell is lazily evaluated), it could be a list or it could be a > lazily evaluated iterable. OK, but the general point is: [x for x in ] is best written list() (x for x in ) is best written iter() (and if is already a list and doesn't need to be copied, or respectively is already being iterated on, just ). > The original post is really just about "when" or may be "until" syntax > that makes it a bit shorter to read and hopefuly easier to understand. This is the first time on this thread in which I'm glimpsing that you mean 'when' not as in SQL (where it has just the same meaning as the 'if' in Python's genexps/listcomps), but rather with the meaning that any Pythonista would instinctively spell 'while'. Since AFAIK 'when' is only used in SQL (out of widespread languages), using it with a drastically different meaning would be an utter disaster, IMHO. Right now, listcomps and genexps can be explained very simply as equivalent to just the same nesting of for and if statement as they have clauses in sequence. Adding a 'while' clause (or 'until', etc) would unfortunately break this simple rule, and therefore make the whole construct harder, not easier, to understand. Unless there are very compelling and frequent use cases for such an addition, I doubt it's worth even trying to make a patch in order to time it against itertools.takewhile... Alex -- http://mail.python.org/mailman/listinfo/python-list
wxPython newbie question, creating "mega widgets" , and DnD
I've made the switch from tKinter to wxPython. I'm slowly trying to learn it, but I had a question - what is the appropriate object to subclass to create a "mega widget" ie A listbox with it's add/delete buttons already built in? wxPanel seems a possibility - any thoughts? A side question - why is their a EVT_LIST_BEGIN_DRAG but no EVT_LIST_END_DRAG, unlike tree's which have BEGIN and END? I need a draggable list box, and would prefer to not handle low level mouse events. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: ... > takewhile(lambda x: condition(x), some_generator) is not very much > difference than(well, still more things to type) > > (x for x in some_generator when condition(x)) So use takewhile(condition, some_generator) which is LESS to type. When your predicate is a function, there's no need to wrap a lambda around it, just like there's no need to wrap an '[x for x in' or '(x for x in' around a list/iterator. > but when I have a number of them in the same expression, the > takewhile/dropwhile becomes to add up. Complicated expressions often become hard to read; so, break the expression up into more readable pieces, assigning names to the intermediate steps. There's negligible price to pay for that, since in Python assignment is NOT a copy, just a 'naming' of an intermediate object. For example, instead of: for x in takefile(foo, takewhile(bar, zlupp)): ... you may choose to code, e.g., zlupps_bars = takewhile(bar, zlupp) zb_foos = takewhile(foo, zlupps_bars) for x in zb_foos: ... Flat is better than nested. Sparse is better than dense. Readability counts. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: gmpy 1.01 rc near... anybody wanna test>
Nick Craig-Wood <[EMAIL PROTECTED]> wrote: > I tested gmpy cvs as of now on Debian/testing/x86 with python2.3. It > compiled perfectly, ran all of its unit tests and also all my test > programs - Well done! Thanks! > My test program seemed to run at the same speed with both versions > (not suprising really since both are using the same libgmp.so on the > system). Yep, as I said any speed differences should be due to the underlying GMP, since gmpy.c itself has not undergone any speed-related change. > Thanks and look forward to the release Thank YOU for the feedback! Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
On Wed, 09 Nov 2005 20:45:52 +0100, bruno at modulix wrote: >> If the array does not exist yet, it's created. > > Which is what I don't like. It should crash. Perhaps not *crash* as such. Raise an exception perhaps. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Steven> But as a general rule, you're right. If you, the developer, Steven> don't have to think of your users as the enemy, you'd be amazed Steven> the amount of make-work you don't have to do. +1 QOTW. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: python + ODBC + Oracle + MySQL - money
In my testing, I need to connect to Oracle, SQL Server and DB2 on various platforms. I have a base class with all the common code, and derived classes for each specific database type using specific database modules such as cxOracle, mxODBC and pyDB2. The derived classes are pretty thin, containing only some syntax peculiarities for a given database type. The code is clean and portable. Grig -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
Alex Martelli wrote: > This is the first time on this thread in which I'm glimpsing that you > mean 'when' not as in SQL (where it has just the same meaning as the > 'if' in Python's genexps/listcomps), but rather with the meaning that > any Pythonista would instinctively spell 'while'. Since AFAIK 'when' is > only used in SQL (out of widespread languages), using it with a > drastically different meaning would be an utter disaster, IMHO. The original post was in the context about dropwhile/takewhile. I may choose the wrong word "when". BTW, what does "when" do it SQL ? I only know about "where" which I believe is the closest equvialent of "if" in python generator comprehension/list expression. To me when/while has a "sequence" element there whereas "where/if" don't. I didn't choose "while" because I know it is a key word already in python so I never thought about it being in this kind of construct, but thinking about it, "if" can be used in list expression then may be while can be used to. > > Right now, listcomps and genexps can be explained very simply as > equivalent to just the same nesting of for and if statement as they have > clauses in sequence. Adding a 'while' clause (or 'until', etc) would > unfortunately break this simple rule, and therefore make the whole > construct harder, not easier, to understand. Unless there are very > compelling and frequent use cases for such an addition, I doubt it's > worth even trying to make a patch in order to time it against > itertools.takewhile... I have no idea what it is involved or what about rules. I just raised a simple question because the whole dropping filter/map/reduce discussion I read gave me the impression that python is siding over in-line list/generator expression rather than the more traditional map/reduce/takewhile function call style. -- http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Antoon Pardon wrote: > Write somekind of property so that if you manipulate a.x it would > manipulate data[-1] Like that? >>> def make_prp(index): ... def get(self): return self[index] ... def set(self, value): self[index] = value ... return property(get, set) ... >>> class List(list): ... first = make_prp(0) ... last = make_prp(-1) ... >>> items = List([1,2,3]) >>> items.first 1 >>> items.last = 42 >>> items [1, 2, 42] However, that's customizing attribute access, not name binding. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: [ x for x in xrange(10) when p(x) ]
Alex Martelli wrote: > So use takewhile(condition, some_generator) > > which is LESS to type. When your predicate is a function, there's no > need to wrap a lambda around it, just like there's no need to wrap an > '[x for x in' or '(x for x in' around a list/iterator. No. my predicate sometimes is not function but inline expression that needs scoping within nested for. > Complicated expressions often become hard to read; so, break the > expression up into more readable pieces, assigning names to the > intermediate steps. There's negligible price to pay for that, since in > Python assignment is NOT a copy, just a 'naming' of an intermediate > object. For example, instead of: > > for x in takefile(foo, takewhile(bar, zlupp)): ... > > you may choose to code, e.g., > > zlupps_bars = takewhile(bar, zlupp) > zb_foos = takewhile(foo, zlupps_bars) > for x in zb_foos: ... > > Flat is better than nested. > Sparse is better than dense. > Readability counts. > That is one opinion and I think I can decide when to break or not to break. Sometimes, breaking them in mutiple level for with interim name assignment is not desirable. In fact, because python allows me to write in both style, I practiced to write the same thing in both style and found that the nested list expression way is less error prone(at least for me ). -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion about __call__ and attribute lookup
Leif K-Brooks wrote: > New-style classes look up special methods on the class, not on the instance: For my future reference, is this documented somewhere in the standard docs? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: A Tcl/Tk programmer learns Python--any advice?
Why does there need to be OO "in the core"? That is one thing I have never understood. If you want OO, get a package that fits your style of OO and "package require" you are off and running. That probably isn't what you would be looking at Tcl for anyway. I agree about Tk and I am actually talking with someone about adding a wxTcl to the mix as well. I think wx is a much better toolkit. > It is all a question what you want to solve and how you want to solve > it. That is so true. Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: A Tcl/Tk programmer learns Python--any advice?
On 2005-11-10, Svenn Are Bjerkem <[EMAIL PROTECTED]> wrote:
> (and python can not do "set result [exec someprog << $input]"
> as far as I know)
I don't remember Tcl very well, but doesn't this do the same
thing?
result = os.popen('someprog','r').read()
--
Grant Edwards grante Yow! I have a VISION! It's
at a RANCID double-FISHWICH on
visi.coman ENRICHED BUN!!
--
http://mail.python.org/mailman/listinfo/python-list
Re: IE Temporary Internet Files & Python
Laszlo Zsolt Nagy wrote: > >> The script does not seem to work when used on Temporary Internet Files. >> > Doesn't work well? What does it mean? Is there an exception raised? > > Les > No exception. The files are not deleted. -- http://mail.python.org/mailman/listinfo/python-list
tiff tags
Hi,
Is any way to write more tags to tiff file
when saved from:
im= Image.fromstring("I",
datasize, newbuftemp, 'raw', 'I;16')
im.save(“myfile.tif”)
the tag are:
256=(640,)
257=(512,)
258=(16,)
259=(1,)
262=(1,)
273=(110,)
278=(512,)
279=(4, '\x00\x00\n\x00')
But there are more: how can I write the
following tags?
296=(1,)
266=(1,)
339=(1,)
282=((1073741824, 1073741824),)
283=((1073741824, 1073741824),)
284=(1,)
305=(2, ...)
269=(2, …)
274=(3, '\x01\x00')
277=(3, '\x01\x00')
Thanks a lot!
James
--
http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
Hi
Proposition 1:
> data = [0, None, 2, 0]
> ref = data[-1]
> ref = 1
> assert data[-1] == 1
Logically, it doesn't work. Here you are assigning to ref a NEW value.
That won't replace the data[-1] value. It's out of logic this
proposition.
While this (proposition 2):
data = [0, None, 2, ["hello"]]
ref = data[-1]
ref.append("world")
does work, because you are assigning to ref THAT list ["hello"]. So, if
you have THAT list, and appends a value, THAT list will be modified.
ref is pointing to THAT object. So, I don't understand why you write
the first proposition, like if that can be a normal thinking of how to
do the second proposition :-S
Well, I hope that newcomers to Python don't confuse himselves :)
Daniel
--
http://mail.python.org/mailman/listinfo/python-list
Re: Addressing the last element of a list
This mutable/immutable object and name/variable is confusing. Daniel Crespo wrote: > Well, I hope that newcomers to Python don't confuse himselves :) > > Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Alex Martelli wrote: > Anand S Bisen <[EMAIL PROTECTED]> wrote: > > > I dont know much !! But if somebody asks me this question my answer > > would be to convert some of the meat inside my programs to C/C++ and > > then provide the interface to those novel ideas to Python using swig. > > And for another level of protection maybe use these offuscator on the > > remaining Python source. What do you think ? > > I think that's feeble protection. If you have valuable code, and > distribute it, people WILL crack it -- just check the warez sites for > experimental proof... EVERYTHING that people are really interested in > DOES get cracked, no matter what tricky machine-code the "protections" > are coded in. > > There's ONE way to have uncrackable code -- don't distribute it, but > rather put it up on the net on a well-secured machine under your > control, available as (say) a webservice (subscription-only, pay per > use, or whatever business model you want). You can distribute all the > parts of your app that aren't worth protecting as a "fat client" app (in > Python or whatever) and keep those which ARE worth protecting on the > server that YOU control (and make sure it's very, VERY safe, of course); > and you may write the precious parts in Python, too, no problem. > > This is (a minor) one of the many reasons that make webservices the way > of the future (hey, even *MSFT* noticed that recently, it seems...). > There are many other advantages, especially if you keep the clients > thin. The only issue is, your apps will require network connectivity to > execute... but these days, with airlines and train lines busy adding > wi-fi, and towns busily blanketing themselves with free wi-fi, etc, etc, > that's less and less likely to be a big problem... > > > Alex I think that is not workable because it is easy to say the the internet is available everywhere. It is not available in developing countries or in rural areas and so these people who live/work there will never benefit from a webservice type protection scheme, and what if the network in your area goes down? bye bye app that I *really* need for tomorrow. Reliability is important but so is protecting your code in an effective manner I do believe that you are right about those that crack software for kicks or money. If you look around at you local market place i'm sure there are many 'discounted' commercial softwares/games sold. of course the big software companies might say 'trusted computing will save us' but I for one will never truly trust it. Perhaps a comprehensive protection for interpreted languages can never be built because of their high level nature? -- http://mail.python.org/mailman/listinfo/python-list
Recommendation please: forming an XML toolkit
I'm asking help on this topic of building a tools foundation for future XML projects because of the sheer volume of possibilities I will not have the time to check/try/test in detail. This question is a bit like the ones pertaining to 'Which web framework to use?', there is a lot of good stuff out there, and often it boils down to personnal preference, mind-fitting interface and such BUT... to make it more precise I will give more context on the future projects involved... I've done some homework trying out a few packages based on published tutorial: Boddie's Python and XML: An Introduction (for minidom), Lundh's elementTree examples, I read a bit about Amara, pyXML, others. I've read a bit on ease-of-use, benchmarks, pythonesque versus job-protection perspectives, I've even tried building my own xml2PythonObjects2xml tools Finally, I've read-up a few threads pertaining to the question 'which XML packages to use' ! Some considerations I have using XML : 1- representing inter-connected academic articles in text-based files whitout a sopecific BD package 2- being 'easily' able to modify the structure of these documents as search tools evolve 3- searching through these articles often, and with evolving algortihmic complexity (from word base search to RDF-type meta data, to OWL-type semantic information, etc) 4- In a context where I'm (in a practical form) evangelizing the use of Python as a great tool from going from 'this could be a new approach' to 'this piece of code realizes that approach' (managers need to be confident that they could choose to make this set of articles evolve using other languages (other developpers not caring for Python for example, but Java instead) and the infobase would be directly accessible and algorithms understandable from a 'popular' xml-manipulation point-of-view (Using DOM, I guess a regular DOM-SAX Java developper would understand Python code, but would they if the code relied heavily on elementTree (for example) 5- relying as less as possible on complex third-party libs (to use A, first get B from elsewhere, which itself requires C from still another place...) I DON'T mind the simple package (PIL comes to mind here) 6- VERY IMPORTANT CONSIDERATION - That I can keep my focus on developing algorithms, MINIMIZING XML clutter I don't want to become a XML guru - I like the simple principle of XML as a tree of tagged elements that have attributes and text data... Thanks for any and all who read this, and those who have experience ressembling what I'm about to embark on for your help ! Jean-Marc -- http://mail.python.org/mailman/listinfo/python-list
Re: A Tcl/Tk programmer learns Python--any advice?
Svenn Are Bjerkem wrote: > (and python can not do "set result [exec someprog << $input]" as far as > I know) execute a pro import subprocess -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Alex Martelli wrote: > If you have valuable code, and > distribute it, people WILL crack it -- just check the warez sites for > experimental proof... EVERYTHING that people are really interested in > DOES get cracked, no matter what tricky machine-code the "protections" > are coded in. That is very black and white thinking. It may be true that everything gets cracked, but there are different degrees to which it might harm your business model. On top of that, some users may be reluctant to install binary cracks from obviously disreputable sources. Who knows what spyware or viruses you could catch? Compare that to the simplicity and safety of someone posting instructions to "open secure.py in notepad, and change the 'if license_found:' line to 'if 1:'", for example. No risk and even less effort than applying a patch. If someone wants to break into your house, they will get in. But it's still worth taking some precautions (locks, alarms, whatever) to reduce the probability. > There's ONE way to have uncrackable code -- don't distribute it, but > rather put it up on the net on a well-secured machine under your > control, available as (say) a webservice (subscription-only, pay per > use, or whatever business model you want). This is all well and good when: - web access is free (it's not if you're on dialup, or on a portable device/phone) - web access is fast enough (it's not if you're working with certain types of real-time games or multimedia) - web access is convenient (it's not if you're behind a restrictive firewall, or your country/area is poorly connected) For example, I'd like to write a game in Python. I'd like to give the game away free and charge for extra content. In C++ I can make it difficult for users to share content with others who haven't paid for it, with cryptographic hashes and the like. No, not impossible, but difficult enough to deter most people. In Python it's much harder, when the end user can open up the relevant file and quickly remove the license check. No doubt this is another of the reasons why Python isn't catching on quickly for game development, sadly. (I'm not saying this is a deficiency of Python as such. It's just a comment on the situation.) > This is (a minor) one of the many reasons that make webservices the way > of the future (hey, even *MSFT* noticed that recently, it seems...). But they are not suitable for all applications, and probably never will be. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: getting results into one variable
Steve Holden wrote:
> [EMAIL PROTECTED] wrote:
>
> That's a nice email address :-)
> > hi
> > the database "execute" function returns a list of logical results. Each
> > logical result is a list of row tuples, as explained in the documents.
> >
> In a DB-API-compliant module, execution of the query adn retrieval of
> the result(s) are actually sepearated: execute() executesthe query (and
> on some, but not all, platforms returns the number of rows in the
> result). Then you use either fetchone(), fetchmany() or fetchall() to
> retrive the results from the cursor.
>
> > everytime i use it to execute various statements, it returns me, for
> > example
> > ([(0,)], [(0,)], [(0,)]) and sometimes , ([(0,)], [(0,)]) or ([(0,)])
> >
> What you seem to be saying here is that you are getting a tuple of
> lists, each of which contains a (single-element) tuple. What mopdule are
> you using to do this, or is it the result of a gedanken-experiment?
>
> > in my call, i give
> > eg (a,b,c) = db.execute(stmt) so that it returns me ([(0,)], [(0,)],
> > [(0,)])
> >
> > in python, can we do something like
> >
> > a = db.execute(stmt) and then expand variable 'a'
> >
> > instead of doing
> > (a,b) = db.execute(stmt) for return of 2
> > (a,b,c) = for return of 3
> > (a,b,c,d) for return of 4
> >
> > thanks
> >
> Yes. Here's a pracical example using the database that generates
> www.holdenweb.com:
>
> >>> import mx.ODBC.Windows as db
> >>> conn = db.connect("comsite")
> >>> curs = conn.cursor()
> >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
> >>>
>
> [Note that this returns None for this particular combination of database
> module and backend].
>
> >>> rows = curs.fetchall()
> >>> rows
> [(1, 'Explore Holden Web', 'hd_explore'), (2, 'Student Links',
> 'hd_students'), (3, 'Other Stuff', 'hd_otherstuff'), (4, 'Recent Python
> News', 'hd_pythonnews'),(5, 'Python Links', 'hd_pythonlinks'), (6,
> 'Python Reading', 'hd_pythonreading'), (7, 'Python Modules',
> 'hd_pythonreviews')]
> >>>
>
> You see here that fetchall() returns a list of tuples - each tuple being
> a rows from the query result. It's normal to iterate over this list, and
> one way to do this is:
>
> >>> for row in rows:
> ... print row
> ...
> (1, 'Explore Holden Web', 'hd_explore')
> (2, 'Student Links', 'hd_students')
> (3, 'Other Stuff', 'hd_otherstuff')
> (4, 'Recent Python News', 'hd_pythonnews')
> (5, 'Python Links', 'hd_pythonlinks')
> (6, 'Python Reading', 'hd_pythonreading')
> (7, 'Python Modules', 'hd_pythonreviews')
> >>>
>
> Of course you can unpack each row if you want to refer to the columns
> individually:
>
> >>> for row in rows:
> ... id, title, path = row
> ... print title, id
> ...
> Explore Holden Web 1
> Student Links 2
> Other Stuff 3
> Recent Python News 4
> Python Links 5
> Python Reading 6
> Python Modules 7
> >>>
> You can save yourself some time by doing the unpacking right in the for
> loop:
>
> >>> for id, title, path in rows:
> ... print id, title
> ...
> 1 Explore Holden Web
> 2 Student Links
> 3 Other Stuff
> 4 Recent Python News
> 5 Python Links
> 6 Python Reading
> 7 Python Modules
> >>>
>
> Finally, if you only want to use the result once you don't even need to
> save it:
>
> >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
> >>> for id, ttl, pth in curs.fetchall():
> ... print pth, ":", ttl
> ...
> hd_explore : Explore Holden Web
> hd_students : Student Links
> hd_otherstuff : Other Stuff
> hd_pythonnews : Recent Python News
> hd_pythonlinks : Python Links
> hd_pythonreading : Python Reading
> hd_pythonreviews : Python Modules
> >>>
>
> You can use fetchone() to return each row as a tuple if that suits you
> better, but it may be less efficient because it can lead to inefficient
> communication between the database server and the client, particularly
> if the result set is large.
>
> >>> curs.execute("SELECT secID, secTitle, secPath FROM SECTION")
> >>> curs.fetchone()
> (1, 'Explore Holden Web', 'hd_explore')
> >>>
>
> So of course you can unpack the tuple as well:
>
> >>> id, ttl, pth = curs.fetchone()
> >>> print "Title:", ttl, "path:", pth, "id:", id
> Title: Student Links path: hd_students id: 2
> >>>
>
> If the result sets are too large to comfortably hold in memory you can
> fetch them N at a time with fetchmany(N), repeating until there's
> nothing left to read. And so on, but I hope this gives you the idea.
>
> 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/
thanks , that's excellent..
currently what i do is sort of combined the sql statements, something
like
stmt = """declare @res int
exec @res sp_adduser '%s'
if @res = 0
insert table values...blah blah where col = '%s'
""" % ( login, colvalue)
then when i do
(a,b) = db.execute
PySol --> SuSE 10.0
Hi,
I'm trying to install PySol on 10.0. I've tried two routes: the RPM and
building from source.
First, from RPM. I su'd to root and run the following:
linuxdell:/home/mike # rpm -i pysol-4.82-1.noarch.rpm
error: Failed dependencies:
tkinter >= 2.2 is needed by pysol-4.82-1
Checking in Yast, it appears that tkinter is provided by python-tk
(although I could be wrong):
pyth_tk
python_tkinter_lib
pyth_tkl
python-tkinter
_tkinter.so
_tkinter.so
python-tk = 2.4.1-3
I also have python-devel and tk-devel installed.
Trying from source, I was told I first needed to install
pysol-sound-server3.01. I did that, and then attempted to install pysol:
linuxdell:/home/mike/pysol-4.82/src # python pysol.py
Traceback (most recent call last):
File "pysol.py", line 121, in ?
sys.exit(main(sys.argv))
File "/home/mike/pysol-4.82/src/main.py", line 424, in main
r = pysol_main(args)
File "/home/mike/pysol-4.82/src/main.py", line 367, in pysol_main
r = pysol_init(app, args)
File "/home/mike/pysol-4.82/src/main.py", line 91, in pysol_init
app.dataloader = DataLoader(args[0], f)
File "/home/mike/pysol-4.82/src/util.py", line 186, in __init__
raise os.error, str(argv0) + ": DataLoader could not find " +
str(filenames)
OSError: pysol.py: DataLoader could not find ('html/license.html',)
Nowhere in the extracted files were there html files. I also downloaded
pysol-4.80, which supposedly didn't need to be compiled. Checking these
extracted files, html/license.html did indeed exist. So, attempting to
install 4.80:
linuxdell:/home/mike/pysol-4.80 # ll
total 51
drwxrwxrwx 3 mike users 240 2001-11-28 03:36 .
drwxr-xr-x 44 mike users 2360 2005-11-07 23:54 ..
-rw-r--r-- 1 mike users 18094 1998-09-07 11:00 COPYING
drwxr-xr-x 17 mike users 712 2001-11-28 03:36 data
-rw-r--r-- 1 mike users 262 2000-08-02 21:23 INSTALL
-rw-r--r-- 1 mike users 1276 2001-11-28 03:31 Makefile
-rw-r--r-- 1 mike users 254 2000-08-02 21:23 NEWS
-rwxr-xr-x 1 mike users 2624 2001-06-22 17:02 pysol
-rw-r--r-- 1 mike users 6808 2001-11-28 03:36 pysol.6
-rw-r--r-- 1 mike users 1241 2001-09-10 12:07 README
linuxdell:/home/mike/pysol-4.80 # ./pysol
./pysol: could not find the file 'pysol_24.pyc' !
Has anyone run across this sort of problem or could please advise me as to
how I can get this to work?
Thanks, Mike
username=trozzo
domain=arcor(dot)de
--
http://mail.python.org/mailman/listinfo/python-list
Re: A Tcl/Tk programmer learns Python--any advice?
oops. > (and python can not do "set result [exec someprog << $input]" as far as > I know) execute a script inside a list comprehension and shift it to the left by a built-in function ? I suspect you want: import subprocess -- http://mail.python.org/mailman/listinfo/python-list
RE: IE Temporary Internet Files & Python
[rtilley] > Below is a script that recursively deletes files from a directory. It > works well on the two directories that I'm currently using it on: > C:\Documents and Settings\user\Cookies > C:\Documents and Settings\user\Temp > However, I'd like to use it on this directory as well: > C:\Documents and Settings\user\Temporary Internet Files > The script does not seem to work when used on Temporary Internet Files. > I've googled around a bit, but haven't found any tips... thought I'd > trouble the list for an answer or at least some explanations. > Feel free to critiqe the script as well. Perhaps it's a programmer error. Temporary Internet Files is one of those special shell folders and, I suspect, isn't really a folder at all in the normal sense: it just presents itself as one to the O/S. (Might be wrong there). Probably means you have to use shell functions to access it. Quick trial with SHFileOperation works up to a point, but ultimately fails with a file-in-use error. This article: http://www.codeguru.com/Cpp/I-N/ieprogram/article.php/c1245/ uses a very different technique. The APIs in question aren't wrapped in pywin32. You could probably get at them via ctypes. Don't have time to try it myself at the moment. TJG PS Probably doesn't matter at the mo, but for general purpose use, those folders aren't always where your script hardwires them to be. You might need to look at the shell functions around SHGetPathFromIDList and SHGetSpecialFolderLocation. Tim This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Newb ??
On Fri, 11 Nov 2005 01:39:40 +1100, Steven D'Aprano wrote:
> On Thu, 10 Nov 2005 13:30:05 +, Norman Silverstone wrote:
>
>>> In that case, think of "bisection". Originally, all the computer knows
>>> is that the number is in some range, say 0 to 100. It can then guess
>>> the midpoint, 50. If it's right, yay! Otherwise: if it's told to go
>>> lower, then the range is now 0 to 49 -- if higher, it's 51 to 100; in
>>> each case the range was just halved (actually, a bit more than halved).
>>
>> Thank you, I thought that might be the case. So, I will have to settle
>> down and try to write some pseudo-code first. I hope to be back.
>
> Heh, you will find that Python is practically executable pseudo-code!
>
> Untested:
>
>
> def guess_number():
> # please don't cheat the poor computer...
> print "Guess a number."
> lo = 0
> hi = 100
> while True:
> guess = (lo+hi)//2
> ans = raw_input("Is it %d? y/n " % guess)
> if ans in ('y', 'yes'):
> break
> ans = raw_input("Too high? y/n ")
> if ans in ("y", "yes"):
> hi = guess-1
> else:
> lo = guess+1
>
> This should run, and it will *almost* do what you want.
Thanks for that but I think it is too simplistic. It appears OK for the
first guess, which is 50 but, what about the next guess. If the guess is
too high then the next guess has to be 50/2. However, if it is too low
then the next guess must be first guess + (100-second guess)/2. In general
terms, if guess is too high then next guess must (guess - lowest
possible)/2 and if too low then it is guess + (highest possible -
guess)/2.
Comments please.
Norman
--
http://mail.python.org/mailman/listinfo/python-list
Re: python + ODBC + Oracle + MySQL - money
Grig Gheorghiu wrote:
> In my testing, I need to connect to Oracle, SQL Server and DB2 on
> various platforms. I have a base class with all the common code, and
> derived classes for each specific database type using specific database
> modules such as cxOracle, mxODBC and pyDB2. The derived classes are
> pretty thin, containing only some syntax peculiarities for a given
> database type. The code is clean and portable.
So maybe you're lucky that all your database modules use the same access
to query parameters. MySQLdb and cx_Oracle would be different in that
MySQLdb has paramstyle = "format" and cx_Oracle has paramstyle =
"qmark/named", i. e. to query a specific record of the person table you
would use
p_id = 4711
cur.execute("select firstname from person where person_id=%s", (p_id,))
using MySQLdb, and:
cur.execute("select firstname from person where person_id=?", (p_id,))
using cx_Oracle.
Now, probably a lot of people have written wrappers for DB-API modules
that translate one paramstyle to the other. The most sensible solution
is to translate the format/pyformat one to others.
Often, one other solution is to use a higher-level database interface
uses your database modules internally, but has the same consistent
interface for the outside.
In my recent evaluations, I liked PyDO2 for this
(http://skunkweb.sourceforge.net/pydo2.html). Unlike SQLObject, it is
able to use MySQL and Oracle now, though there is work underway to add
Oracle support to SQLObject.
OTOH, the advice to use MySQLdb and cx_Oracle directly is probably a
good one, especially for a newcomer to Python. It's a good way to learn
Python and learning the Python DB-API is a good idea if you want to do a
database application in Python. You can use higher-level interfaces (or
write them yourself) later on.
And if this is serious work with business value, then just buying a
mxODBC license and go on with the real problem is probably the most
sensible solution.
You can use the time saved for learning Python, then, which is perhaps
more fun :-)
Cheers,
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list
