Re: docstrings style question
On Jan 9, 11:51 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Steve Brown wrote: > > I've got a series of modules which look like this: > > > # > > # > > # Temperature Sense Test > > # > > # > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > > the docstring self.__doc__ is already in use in the test log. I've read that > > all modules and classes should have docstrings, but I don't really have > > anything else to say, and each module contains only one class. I don't think > > that > > > """Temperature Sense Test""" > > class Test3(ar_test.AR_TEST): > > """Temperature Sense Test""" > > > would be a real improvement. > > > What do you think? > > since you already seem to cater to your audience (clearly marked > comments for people browsing the code, brief docstrings for the test > log), I don't really see why you should change anything. > > > I've read that all modules and classes should have docstrings > > if nobody's going to read them, there's no reason to add them. don't > treat generic style advice as dogma. > > Well, trivial modules certainly don't need much documentation, but he didn't say they were trivial. I assumed there was more to them then he showed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a bidimensional list in a bidimensional array
> C:\> \python25\python -m -s :-) Thanks a lot :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: docstrings style question
-On [20080110 06:51], Steve Brown ([EMAIL PROTECTED]) wrote: >I don't like the duplicated information: But the comment is attractive, I find it unattractive to be honest. >and the docstring self.__doc__ is already in use in the test log. I've read >that all modules and classes should have docstrings, but I don't really have >anything else to say, and each module contains only one class. The ultimate test is running `pydoc your.module` or running epydoc on your source and see how well the resulting documentation is built up. -- Jeroen Ruigrok van der Werven / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ The quieter you become, the more you are able to hear... -- http://mail.python.org/mailman/listinfo/python-list
Re: Conventions for dummy name (was: for loop without variable)
-On [20080110 00:21], Ben Finney ([EMAIL PROTECTED]) wrote: >The problem with the '_' name is that it is already well-known and >long-used existing convention for an entirely unrelated purpose: in >the 'gettext' i18n library, the '_' function to get the >locally-translated version of a text string. The same applies for Babel (http://babel.edgewall.org/) where we have _() in similar vein to the gettext implementation. -- Jeroen Ruigrok van der Werven / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ With a nuclear fire of Love in our Hearts, rest easy baby, rest easy... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get memory size/usage of python object
> Would you care to precisely define "REAL size" first? Consider: > > >>> atuple = (1, 2) > >>> mylist = [(0, 0), atuple] > > Should sizeof(mylist) include sizeof(atuple) ? No, I'm talking about "simple" lists, without REFERENCES to another objects into it. I mean: lists = [ 0, 1, 2, 3, 4, (1,2), 3] or array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] Maybe I can "pickle" the object to disk and see the filesize ... :-? -- http://mail.python.org/mailman/listinfo/python-list
PyGILState_Release produces a seg fault
Hello and happy new year folks,
I am experiencing a seg fault while using the python interface to
the VTK library (debian oldstable, python 2.3). The VTK library is
wrapped by a custom mechanism to provide a python API. In particular
they implemented a way so that a python function can be called in
response to an event(*). Basically all the code is doing is:
{
PyGILState_STATE state = PyGILState_Ensure();
// construct arglist from C++ args:
...
// call python function:
result = PyEval_CallObject(this->obj, arglist);
PyGILState_Release(state); // crash happens here
}
However the event being triggered from the C++ layer is done from
multiple threads. After reading :
http://docs.python.org/api/threads.html
I tought that the VTK-python layer was simply missing a call to :
PyEval_InitThreads() just before Py_InitModule(), but now my python
shell appears as hung ! The only solution I found is that if I comment
out the function calls PyGILState_Ensure/PyGILState_Release then
everything goes smoothly.
Am I reading the docs backward ? I do need to keep the call to
PyGILState_Ensure/PyGILState_Release, right ?
I am also copying the log from valgrind (VTK lib untouched, no call
to PyEval_InitThreads), UpdateProgress being the function called from
multiple threads:
==20066== Thread 2:
==20066== Invalid read of size 4
==20066==at 0x403232A: sem_post@@GLIBC_2.1 (in /usr/lib/debug/
libpthread-2.5.so)
==20066==by 0x80B0D53: PyEval_ReleaseLock (in /usr/bin/python2.4)
==20066==by 0x80DDB20: PyGILState_Release (in /usr/bin/python2.4)
==20066==by 0x45C7AB4: vtkPythonCommand::Execute(vtkObject*,
unsigned long, void*) (vtkPythonUtil.cxx:2016)
==20066==by 0x483C0DF: vtkSubjectHelper::InvokeEvent(unsigned
long, void*, vtkObject*) (vtkObject.cxx:547)
==20066==by 0x483C18E: vtkObject::InvokeEvent(unsigned long,
void*) (vtkObject.cxx:713)
==20066==by 0x4E67E6A: vtkAlgorithm::UpdateProgress(double)
(vtkAlgorithm.cxx:115)
Thanks,
-Mathieu
Original post:
http://public.kitware.com/pipermail/vtk-developers/2008-January/004890.html
(*) See line 1906->2019 at:
http://public.kitware.com/cgi-bin/viewcvs.cgi/Common/vtkPythonUtil.cxx?annotate=1.80
--
http://mail.python.org/mailman/listinfo/python-list
Re: alternating string replace
On Jan 10, 3:46 am, [EMAIL PROTECTED] wrote: > Gordon C: > > > This is very cool stuff but I suspect that the code is unreadable > > to many readers, including me. Just for fun here is a complete program, > > written in Turbo Pascal, circa 1982, that does the job. Readable > > n'est pas? > > I think it's quite readable, especially if you indent it more > correctly. > Pascal is usually among the most readable languages, for not-too-much > complex tasks. I don't mind its mutable strings too much. > > Bye, > bearophile And for me to feel a tiny bit happier, is very similar to mine :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
Ed Jensen a écrit : > Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: >> And the reference implementation of Python (CPython) is not >> interpreted, it's compiled to byte-code, which is then executed by a VM >> (just like Java). > > Wow, this is pretty misleading. Ho yes ??? Why so, please ? Care to point to anything *wrong* in the above statement ? > Java is, indeed, compiled to bytecode; however, modern JVMs typically > compile the bytecode to native code and then execute the native code. Which is known as JIT compilation - and there are a couple attempts at it in Python too. Anyway, the JIT compiler is not part of the Java spec (while the byte-code/VM is), and its not garanteed to be there on each an every Java VM. > CPython strictly interprets bytecode; And ? > it does not compile the > bytecode to native code. And ? I fail to see how the existence of JIT compilers in some Java VM changes anything to the fact that both Java (by language specification) and CPython use the byte-code/VM scheme. -- http://mail.python.org/mailman/listinfo/python-list
Re: Conventions for dummy name
Hallöchen! Ben Finney writes: > "Diez B. Roggisch" <[EMAIL PROTECTED]> writes: > >> The underscore is used as "discarded" identifier. So maybe >> >> for _ in xrange(10): >> ... > > The problem with the '_' name is that it is already well-known and > long-used existing convention for an entirely unrelated purpose: > in the 'gettext' i18n library, the '_' function to get the > locally-translated version of a text string. Right, that's because I've used "__" where not all returning values are interesing to me such as a, b, __ = function_that_returns_three_values(x, y) However, in loops, I prefer real names, even if the loop variable isn't used outside. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python via a little word frequency program
MRAB a écrit : > On Jan 9, 12:19 pm, Bruno Desthuilliers [EMAIL PROTECTED]> wrote: (snip) > That actually prints: > > kevin : 3 > fred : 2 > jock : 2 > andrew : 1 > bill : 1 > freddy : 1 > > It says that "fred" occurs twice because of "freddy". oops ! My bad, didn't spot that one :( Thanks for pointing this out. -- http://mail.python.org/mailman/listinfo/python-list
FindWindowById returns None..... ?
Hi, I'm trying to split my GUI into several files since its beginning to become a bit large.. I've placed a panel class inside gui2.py, but it needs some information from a panel in gui1.py... if I import gui1 in gui2 and try to find the panel by its ID, (using the Id generated in gui1) I get a None value returned?? using findwindowbyid in gui1 on the same ID works fine.. I'm guessing i'm doing this the wrong way, can anyone comment on this? Thanks, Soren -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python via a little word frequency program
Paul Hankin a écrit : > On Jan 9, 12:19 pm, Bruno Desthuilliers [EMAIL PROTECTED]> wrote: >> Andrew Savige a écrit : >>> and the -x hack above to >>> achieve a descending sort feels a bit odd to me, though I couldn't think >>> of a better way to do it. >> The "other" way would be to pass a custom comparison callback to sort, >> which would be both slower and more complicated. Your solution is IMHO >> the right thing to do here. > > Both list.sort and sorted have a parameter 'reverse' which does a > descending rather than ascending sort. Yes. But here the specs says that sort must be descending on first key (frequency) and ascending on the second (name), so you can't just use reverse sort. FWIW, a correct (and readable) solution - based on the 'key' param - has been given by Peter Otten, but it still requires a callback function, so while it avoids the '-x hack', it's still more expensive than a plain sort. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get memory size/usage of python object
Hi, The only list without references to other objects in it is [ ]. 0, 1, 2, etc are objects. Every value in Python is a reference to an object. Remco On Jan 10, 2008 9:14 AM, Santiago Romero < [EMAIL PROTECTED]> wrote: > > > Would you care to precisely define "REAL size" first? Consider: > > > > >>> atuple = (1, 2) > > >>> mylist = [(0, 0), atuple] > > > > Should sizeof(mylist) include sizeof(atuple) ? > > No, I'm talking about "simple" lists, without REFERENCES to another > objects into it. > > I mean: > > lists = [ 0, 1, 2, 3, 4, (1,2), 3] > > or > > array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ] > > Maybe I can "pickle" the object to disk and see the filesize ... :-? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: FindWindowById returns None..... ?
On Jan 10, 9:43 am, Soren <[EMAIL PROTECTED]> wrote: > Hi, > > I'm trying to split my GUI into several files since its beginning to > become a bit large.. I've placed a panel class inside gui2.py, but it > needs some information from a panel in gui1.py... if I import gui1 in > gui2 and try to find the panel by its ID, (using the Id generated in > gui1) I get a None value returned?? using findwindowbyid in gui1 on > the same ID works fine.. > > I'm guessing i'm doing this the wrong way, can anyone comment on this? > > Thanks, > Soren Wops.. and I'm using wxPython :) -- http://mail.python.org/mailman/listinfo/python-list
Why my program (using pexpect to switch user) doesn't work well?
I'm new to python
I want to write a simple script to switch user,for example,from user_A
to user_B.
This my codes:
#!/usr/bin/python
import pexpect
import os
passwd="user_B"
child = pexpect.spawn('su user_B')
child.expect('Password:')
child.sendline(passwd)
child.expect('$')
child.close()
Maybe it's the easiest pexpect program.Sometimes ,it work well,it
switch to user_B successfully .But after i type the command exit to
switch back to user_A,execute the python script again,it can't work,do
nothing or just waiting.Why it have different results?
Sorry for my poor English,and many thanks to all.
Blackjade
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to get memory size/usage of python object
On Thu, 10 Jan 2008 00:14:42 -0800, Santiago Romero wrote:
>> Would you care to precisely define "REAL size" first? Consider:
>>
>> >>> atuple = (1, 2)
>> >>> mylist = [(0, 0), atuple]
>>
>> Should sizeof(mylist) include sizeof(atuple) ?
>
> No, I'm talking about "simple" lists, without REFERENCES to another
> objects into it.
>
> I mean:
>
> lists = [ 0, 1, 2, 3, 4, (1,2), 3]
That list has 7 references to other objects. One of those objects has 2
references to objects.
In total, depending on implementation, there could be as many as 9
objects referenced by that list, or as few as 6 objects (both references
to 3 could be to the same object).
In the current CPython implementation, that list will have 7 references
to 6 objects. Including indirect references, there will be 9 references
to 6 objects. (Or so I understand.)
> or
>
> array = [ [0,0,0,0,0,0,0], [1,1,1,1,2,1,2], ... ]
Ignoring the '...', there will be a total of 16 references to 5 objects
in the current CPython implementation. Other Pythons (Jython, IronPython,
PyPy, ...) may be different.
> Maybe I can "pickle" the object to disk and see the filesize ... :-?
That would measure something very different.
Possibly you want something like this heuristic:
def sizeof(obj):
"""APPROXIMATE memory taken by some Python objects in
the current 32-bit CPython implementation.
Excludes the space used by items in containers; does not
take into account overhead of memory allocation from the
operating system, or over-allocation by lists and dicts.
"""
T = type(obj)
if T is int:
kind = "fixed"
container = False
size = 4
elif T is list or T is tuple:
kind = "variable"
container = True
size = 4*len(obj)
elif T is dict:
kind = "variable"
container = True
size = 144
if len(obj) > 8:
size += 12*(len(obj)-8)
elif T is str:
kind = "variable"
container = False
size = len(obj) + 1
else:
raise TypeError("don't know about this kind of object")
if kind == "fixed":
overhead = 8
else: # "variable"
overhead = 12
if container:
garbage_collector = 8
else:
garbage_collector = 0
malloc = 8 # in most cases
size = size + overhead + garbage_collector + malloc
# Round to nearest multiple of 8 bytes
x = size % 8
if x != 0:
size += 8-x
size = (size + 8)
return size
See:
http://mail.python.org/pipermail/python-list/2002-March/135223.html
to get you started.
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Win32com and Excel
Hi,
I currently have an excel table (1 table each time) that has differing
number of rows and differing number of columns each time, for another
program i use (SPSS) to import the data i need to know the cell range
of this data table.
I.e what the last row of data is and the last column that has data in
it.
Does anyone have any code that does something similar? My guess is i
have to do something like thefollowing to enable python to read xl?
import win32com.client
working_dir = '//c:/temp/'
xl = win32com.client.Dispatch("Excel.Application")
xl.Visible = 1 #open MS Excel
xl.Workbooks.Open('%s/working_output.xls' % (working_dir))
then code to find the cell ranges
Any help here is much appreciated
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Using a proxy with urllib2
I'm trying to use a proxy server with urllib2.
So I have managed to get it to work by setting the environment
variable:
export HTTP_PROXY=127.0.0.1:8081
But I wanted to set it from the code. However, this does not set the proxy:
httpproxy = '127.0.0.1:3129'
proxy_support = urllib2.ProxyHandler({"http":"http://"; + httpproxy})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
I'm using it from a web.py URL handler file, not sure if it matters.
I have another question though. It seems that using either of the
methods above, the proxy will be global. What if I want to use
a proxy with one site, but not with another site? Or even use a
proxy for some URLs but not others? The proxy having to be global
is really not convenient. Is there any way to do per-fetch proxy?
--
http://mail.python.org/mailman/listinfo/python-list
RE: docstrings style question
> On Behalf Of Steve Brown > What do you think? I think that comments are for maintainers, and docstrings are for users. Some of the things I use comments for: * Visually separate classes (using a syntax-highlighting editor) * Explain algorithm choices * Explain bug fixes so I don't later "fix" code back to the buggy version Some of the things I use docstrings for: * Describe interface (inputs/outputs) * Sample usage I personally don't use doctests, but that's one more use of docstrings. Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
RE: Win32com and Excel
> On Behalf Of Mike P > Does anyone have any code that does something similar? My > guess is i have to do something like thefollowing to enable > python to read xl? I think that what you want is UsedRange for row in sheet.UsedRange.Value: ... Regards, Ryan Ginstrom -- http://mail.python.org/mailman/listinfo/python-list
Re: Win32com and Excel
On Jan 10, 8:21 pm, Mike P <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I currently have an excel table (1 table each time) that has differing
> number of rows and differing number of columns each time, for another
> program i use (SPSS) to import the data i need to know the cell range
> of this data table.
SPSS is clever enough to be able to read an XLS file, but needs to be
told a precise range of cells, and can't be told "all the cells in the
worksheet"?
> I.e what the last row of data is and the last column that has data in
> it.
>
> Does anyone have any code that does something similar? My guess is i
> have to do something like thefollowing to enable python to read xl?
No, you don't have to something like that at all. See below.
>
> import win32com.client
> working_dir = '//c:/temp/'
> xl = win32com.client.Dispatch("Excel.Application")
> xl.Visible = 1 #open MS Excel
> xl.Workbooks.Open('%s/working_output.xls' % (working_dir))
>
> then code to find the cell ranges
>
> Any help here is much appreciated
>
Assuming that you have only one worksheet in the workbook, the
following will do the trick. Otherwise you'll need book.nsheets plus a
peep at the documentation.
>>> def get_sheet_size(xl_file_name, sheet_index=0):
... import xlrd
... book = xlrd.open_workbook(xl_file_name)
... sheet = book.sheet_by_index(sheet_index)
... return sheet.nrows, sheet.ncols
...
>>> get_sheet_size('sjm1.xls')
(8, 3)
>>>
http://pypi.python.org/pypi/xlrd
HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list
Import of cStringIO failing with "undefined symbol: PyObject_SelfIter" on python-2.3.3-88.9
I am importing cStringIO module in my PythonC++ embedded program. The import is failing with the following error: ImportError: /usr/lib/python2.3/lib-dynload/cStringIO.so: undefined symbol: PyObject_SelfIter I have python-2.3.3-88.9.x86 installed on my machine. Why is this error coming? how can I resolve this undefined symbol? Do I need to import anything before this? -- http://mail.python.org/mailman/listinfo/python-list
Re: docstrings style question
Russ P. wrote:
> On Jan 9, 9:47 pm, "Steve Brown" <[EMAIL PROTECTED]> wrote:
>> I've got a series of modules which look like this:
>>
>> #
>> #
>> # Temperature Sense Test
>> #
>> #
>> class Test3(ar_test.AR_TEST):
>> """Temperature Sense Test"""
>>
>> I don't like the duplicated information: But the comment is attractive,
>> and the docstring self.__doc__ is already in use in the test log. I've
>> read that all modules and classes should have docstrings, but I don't
>> really have anything else to say, and each module contains only one
>> class. I don't think that
>>
>> """Temperature Sense Test"""
>> class Test3(ar_test.AR_TEST):
>> """Temperature Sense Test"""
>>
>> would be a real improvement.
>>
>> What do you think?
It's still duplicated information.
> I tend to be a bit skimpy with one-line comments for classes and
> methods, but I think a more complete (""" style) comment is often
> appropriate for the top of the file.
>
> I'm sure you can think of more to say than "Temperature Sense Test."
exactly my opinion
> What temperature? What kind of temperature sensor? What kind of test
> is it, and why are you doing it? That may all be obvious in context,
> but you've provided no context in your post. Also, if the module is of
> any significant size, you might want to provide a clue about who wrote
> it. Then, if someone has a question about it later, they will know who
> to ask.
I tend to mention the main use cases for test classes (especially) and also
a "human readable" description of what can happen (forgive me the missing
line breaks). Something like this:
class Test3(ar_test.AR_TEST):
"""Temperature Sense Test.
This class assures that the connection to the hardware sensor can be
established. It also checks a reference sensor that always reports a
certain value so that one can be sure correct data values are reported.
"""
hth
martin
--
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
Rebuild list of objects with redundancies on objects' attribute
Hi there I have a list of dummy objects which have the attributes 'location', 'name', 'gender'. Now I want to rebuild this list in order to avoid redundancies on objects with the same 'location'. Example: #-- class Dummy: pass a = Dummy() a.location = 'tokio' a.name = 'john' a.gender = 'm' b = Dummy() b.location = 'tokio' b.name = 'peter' b.gender = 'm' c = Dummy() c.location = 'madrid' c.name = 'susan' c.gender = 'f' d = Dummy() d.location = 'london' d.name = 'alex' d.gender = 'm' persons = [a, b, c, d] print "loc name gender" print "-" for obj in persons: print "%s - %s - %s" % (obj.location, obj.name, obj.gender) #-- The output reads like this: loc name gender - tokio john m tokio peter m madrid susan f london alex m I want to create this list (where name and gender are lists): loc name gender - tokio[john, peter] [m] madrid [susan] [f] london [alex][m] How can I do this? Thanks in advance. Nico -- http://mail.python.org/mailman/listinfo/python-list
Re: docstrings style question
"Russ P." <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Jan 9, 11:51 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: >> Steve Brown wrote: >> > I've got a series of modules which look like this: >> >> > # >> > # >> > # Temperature Sense Test >> > # >> > # >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > I don't like the duplicated information: But the comment is attractive, >> > and >> > the docstring self.__doc__ is already in use in the test log. I've read >> > that >> > all modules and classes should have docstrings, but I don't really have >> > anything else to say, and each module contains only one class. I don't >> > think >> > that >> >> > """Temperature Sense Test""" >> > class Test3(ar_test.AR_TEST): >> > """Temperature Sense Test""" >> >> > would be a real improvement. >> >> > What do you think? >> >> since you already seem to cater to your audience (clearly marked >> comments for people browsing the code, brief docstrings for the test >> log), I don't really see why you should change anything. >> >> > I've read that all modules and classes should have docstrings >> >> if nobody's going to read them, there's no reason to add them. don't >> treat generic style advice as dogma. >> >> > > Well, trivial modules certainly don't need much documentation, but he > didn't say they were trivial. I assumed there was more to them then he > showed. All of the complexity is in the test framework. I've been working on paring back the tests to make them simple to understand, create and modify, which is how I've come to this: I'm still trying to remove lines. The test itself is a now a linear script of 20-40 lines, and I'm still working on them. However, it is relatively important to make the documentation right for these simple scripts. The docstring/comment does need to show some embedded dependancies, I just chose one without any. I realise from reading Jeroen Ruigrok van der Werven's comment that I should probably also care what epydoc makes of my doc strings, -- that's an additional constraint. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On 2008-01-09, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I'm pretty new to Python, and even newer to Image/Video processing, > and trying to get started on a project similar to GRL Vienna's laser > marker. I found some sample code here > http://janto.blogspot.com/2006/01/motion-capture-in-python.html, > but after running the code with the included sample input file, it > seems quite slow (1-2 seconds from start to finish to do the 800 by > 600 gif image). > Is there a better way to do color tracking, or is Python just too slow > as an interpreted language to do any effective color tracking? People seem quite obsessed with execution speed of CPU's. I have come to believe that it is only one part of the equation, development time and ease of maintenance or modification is another one, which I believe is much more interesting to perform as fast as possible. 1-2 seconds may be slower than some alternative solution (you could in principle develop custom hardware for it, and do the trick in a few nano-seconds). The question that arises (for me at least) is, how fast can you write, maintain, and modify what you want in that other solution. Suppose you can do color-tracking in 0.5 seconds. So, you gained 1.5 seconds CPU time. Now the question you need to answer for yourself, is how much more worth is your own time compared to the gain in CPU time. If you think they are equal (ie the problem as a whole should be solved as fast as possible, thus the sum of development time + execution time should be as short as possible), you can spend an additional 1.5 seconds development in the alternative solution. Of course, if you do more color-tracking, the differences between alternative solutions become larger, and your custom hardware solution may become a feasible alternative :) In my experience however, differences in CPU execution time are usually meaningless compared to differences in development time. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: help with a problem from school??
Josh wrote: > Hello all I did a Google search and found this site and was hoping someone > could help me with what I am sure is a simple question that I cannot > figure out. Here goes: > > Given a simple straight through switch (SPST) with a supply of > 14V, and the need to simulate its intended load of 14mA, what > would you use to simulate this load? Please show your > calculations used to support your answer. This is a mailing list about the python programming language (http://www.python.org). I'm not quite sure how your question is related to python. You might want to try a mailinglist specific to your problem... martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
-On [20080110 11:46], A.T.Hofkamp ([EMAIL PROTECTED]) wrote: >In my experience however, differences in CPU execution time are usually >meaningless compared to differences in development time. I have to disagree with you to a point. Yes, maintenance of code is important, no denying that. However, if I can calculate N variations of a certain material's properties in an hour and using Python will cut that in half, the number of calculated variations per hour, I will be concerned. This is especially so for people designing, say, optics. If you look at the amount of optimizing designs and calculating the resulting properties and doing this for X iterations in a day it becomes quite painfully obvious that raw CPU execution time *does* matter. 't All varies with what you want, of course... -- Jeroen Ruigrok van der Werven / asmodai イェルーン ラウフロック ヴァン デル ウェルヴェン http://www.in-nomine.org/ | http://www.rangaku.org/ When you have eliminated the impossible, whatever remains, however improbable, must be the truth... -- http://mail.python.org/mailman/listinfo/python-list
Do you know mirror repository of PyUMLGraph, what do you thinks about this tools ?
Hi, I've looked http://www.umlgraph.org/ tools. I think it's great to generate UML Diagram from source code and comment's. I read there are "Python version" of this tools : PyUMLGraph (http://pypi.python.org/pypi/ PyUMLGraph/0.1.10). Unfortunately, repository of this tools is down :( My questions : * do you know a mirror repository of this tools ? * have you used this tools ? What do you thinks about ? I thinks this can be a great tools in agility programming context. Thanks for your informations Stephane -- http://mail.python.org/mailman/listinfo/python-list
Re: Rebuild list of objects with redundancies on objects' attribute
Nico Grubert wrote: > Hi there > > I have a list of dummy objects which have the attributes 'location', > 'name', 'gender'. > Now I want to rebuild this list in order to avoid redundancies on > objects with the same 'location'. > > Example: > > #-- > class Dummy: > pass > > a = Dummy() > a.location = 'tokio' > a.name = 'john' > a.gender = 'm' > > b = Dummy() > b.location = 'tokio' > b.name = 'peter' > b.gender = 'm' > > c = Dummy() > c.location = 'madrid' > c.name = 'susan' > c.gender = 'f' > > d = Dummy() > d.location = 'london' > d.name = 'alex' > d.gender = 'm' > > persons = [a, b, c, d] > > print "loc name gender" > print "-" > for obj in persons: > print "%s - %s - %s" % (obj.location, obj.name, obj.gender) > > #-- > > The output reads like this: > >loc name gender >- >tokio john m >tokio peter m >madrid susan f >london alex m > > I want to create this list (where name and gender are lists): >loc name gender >- >tokio[john, peter] [m] >madrid [susan] [f] >london [alex][m] > > How can I do this? Put the persons into a dictionary using the location as key from collections import defaultdict groups = defaultdict(list) for p in persons: groups[p.location].append(p) Below is a spoiler that uses itertools.groupby(), but you learn more if you try to work it out yourself ;) from itertools import groupby def location(p): return p.location persons.sort(key=location) print "loc name gender" print "-" for loc, group in groupby(persons, key=location): group = list(group) genders = sorted(set(p.gender for p in group)) names = sorted(p.name for p in group) print "%s - %s - %s" % (loc, names, genders) Peter -- http://mail.python.org/mailman/listinfo/python-list
SV: Conventions for dummy name
Torsten Bronger wrote: >Hallöchen! > >Ben Finney writes: > >> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes: >> >>> The underscore is used as "discarded" identifier. So maybe >>> >>> for _ in xrange(10): >>> ... >> >> The problem with the '_' name is that it is already well-known and >> long-used existing convention for an entirely unrelated purpose: >> in the 'gettext' i18n library, the '_' function to get the >> locally-translated version of a text string. > >Right, that's because I've used "__" where not all returning values >are interesing to me such as > >a, b, __ = function_that_returns_three_values(x, y) Variable name "dummy" serves the same purpose, such as: a, b, dummy = function_that_returns_three_values(x, y) According to http://linux.die.net/man/1/pylint it is also possible to use the option --dummy-variables-rgx= to further specify which variable not to report as unused. As far as I can tell, it defaults to '_|dummy'. .david -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
For the most part, I agree with you, which is why I chose Python in the first place. I like quick development. Unfortunately, this is one of those cases where execution time is a factor. Who knows, maybe someone who's done camera vision with Python will come in and say it's just the algorithm in the example that needs work (I'm crossing my fingers that that's the case). -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.7.10
Hello! I'm pleased to announce the 0.7.10 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.10 News and changes: http://sqlobject.org/docs/News.html What's New == News since 0.7.9 * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
Re: Conventions for dummy name
Hallöchen! [EMAIL PROTECTED] writes: > Torsten Bronger wrote: > >> [...] >> >> Right, that's because I've used "__" where not all returning >> values are interesing to me such as >> >> a, b, __ = function_that_returns_three_values(x, y) > > Variable name "dummy" serves the same purpose, such as: > > a, b, dummy = function_that_returns_three_values(x, y) Granted, but my rationale is that "__" is less visible in the source code, so there is more emphasis on the actually interesting variables. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop without variable
erik gartz <[EMAIL PROTECTED]> wrote:
> Hi. I'd like to be able to write a loop such as:
> for i in range(10):
> pass
> but without the i variable. The reason for this is I'm using pylint
> and it complains about the unused variable i. I can achieve the above
> with more lines of code like:
> i = 0
> while (i != 10):
> i += 1
> Is there a concise way to accomplish this without adding extra lines
> of codes? Thanks in advance for your help.
Google for: pylint unused
It pointed me at:
> Question:
> I've a function / method which is a callback where I do not have any
> control on received argument, and pylint is complaining about unused
> arguments. What can I do to avoid those warnings ?
>
> Answer:
> prefix (ui) the callback's name by cb_, as in cb_onclick(...). By doing
> so arguments usage won't be checked. Another solution is to use one of
> the name defined in the "dummy-variables" configuration variable for
> unused argument ("_" and "dummy" by default).
http://www.iaeste.or.at/doc/python2.3-pylint/html/FAQ.html
So it looks like you can use 'dummy' or add any other names you want to the
configuration.
--
http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.8.7
Hello! I'm pleased to announce the 0.8.7 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.7 News and changes: http://sqlobject.org/News.html What's New == News since 0.8.6 * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.9.3
Hello! I'm pleased to announce the 0.9.3 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.3 News and changes: http://sqlobject.org/News.html What's New == Bug Fixes ~ * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use base64 for BLOBs. * MySQLConnection doesn't convert query strings to unicode (but allows to pass unicode query strings if the user build ones). DB URI parameter sqlobject_encoding is no longer used. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
SV: Conventions for dummy name
Torsten Bronger writes: >[EMAIL PROTECTED] writes: > >> Torsten Bronger wrote: >> >>> [...] >>> >>> Right, that's because I've used "__" where not all returning >>> values are interesing to me such as >>> >>> a, b, __ = function_that_returns_three_values(x, y) >> >> Variable name "dummy" serves the same purpose, such as: >> >> a, b, dummy = function_that_returns_three_values(x, y) > >Granted, but my rationale is that "__" is less visible in the source >code, so there is more emphasis on the actually interesting >variables. I guess it's a matter of preference. Personally, I find "dummy" to be more explicit, and hence more readable for those that that will read my code later. YMMV. Regards, .david -- http://mail.python.org/mailman/listinfo/python-list
importing module conflict
Hi, Suppose I've a module named "urllib" and from it I need to import the urllib module from the python standart library. ¿how can I do this? The problem I found is that when I do: import urrlib The imported module is itself, and not the one from the stdlib. Any idea? Thanks a lot. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On Jan 10, 12:04 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > For the most part, I agree with you, which is why I chose Python in > the first place. I like quick development. Unfortunately, this is > one of those cases where execution time is a factor. Who knows, maybe > someone who's done camera vision with Python will come in and say it's > just the algorithm in the example that needs work (I'm crossing my > fingers that that's the case). It would probably be worth reposting your question with a different subject line. Something along the lines of "Image/Video processing performance in Python", and explaining what you actually want to achieve. "Python too slow?" doesn't give enough information - clearly Python is fast enough for many many tasks, since it is so widely used. It also sounds like a troll - so many people who would actually be able to assist you (such as the PIL, pygame and numpy/scipy communities) may have ignored this thread. Cheers, -- Ant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On Jan 10, 3:00 am, Ant <[EMAIL PROTECTED]> wrote: > On Jan 10, 12:04 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> > wrote: > > > For the most part, I agree with you, which is why I chose Python in > > the first place. I like quick development. Unfortunately, this is > > one of those cases where execution time is a factor. Who knows, maybe > > someone who's done camera vision with Python will come in and say it's > > just the algorithm in the example that needs work (I'm crossing my > > fingers that that's the case). > > It would probably be worth reposting your question with a different > subject line. Something along the lines of "Image/Video processing > performance in Python", and explaining what you actually want to > achieve. "Python too slow?" doesn't give enough information - clearly > Python is fast enough for many many tasks, since it is so widely used. > It also sounds like a troll - so many people who would actually be > able to assist you (such as the PIL, pygame and numpy/scipy > communities) may have ignored this thread. > > Cheers, > > -- > Ant. Thanks for the advice. I'll do that now. -- http://mail.python.org/mailman/listinfo/python-list
Re: importing module conflict
Matias Surdi <[EMAIL PROTECTED]> writes: > Suppose I've a module named "urllib" and from it I need to import > the urllib module from the python standart library. What you want is the "absolute import" behaviour, described in PEP 328 http://www.python.org/peps/pep-0328.html> and implemented in Python 2.5 http://docs.python.org/whatsnew/pep-328.html>. -- \ "The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything." -- Aahz | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: importing module conflict
Matias Surdi a écrit : > Hi, > > Suppose I've a module named "urllib" and from it I need to import the > urllib module from the python standart library. > > ¿how can I do this? > > The problem I found is that when I do: > > > import urrlib > > The imported module is itself, and not the one from the stdlib. > > Any idea? Yes : don't name your module 'urllib' !-) Else, you can play with sys.path before importing the std urllib, etc, etc... -- http://mail.python.org/mailman/listinfo/python-list
Embedding python code into text document question.
Dear all, I've written a program that parses a string or file for embedded python commands, executes them and fills in the returned value. The input might look like this: process id: $$return os.getpid()$$ current date: $$return time.ctime()$$ superuser: $$ if os.geteuid(): return "Yes" else: return "No"$$ I've tried several solutions using eval, execfile or compile, but none of those would solve my problem. Does anyone have a solution that works? Any suggestions? Any help will be appreciated :) Regards, Thomas. -- http://mail.python.org/mailman/listinfo/python-list
Image/Video Processing in Python
Hello, I'm trying to work on a project in Python that involves the use of a webcam to track a laser pointer. I found some example code here http://janto.blogspot.com/2006/01/motion-capture-in-python.html, but the problem is that it's quite slow (about a sec to process a 800 by 600 image). Can anyone who has experience with computer vision help me? Are there any existing algorithms for finding a color in an image and plotting its coordinates? It would help me very much. the profile.py output from the example can be found here if anyone's interested http://heightened.files.wordpress.com/2008/01/output.txt -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or PowerShell ?
[EMAIL PROTECTED] wrote: > On Jan 8, 1:57 pm, "Martin P. Hellwig" <[EMAIL PROTECTED]> wrote: >> And adding to that, if you don't care about cross platform anyway, why >> even bother with python? I am sure that MS has tools that can do in a >> point and click kind of way all the things you might encounter. > > I code mostly for Windows users, but I use Python almost exclusively. > Why? > > 1) Python is "free" > 2) Microsoft Visual Studio is very expensive > 3) Python is Open Source > 4) Visual Studio is not Open Source > 5) I can actually take the code from IDLE and refine it for my > purposes if it doesn't suit me. Good luck doing that with practically > anything Microsoft supplies. > 6) With relative ease, I can go cross-platform with my code if > requirements change > > I could go on. There are many good reasons to use Python (or some > other good open source language, like Ruby) even if you just program > for Windows. > > Mike Well if that are your requirements, which are all good ones btw, then you have answered your own question :-) -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
> The best thing about Python is ___. this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding python code into text document question.
On Jan 10, 2:10 pm, Thomas Troeger <[EMAIL PROTECTED]> wrote: > Dear all, > > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) > AST visitor approach: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440629 -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding python code into text document question.
Ok I've written a small example program to clarify matters: [SNIP] #!/usr/bin/python import os, sys, time def template(src, dst, sep): """ Copy file from src to dst, executing embedded python code. """ try: # read template file. f=open(src, "rU") data="".join(f.readlines()) f.close() # find embedded python code and execute it. while True: # find embedded embedded python command. offset=data.find(sep) if offset < 0: break offset2=data.find(sep, offset+1) if offset2 < 0: break cmd=data[offset+len(sep):offset2] # execute command. try: ret="" exec(compile(cmd, '', 'exec')) except: print "error compiling code `%s'." % cmd # substitute command with return value. data=data[:offset]+str(ret)+\ data[offset2+len(sep):] # write translated input. f=open(dst, "w") f.write(data) f.close() except: print "error processing template file `%s'." % src # -- main --- if len(sys.argv) > 2: template(sys.argv[1], sys.argv[2], '$$') [SNIP] This is the example input that works: [SNIP] process id: $$ret=os.getpid()$$ current date: $$ret=time.ctime()$$ superuser: $$ if os.geteuid(): ret="No" else: ret="Yes"$$ [SNIP] Now the `ret= ...' mechanism is not nice, I'd prefer to have a return statement instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: New Tk look (aka Ttk or Tile widgets)
Robert Hicks napisał(a): > Do I have to install something extra to use the new look? I managed to use Tile with Tk 8.4 and Python 2.5. After installing Tile I followed these advices: http://tkinter.unpythonic.net/wiki/UsingTile and used this code: http://tkinter.unpythonic.net/wiki/TileWrapper Actually, I wanted to use Treeview, so I needed to tweak a little bit this code, but it's very simple to do. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
Thanks Caleb. Really liked some points. On Jan 10, 2008 11:20 AM, Caleb <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > > Anything written somewhere that's thorough? Any code body that should > > serve as a reference? > > 1. Don't use tabs (use spaces). > 2. Study "import this" > 3. Use lists and dictionaries as much as you possibly can > 4. Use comprehensions and generators as much as you possibly can > 5. Use the standard library for everything you possibly can > 6. As much as you possibly can, when starting a new project, postpone > setting up classes for everything (start with functions). In some > projects, you might never need the overhead at all. > > It will be difficult to go far wrong regarding style if you do a lot of > what's in this list. This list is not mine. I jotted these points > down, but this information is continually repeated by the actual wise > people (not me) in this newsgroup. > > Caleb > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Rui http://rui.tumblr.com "Rubi? Aquela novela do SBT?" ~ Carla Perez sobre Ruby "Em Python, tudo é objeto, além de lindo e maravilhoso." ~ Caetano Veloso sobre Python -- http://mail.python.org/mailman/listinfo/python-list
Re: New Tk look (aka Ttk or Tile widgets)
2008/1/10, Robert Hicks <[EMAIL PROTECTED]>: > Do I have to install something extra to use the new look? > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list > Tk 8.5 -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: docstrings style question
On Jan 10, 2008 12:47 AM, Steve Brown <[EMAIL PROTECTED]> wrote: > I've got a series of modules which look like this: > > # > # > # Temperature Sense Test > # > # > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > > I don't like the duplicated information: But the comment is attractive, and > the docstring self.__doc__ is already in use in the test log. I've read that > all modules and classes should have docstrings, but I don't really have > anything else to say, and each module contains only one class. I don't think > that > > """Temperature Sense Test""" > class Test3(ar_test.AR_TEST): > """Temperature Sense Test""" > > would be a real improvement. > > What do you think? I recommend a careful reading of PEP 257. You shouldn't waste your time creating (at best) decorative comments, like: # # # Temperature Sense Test # # class Test3(ar_test.AR_TEST): """Temperature Sense Test"" Remember that comments have to maintained along with the rest of the code, so unnecessary ones just create more work for you. Any time you can replace a comment with self-explanatory code, you should. Here's a vast improvement: class TemperatureSenseTester(ar_test.AR_TEST): -- Neil Cerutti <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
New Tk look (aka Ttk or Tile widgets)
Do I have to install something extra to use the new look? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
[EMAIL PROTECTED] wrote: > Anything written somewhere that's thorough? Any code body that should > serve as a reference? 1. Don't use tabs (use spaces). 2. Study "import this" 3. Use lists and dictionaries as much as you possibly can 4. Use comprehensions and generators as much as you possibly can 5. Use the standard library for everything you possibly can 6. As much as you possibly can, when starting a new project, postpone setting up classes for everything (start with functions). In some projects, you might never need the overhead at all. It will be difficult to go far wrong regarding style if you do a lot of what's in this list. This list is not mine. I jotted these points down, but this information is continually repeated by the actual wise people (not me) in this newsgroup. Caleb -- http://mail.python.org/mailman/listinfo/python-list
run shell commands
Hello! :) I'm trying to run shell commands both with os.system() and subprocess.Popen() class. But I can't run aliases or function defined in my .bashrc file, like in the login interactive shell. Can you help me? Maybe have I to add some commands to load the .bashrc? Thanks a lot! :) Ric. -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding python code into text document question.
Thomas Troeger <[EMAIL PROTECTED]> wrote: > I've written a program that parses a string or file for embedded > python commands, executes them and fills in the returned value. > ... > I've tried several solutions using eval, execfile or compile, but > none of those would solve my problem. Does anyone have a solution > that works? Any suggestions? Any help will be appreciated :) Hi, first, to quote the manual [1] > Be aware that the return and yield statements may not be used > outside of function definitions even within the context of code > passed to the exec statement. Once you get rid of those return statements, the first two substitutions could simpy be eval'ed. Conditions and loops can be exec'ed, but you need to capture the output somehow. You could replace sys.stdout with your own StringIO before you exec, and use 'print' instead of 'return' in your templates. Two basic approaches: you eval every substitution by itself [2], or you parse the whole template into one big python chunk, and exec that [3]. [1] http://docs.python.org/ref/exec.html [2] http://blog.ianbicking.org/templating-via-dict-wrappers.html [3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464766 -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding python code into text document question.
On Thu, 10 Jan 2008 14:10:05 +0100, Thomas Troeger wrote: > I've written a program that parses a string or file for embedded python > commands, executes them and fills in the returned value. The input might > look like this: > > process id: $$return os.getpid()$$ > current date: $$return time.ctime()$$ > superuser: $$ > if os.geteuid(): > return "Yes" > else: > return "No"$$ > > I've tried several solutions using eval, execfile or compile, but none > of those would solve my problem. Does anyone have a solution that works? > Any suggestions? Any help will be appreciated :) My suggestion would be: use one of the many already existing templating systems. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Strip lines from files
Francesco Pietra wrote:
> I am posting again as previous identical message had alleged suspicious
> header.
>
> I used successfully script
>
> f=open("prod1-3_no_wat_pop.pdb", "r")
> for line in f:
> line=line.rstrip()
> if "WAT" not in line:
> print line
> f.close()
log = [[line for line in file(filename,'r') if line.find('WAT')=-1] for
filename in filenamelist]
print log
You can populate filenamelist however you like, e.g. with a command-line
wildcard into sys.argv, or with a os.listdir lookup as in
filenamelist = [filename for filename in os.listdir('.') if
filename.find('.pdb.')]
Caleb
--
http://mail.python.org/mailman/listinfo/python-list
Problem with Tkinter.PhotoImage
Hi,
I can only load gif images with Tkinter.PhotoImage and none with BitmapImage.
I tried png, jpg, bmp and xpm and always got this errors :
>>> img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm')
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3206, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3162, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image
file "/home/omer/fgfs/fgsync/map.xpm"
(or _tkinter.TclError: format error in bitmap data with BitmapImage)
I also tried the imageview demo with the bitmaps in Demo/tix/bitmaps and same
result (only works with tix.gif). Sounds weird that tkinter only supports a
non-free format... Am I lacking some packages or config ? I'm on a debian sid
and have the following python packages installed :
libboost-python1.34.1
python
python-central
python-doc
python-imaging
python-imaging-tk
python-minimal
python-mode
python-newt
python-selinux
python-semanage
python-support
python-tk
python2.4
python2.4-doc
python2.4-minimal
thanks,
--
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list
Re: Import module conflict
>Suppose I've a module named "urllib" and from it I need to import the >urllib module from the python standart library. >¿how can I do this? >The problem I found is that when I do: >import urrlib >The imported module is itself, and not the one from the stdlib. >Any idea? Try this: *from stdlib import urllib I am a newbie but this might help * -- http://mail.python.org/mailman/listinfo/python-list
Re: importing module conflict
Ben Finney escribió: > Matias Surdi <[EMAIL PROTECTED]> writes: > >> Suppose I've a module named "urllib" and from it I need to import >> the urllib module from the python standart library. > > What you want is the "absolute import" behaviour, described in PEP 328 > http://www.python.org/peps/pep-0328.html> and implemented in > Python 2.5 http://docs.python.org/whatsnew/pep-328.html>. > Thanks a lot. That was exactly what I was looking for.Excellent. -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO books of official Python docs
In <[EMAIL PROTECTED]> gordyt <[EMAIL PROTECTED]> writes: >Howdy kynnjo, >> Is it possible to buy the official Python docs in book form? If >> so, I'd very much appreciate the name(s) and author(s) of the >> book(s). >I haven't seen them in print form, but you can download PDF's from >here: >http://docs.python.org/download.html Thanks for the link. With the name of the manual on hand I was able to find a printed version of it (ISBN: 0954161785). A mere 144 pages, and for under $15. Swet! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with Tkinter.PhotoImage
Cédric Lucantis wrote: > Hi, > > I can only load gif images with Tkinter.PhotoImage and none with BitmapImage. > I tried png, jpg, bmp and xpm and always got this errors : > That's because Tk only supports the gif format natively. You need to install an additional photo library to support additional images (Tk has an Img extension, and Python Image Library is also very good). -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: New Tk look (aka Ttk or Tile widgets)
On Jan 10, 9:08 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote: > 2008/1/10, Robert Hicks <[EMAIL PROTECTED]>: > > > Do I have to install something extra to use the new look? > > > Robert > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Tk 8.5 > > -- > -- Guilherme H. Polo Goncalves Is that it? I have Tcl and Tk 8.5 installed. Robert -- http://mail.python.org/mailman/listinfo/python-list
ISO Python example projects (like in Perl Cookbook)
I'm looking for "example implementations" of small projects in Python, similar to the ones given at the end of most chapters of The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately, the otherwise excellent Python Cookbook (2nd edition, isbn: 0596007973), by the same publisher (O'Reilly), does not have this great feature.) The subchapters devoted to these small projects (which are called "Program"s in the book), each consists of a description of the task, a discussion of the relevant design considerations, and one or more illustrative implementations. As such, these programs are larger and more complex than the typical "recipe" in the book, but are still short enough to be read and understood in a few minutes. I find the study of such small programs invaluable when learning a new language. Does anyone know of a source of similar material for Python? TIA! kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
PIL rotate : Rotate By Shear / Paeth Rotation?
I've been doing some image rotation with PIL and comparing the images with imagemagick's convert -rotate output. Imagemagick uses an RBS / Paeth rotation algorithm that appears to give better results than PIL's rotate method. However, I love PIL and don't want to have to shell out to imagemagick or use it's python bindings if I can stay with my beloved Python Imaging Library. Has anyone implemented RBS using PIL? Anyone looked at doing it and backed away? -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO Python example projects (like in Perl Cookbook)
On Jan 10, 10:13 am, kj <[EMAIL PROTECTED]> wrote:
> I'm looking for "example implementations" of small projects in
> Python, similar to the ones given at the end of most chapters of
> The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately,
> the otherwise excellent Python Cookbook (2nd edition, isbn:
> 0596007973), by the same publisher (O'Reilly), does not have this
> great feature.)
>
> The subchapters devoted to these small projects (which are called
> "Program"s in the book), each consists of a description of the
> task, a discussion of the relevant design considerations, and one
> or more illustrative implementations. As such, these programs are
> larger and more complex than the typical "recipe" in the book, but
> are still short enough to be read and understood in a few minutes.
>
> I find the study of such small programs invaluable when learning
> a new language.
>
> Does anyone know of a source of similar material for Python?
>
> TIA!
>
> kynn
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.
I know that Hetland's book, "Beginning Python" has some projects in
the back. Zelle's book ("Python Programming: An Introduction to
Computer Science") has exercises of sorts at the end of each of the
chapters.
Python Programming for the Absolute Beginner walks the reader through
designing some games with the pygame module...and for some involved
reading, I would recommend Lutz's tome, "Programming Python 3rd Ed.",
which has various projects throughout that the author goes into in
depth.
I've seen tutorials of varying worth on devshed.com and good articles
on IBM's site as well.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
urllib2 rate limiting
Hello list, I want to limit the download speed when using urllib2. In particular, having several parallel downloads, I want to make sure that their total speed doesn't exceed a maximum value. I can't find a simple way to achieve this. After researching a can try some things but I'm stuck on the details: 1) Can I overload some method in _socket.py to achieve this, and perhaps make this generic enough to work even with other libraries than urllib2? 2) There is the urllib.urlretrieve() function which accepts a reporthook parameter. Perhaps I can have reporthook to increment a global counter and sleep as necessary when a threshold is reached. However there is not something similar in urllib2. Isn't urllib2 supposed to be a superset of urllib in functionality? Why there is no reporthook parameter in any of urllib2's functions? Moreover, even the existing way reporthook can be used doesn't seem so right: reporthook(blocknum, bs, size) is always called with bs=8K even for the last block, and sometimes (blocknum*bs > size) is possible, if the server sends wrong Content-Lentgth HTTP headers. 3) Perhaps I can use filehandle.read(1024) and manually read as many chunks of data as I need. However I think this would generally be inefficient and I'm not sure how it would work because of internal buffering of urllib2. So how do you think I can achieve rate limiting in urllib2? Thanks in advance, Dimitris P.S. And something simpler: How can I disallow urllib2 to follow redirections to foreign hosts? -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLObject 0.9.3
On Jan 10, 6:38 am, Oleg Broytmann <[EMAIL PROTECTED]> wrote: > Hello! > > I'm pleased to announce the 0.9.3 release of SQLObject. > > What is SQLObject > = > > SQLObject is an object-relational mapper. Your database tables are described > as classes, and rows are instances of those classes. SQLObject is meant to be > easy to use and quick to get started with. > > SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and > Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also > known as SAPDB). > > Where is SQLObject > == > > Site:http://sqlobject.org > > Development:http://sqlobject.org/devel/ > > Mailing list:https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss > > Archives:http://news.gmane.org/gmane.comp.python.sqlobject > > Download:http://cheeseshop.python.org/pypi/SQLObject/0.9.3 > > News and changes:http://sqlobject.org/News.html > > What's New > == > > Bug Fixes > ~ > > * With PySQLite2 do not use encode()/decode() from PySQLite1 - always use > base64 for BLOBs. > > * MySQLConnection doesn't convert query strings to unicode (but allows to > pass unicode query strings if the user build ones). DB URI parameter > sqlobject_encoding is no longer used. > > For a more complete list, please see the news:http://sqlobject.org/News.html > > Oleg. > -- > Oleg Broytmannhttp://phd.pp.ru/ [EMAIL PROTECTED] >Programmers don't die, they just GOSUB without RETURN. I've been wondering about this for a while...Do all three versions (0.9.3, 0.8.7, 0.7.10) work the same? The website seems to only have docs for the 0.9 version. Do you maintain and update the 3 versions for backwards compatibility? Just curious. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO Python example projects (like in Perl Cookbook)
Have a look at Dive into Python by Mark Pilgrim. It is available for free here http://www.diveintopython.org/. Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: run shell commands
On Jan 10, 2008 9:24 AM, Riccardo Maria Bianchi <[EMAIL PROTECTED]> wrote: > > Hello! :) > > I'm trying to run shell commands both with os.system() and > subprocess.Popen() class. > > But I can't run aliases or function defined in my .bashrc file, like in > the login interactive shell. > > Can you help me? > Maybe have I to add some commands to load the .bashrc? > > Thanks a lot! :) > > Ric. > > -- > http://mail.python.org/mailman/listinfo/python-list > you'd need to run an instance of the shell from python and probably as a login shell so that it pulls in .bashrc. so you'd need a command line like: /bin/bash -l -c "shell commands to run go here" if you want to feed more commands to bash, then use -s. It will read commands from standard input, which you would feed it from python, probably by writing to a Popen pipe. A lot of people also use the pexpect python library to "drive" other programs, especially if you need python to act differently depending upon the output of the called programs. Either way, this list's archives do have some good examples as to the uses and limitations of both subprocess and pexpect. -- Noah Dain "The beatings will continue, until morale improves" - the Management -- http://mail.python.org/mailman/listinfo/python-list
Re: Why my program (using pexpect to switch user) doesn't work well?
On Jan 10, 12:59 am, BlackjadeLin <[EMAIL PROTECTED]> wrote:
> I'm new to python
> I want to write a simple script to switch user,for example,from user_A
> to user_B.
> This my codes:
>
> #!/usr/bin/python
> importpexpect
> import os
> passwd="user_B"
> child =pexpect.spawn('su user_B')
> child.expect('Password:')
> child.sendline(passwd)
> child.expect('$')
> child.close()
>
> Maybe it's the easiest pexpect program.Sometimes ,it work well,it
> switch to user_B successfully .But after i type the command exit to
> switch back to user_A,execute the python script again,it can't work,do
> nothing or just waiting.Why it have different results?
> Sorry for my poor English,and many thanks to all.
>
> Blackjade
When you call child.close() that will kill the child process.
Possibly you want to use the interact() method.
It is not clear from your message if you want to interact with
the child process as if it were your new shell. If you do,
then take a look at the interact() method.
#!/usr/bin/python
importpexpect
import os
passwd="user_B"
child =pexpect.spawn('su user_B')
child.expect('Password:')
child.sendline(passwd)
child.expect('$')
child.interact()
--
Noah
--
http://mail.python.org/mailman/listinfo/python-list
Re: Using a proxy with urllib2
"Jack" <[EMAIL PROTECTED]> writes:
> I'm trying to use a proxy server with urllib2.
> So I have managed to get it to work by setting the environment
> variable:
> export HTTP_PROXY=127.0.0.1:8081
>
> But I wanted to set it from the code. However, this does not set the proxy:
> httpproxy = '127.0.0.1:3129'
> proxy_support = urllib2.ProxyHandler({"http":"http://"; + httpproxy})
> opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
> urllib2.install_opener(opener)
Works for me.
How do you know that the proxy is not set?
> I'm using it from a web.py URL handler file, not sure if it matters.
I don't think so.
> I have another question though. It seems that using either of the
> methods above, the proxy will be global. What if I want to use
> a proxy with one site, but not with another site? Or even use a
> proxy for some URLs but not others? The proxy having to be global
> is really not convenient. Is there any way to do per-fetch proxy?
Try this:
import urllib2
def getopener(proxy=None):
opener = urllib2.build_opener(urllib2.HTTPHandler)
if proxy:
proxy_support = urllib2.ProxyHandler({"http": "http://"; + proxy})
opener.add_handler(proxy_support)
return opener
def fetchurl(url, opener):
f = opener.open(url)
data = f.read()
f.close()
return data
print fetchurl('http://www.python.org', getopener('127.0.0.1:8081'))
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess "handle is invalid" error
Thomas Heller-2 wrote: > > Grant Edwards schrieb: > > [snip] > >> >> Traceback (most recent call last): >> File "surfedit.py", line 28, in ? >> File "Gnuplot\_Gnuplot.pyc", line 178, in __init__ >> File "Gnuplot\gp_win32.pyc", line 117, in __init__ >> File "subprocess.pyc", line 533, in __init__ >> File "subprocess.pyc", line 607, in _get_handles >> File "subprocess.pyc", line 634, in _make_inheritable >> WindowsError: [Errno 6] The handle is invalid >> >> How does one troubleshoot errors that happen three layers deep >> in the subprocess module? >> > > I think this is a subprocess bug. It is often attributed to py2exe > because > usually developers do never run the script in pythonW.exe instead of > python.exe, > and later build a *windows* program with py2exe (the *windows* program has > no > console, and that triggers the bug). > > [snip] > > I thought that this bug was fixed in Python2.5.1 (the release candidate), > but it seems it wasn't. The bug is at > http://sourceforge.net/tracker/index.php?func=detail&aid=1124861&group_id=5470&atid=105470 > > If all this is correct, I hope that someone adds a section to the py2exe > wiki; > and reopens the above bug report. > > Thomas > I've been bitten by this same bug in 2.5.1, and the bug you linked to (which is now @ http://bugs.python.org/issue1124861) is still marked as fixed. I've tried to reopen it but it seems only the reporter (or some "admin" user) is able to do it. -- View this message in context: http://www.nabble.com/subprocess-%22handle-is-invalid%22-error-tp10060967p14740517.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
A.T.Hofkamp wrote: > Now the question you need to answer for yourself, is how much more worth is > your own time compared to the gain in CPU time. If you think they are equal > (ie > the problem as a whole should be solved as fast as possible, thus the sum of > development time + execution time should be as short as possible), you can > spend an additional 1.5 seconds development in the alternative solution. so you only run your programs once? -- http://mail.python.org/mailman/listinfo/python-list
What is "lambda x=x : ... " ?
I'm reading this page: http://www.ps.uni-sb.de/~duchier/python/continuations.html and I've found a strange usage of lambda: Now, CPS would transform the baz function above into: def baz(x,y,c): mul(2,x,lambda v,y=y,c=c: add(v,y,c)) ### What does "y=y" and "c=c" mean in the lambda function? I thought it bounds the outer variables, so I experimented a little bit: # x = 3 y = lambda x=x : x+10 print y(2) ## It prints 12, so it doesn't bind the variable in the outer scope. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 rate limiting
Dimitrios Apostolou <[EMAIL PROTECTED]> writes: > P.S. And something simpler: How can I disallow urllib2 to follow > redirections to foreign hosts? You need to subclass `urllib2.HTTPRedirectHandler`, override `http_error_301` and `http_error_302` methods and throw `urllib2.HTTPError` exception. http://diveintopython.org/http_web_services/redirects.html HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Collecting Rich Data Structures for students
On Jan 10, 1:01 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Wed, 9 Jan 2008 15:05:25 -0800 (PST), "[EMAIL PROTECTED]" > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > Sometimes we spare the students (whomever they may be) this added > > step and just hand them a dictionary of lists or whatever. We > > may not be teaching parsing in this class, but chemistry, and > > having the info in the Periodic Table in a Pythondatastructure > > maybe simply be the most relevant place to start. > > In this particular example, I'd probably suggest stuffing thedata > into an SQLite3 database file... Searching on name, symbol, weight, etc. > would be much easier then trying to dig through a nested dictionary. > > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ That's not a bad idea. We might see people passing ZODBs around more too, as 'import zodb' in IDLE or whatever is increasingly the style, vs. some megabundle you have to install. Think of Zope as another site-package. The advantage of just passing .py files around, among XO users for example, is the periodicTable.py's contents are directly eyeballable as ascii/unicode text, vs. stuffed into a wrapper. I think what I'm getting from this fruitful discussion is the different role of amalgamator-distributors, and Sayid or Kate as classroom teachers, just trying to get on with the lesson and having no time for computer science topics. XML or YAML also make plenty of sense, for the more generic distributor type operations. Speaking only for myself, I appreciated some of the pointers to APIs. Over on edu-sig, we've been talking a lot about the 3rd party module for accessing imdb information -- not a screen scraper. Given xml-rpc, there's really no limit on the number of lightweight APIs we might see. How about CIA World Factbook? Too boring maybe, but it's already going out on the XOs, or some of them, just because it's relatively up to date. Could be imported as Python module too -- maybe that work has already been done? Kirby -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
> What does "y=y" and "c=c" mean in the lambda function? the same thing it does in a function definition: def myfunct(a, b=42, y=3.141): pass > # > x = 3 > y = lambda x=x : x+10 > > print y(2) > ## > > It prints 12, so it doesn't bind the variable in the outer scope. You're mostly correct, as it does pull it out of the local context. Try x = 3 y = lambda x=x: x+10 print y(2) print y() to get "12" then "13" back. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO Python example projects (like in Perl Cookbook)
On Jan 10, 11:13 am, kj <[EMAIL PROTECTED]> wrote: > I'm looking for "example implementations" of small projects in > Python, similar to the ones given at the end of most chapters of > The Perl Cookbook (2nd edition, isbn: 0596003137). (Unfortunately, > the otherwise excellent Python Cookbook (2nd edition, isbn: > 0596007973), by the same publisher (O'Reilly), does not have this > great feature.) > > The subchapters devoted to these small projects (which are called > "Program"s in the book), each consists of a description of the > task, a discussion of the relevant design considerations, and one > or more illustrative implementations. As such, these programs are > larger and more complex than the typical "recipe" in the book, but > are still short enough to be read and understood in a few minutes. > > I find the study of such small programs invaluable when learning > a new language. > > Does anyone know of a source of similar material for Python? > > TIA! > > kynn > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. http://pleac.sourceforge.net/pleac_python/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
I've figured it out, it is default argument. print y() gives 13 as result. It's a bit evil though. I hope this post will be useful some newbie like i'm now someday :) On Jan 10, 7:25 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > I'm reading this > page:http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > # > x = 3 > y = lambda x=x : x+10 > > print y(2) > ## > > It prints 12, so it doesn't bind the variable in the outer scope. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
[EMAIL PROTECTED] wrote: > > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ### > > What does "y=y" and "c=c" mean in the lambda function? they bind the argument "y" to the *object* currently referred to by the outer "y" variable. for example, y = 10 f = lambda y=y: return y y = 11 calling f() will return 10 no matter what the outer "y" is set to. in contrast, if you do y = 10 f = lambda: y y = 11 calling f() will return whatever "y" is set to at the time of the call. or in other words, default arguments bind to values, free variables bind to names. > I thought it bounds the outer variables, so I experimented a little > bit: > > # > x = 3 > y = lambda x=x : x+10 > > print y(2) > ## > > It prints 12, so it doesn't bind the variable in the outer scope. it does, but you're overriding the bound value by passing in a value. try: x = 3 y = lambda x=x : x+10 y() x = 10 y() instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
On Thu, 10 Jan 2008 10:25:27 -0800 (PST) "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > I'm reading this page: > http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ### > > What does "y=y" and "c=c" mean in the lambda function? Older versions of python didn't make variables in an outer scope visible in the inner scope. This was the standard idiom to work around that. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
You're talking about syntax from the bad old days when the scope rules were different. If not too archeological for your tastes, download and boot a 1.5 and see what happens. Less empirically, here're some key references: http://www.python.org/doc/2.2.3/whatsnew/node9.html http://www.python.org/dev/peps/pep-0227/ The change came in 2.2 with from __future__ support in 2.1. Kirby 4D On Jan 10, 11:25 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > I'm reading this > page:http://www.ps.uni-sb.de/~duchier/python/continuations.html > and I've found a strange usage of lambda: > > > Now, CPS would transform the baz function above into: > > def baz(x,y,c): > mul(2,x,lambda v,y=y,c=c: add(v,y,c)) > > ### > > What does "y=y" and "c=c" mean in the lambda function? > I thought it bounds the outer variables, so I experimented a little > bit: > > # > x = 3 > y = lambda x=x : x+10 > > print y(2) > ## > > It prints 12, so it doesn't bind the variable in the outer scope. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
Mike Meyer wrote: >> What does "y=y" and "c=c" mean in the lambda function? > > Older versions of python didn't make variables in an outer scope > visible in the inner scope. This was the standard idiom to work > around that. lexically scoped free variables and object binding are two different things, and have different semantics. the former does not always replace the latter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On Jan 10, 3:37 am, Bruno Desthuilliers wrote: > I fail to see how the existence of JIT compilers in some Java VM changes > anything to the fact that both Java (by language specification) and > CPython use the byte-code/VM scheme. Because these "some Java VMs" with JIT compilers are the de facto standard used by millions; the spec is pretty much irrelevant (unless you're a compiler writer or language theorist). George -- http://mail.python.org/mailman/listinfo/python-list
Persistent HTTP Connections with Python?
Hello All, I am trying to write a python script to talk to an xml-based stock feed service. They are telling me that I must connect and login, and then "issue refresh requests" to fetch the data. This sounds a lot (to me) like HTTP 1.1 persistent connections. Can I do that with the urllib functions, or do I need to use the httplib functions for this kind of work. Pointers and/or sample code would be much appreciated. Thanks! -scott -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with Tkinter.PhotoImage
Cédric Lucantis wrote:
> I can only load gif images with Tkinter.PhotoImage and none with BitmapImage.
> I tried png, jpg, bmp and xpm and always got this errors :
>
img = Tkinter.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm')
> Traceback (most recent call last):
> File "", line 1, in ?
> File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3206, in __init__
> Image.__init__(self, 'photo', name, cnf, master, **kw)
> File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 3162, in __init__
> self.tk.call(('image', 'create', imgtype, name,) + options)
> _tkinter.TclError: couldn't recognize data in image
> file "/home/omer/fgfs/fgsync/map.xpm"
to add to Kevin's reply, you seem to have a properly configured PIL on
your machine:
> python-imaging
> python-imaging-tk
which means that you could try replacing Tkinter.PhotoImage with
from PIL import ImageTk
img = ImageTk.PhotoImage(file='/home/omer/fgfs/fgsync/map.xpm')
(PIL's XPM support isn't 100% perfect though; if it looks like crap, try
using PNG or GIF or some other not quite as silly format...)
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
On Thu, 10 Jan 2008 19:59:23 +0100 Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Mike Meyer wrote: > >> What does "y=y" and "c=c" mean in the lambda function? > > > > Older versions of python didn't make variables in an outer scope > > visible in the inner scope. This was the standard idiom to work > > around that. > lexically scoped free variables and object binding are two different > things, and have different semantics. the former does not always > replace the latter. And? http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop without variable
On Thu, 10 Jan 2008 08:42:16 +0100 Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > Mike Meyer <[EMAIL PROTECTED]> writes: > > It sounds to me like your counter variable actually has meaning, > It depends how the code is written. In the example such as: > > for meaningless_variable in xrange(number_of_attempts): > ... > > the loop variable really has no meaning. Rewriting this code only to > appease pylint is exactly that, it has nothing with making the code > more readable. Except in this case, the variable *has* a meaning. You've just chosen to obfuscate it. > > you've hidden that meaning by giving it the meaningless name "i". If > > you give it a meaningful name, then there's an obvious way to do it > > (which you listed yourself): > > > > while retries_left: > [...] > > This loop contains more code and hence more opportunities for > introducing bugs. For example, if you use "continue" anywhere in the > loop, you will do one retry too much. All correct - and I'm a big fan of minimizing code, as code you don't write has no bugs in it. But you can still show the meaning of this "meaningless" variable: for number_of_attempts in xrange(maximum_attempts): Of course, the OP's request is a better solution: since he doesn't actually need the variable, removing it completely means there's one less variable, which is one less thing you can set to the wrong value. http://www.mired.org/consulting.html Independent Network/Unix/Perforce consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is "lambda x=x : ... " ?
Mike Meyer wrote: What does "y=y" and "c=c" mean in the lambda function? >>> >>> Older versions of python didn't make variables in an outer scope >>> visible in the inner scope. This was the standard idiom to work >>> around that. >>> >> lexically scoped free variables and object binding are two different >> things, and have different semantics. the former does not always >> replace the latter. > > And? and what? it's not the same thing. the "newer" idiom only replaces the "older" idiom under certain circumstances (such as in the OP's first example, but *not* in his second example). -- http://mail.python.org/mailman/listinfo/python-list
XML+Logs to Latex. XSLT?
Hi! I'm thinking about implementing a script in Python to do this task. I have a XML log and logs from other programs. My aim is to do a report about all this information. I'm thinking in using Python to transform the plain logs to XML and combine them with the XML document I have and later use some kind of XSLT to transform the whole XML document to Latex. What do you think about that? I have not worked with XSLT before and I don't know if this would be a correct use. How will you do the job? -- Florencio Cano Gabarda -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > And the reference implementation of Python (CPython) is not > interpreted, it's compiled to byte-code, which is then executed by a VM > (just like Java). Ed Jensen a écrit : > Wow, this is pretty misleading. Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: >Ho yes ??? Why so, please ? Care to point to anything *wrong* in the >above statement ? Python's byte-code interpreter is not "just like" Java's virtual machine. You're deliberately trying to mislead people into thinking Python performs similarily to Java. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] [EMAIL PROTECTED] -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
Re: XML+Logs to Latex. XSLT?
Florencio Cano wrote: > I'm thinking about implementing a script in Python to do this task. I > have a XML log and logs from other programs. My aim is to do a report > about all this information. I'm thinking in using Python to transform > the plain logs to XML and combine them with the XML document I have > and later use some kind of XSLT to transform the whole XML document to > Latex. What do you think about that? I have not worked with XSLT > before and I don't know if this would be a correct use. > How will you do the job? why not do it all in Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 rate limiting
On Thu, 10 Jan 2008, Rob Wolfe wrote: > Dimitrios Apostolou <[EMAIL PROTECTED]> writes: > >> P.S. And something simpler: How can I disallow urllib2 to follow >> redirections to foreign hosts? > > You need to subclass `urllib2.HTTPRedirectHandler`, override > `http_error_301` and `http_error_302` methods and throw > `urllib2.HTTPError` exception. Thanks! I think for my case it's better to override redirect_request method, and return a Request only in case the redirection goes to the same site. Just another question, because I can't find in the docs the meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I get redirected to (the 'Location:' HTTP header?), should I check the hdrs parameter or there is a better way? Thanks, Dimitris > > http://diveintopython.org/http_web_services/redirects.html > > HTH, > Rob > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: XML+Logs to Latex. XSLT?
2008/1/10, Fredrik Lundh <[EMAIL PROTECTED]>: > Florencio Cano wrote: > > > I'm thinking about implementing a script in Python to do this task. I > > have a XML log and logs from other programs. My aim is to do a report > > about all this information. I'm thinking in using Python to transform > > the plain logs to XML and combine them with the XML document I have > > and later use some kind of XSLT to transform the whole XML document to > > Latex. What do you think about that? I have not worked with XSLT > > before and I don't know if this would be a correct use. > > How will you do the job? > > why not do it all in Python? Yes. For sure. I though XSLT was something like XML not other "language" and that Python will have any library that uses XSLT to do transformation...but, what you suggest is: - First process the XML document with Python (sax?) and do the first Latex document. - Second process each log with Python and insert the information in the Latex document created in first step. Do you think this approach is the best? Fastest, clearest, more maintenable? Is this the way you will do it? It seems good for me but I would like to do this properly. -- Florencio Cano Gabarda -- http://mail.python.org/mailman/listinfo/python-list
open excel file while it is being used.
Hi,
I have a python program that constantly updates an excel spreadsheet.
I would like to be able to view its updates while using excel to edit
other excel files. Below are the test codes I have:
--
from time import sleep
import win32com.client as w32c
def test():
w32c.pythoncom.CoInitialize()
print w32c.pythoncom._GetInterfaceCount()
app1 = w32c.Dispatch("Excel.Application")
#app1.Visible=False
#app1.Interactive = False
wb=app1.Workbooks.Open("c:\\temp\\Book1.xls")
sleep(3)
sh=wb.Sheets("Sheet1")
sh.Cells(2,1).Value = "Hello, world!"
sh = None
wb.Save()
wb = None
app1 = None
w32c.pythoncom.CoUninitialize()
print w32c.pythoncom._GetInterfaceCount()
-
If the user just looks at the file then it's fine, but if the user
double clicks one cell, which will have a cursor flashing in the cell,
then it will lead to a crash of the program with error: "Call was
rejected by callee." I can make the program keep trying to access the
file, but if the user doesn't make the flashing cursor disappear, the
program will wait forever!
I know excel has the fuction such that when a user is accessing a file
and other users open that file, it will prompt for options of opening
it as read-only or sending notification. I have been trying to
implement that in the program, but don't know how.
So, any suggestion will be greatly appreciated!
- Barry
--
http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 rate limiting
Dimitrios Apostolou <[EMAIL PROTECTED]> writes: > On Thu, 10 Jan 2008, Rob Wolfe wrote: > >> Dimitrios Apostolou <[EMAIL PROTECTED]> writes: >> >>> P.S. And something simpler: How can I disallow urllib2 to follow >>> redirections to foreign hosts? >> >> You need to subclass `urllib2.HTTPRedirectHandler`, override >> `http_error_301` and `http_error_302` methods and throw >> `urllib2.HTTPError` exception. > > Thanks! I think for my case it's better to override redirect_request > method, and return a Request only in case the redirection goes to the > same site. Just another question, because I can't find in the docs the > meaning of (req, fp, code, msg, hdrs) parameters. To read the URL I > get redirected to (the 'Location:' HTTP header?), should I check the > hdrs parameter or there is a better way? Well, according to the documentation there is no better way. But I looked into the source code of `urllib2` and it seems that `redirect_request` method takes one more parameter `newurl`, what is probably what you're looking for. ;) Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding python code into text document question.
On Jan 10, 1:10 pm, Thomas Troeger <[EMAIL PROTECTED]>
wrote:
> Dear all,
>
> I've written a program that parses a string or file for embedded python
> commands, executes them and fills in the returned value. The input might
> look like this:
>
> process id: $$return os.getpid()$$
> current date: $$return time.ctime()$$
> superuser: $$
> if os.geteuid():
> return "Yes"
> else:
> return "No"$$
>
> I've tried several solutions using eval, execfile or compile, but none
> of those would solve my problem. Does anyone have a solution that works?
> Any suggestions? Any help will be appreciated :)
>
You could wrap the bits of code in a def statement and then exec it:
>>> print field
return os.getpid()
>>> exec("def field_func():\n" + "".join("%s\n" % line for line in
>>> field.splitlines()))
>>> print field_func()
3904
--
http://mail.python.org/mailman/listinfo/python-list
