lpod-python
I'm trying to use the lpod-python module to programmatically read data from Open Document files. My problem is: i can't download the module from its authors' site, http://download.lpod-project.org/lpod-python/lpod-python-0.9.3.tar.gz. It seems the download site is unavailable, while the main site is working. I also tried to install the module with pip (I read on the site that it's now available), but again, no luck. Do somebody know what's happening to download.lpod-project.org ? It doesn't even ping... Please let me know, thank you very much. Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: A ClientForm Question
Il Fri, 01 Apr 2005 02:36:24 -0800, narke ha scritto: > Does anyone here use ClientForm to handle a HTML form on client side? > > I got a form, within which there is a image control, it direct me to > another page if i use mouse click on it. the code of the form as > below: > > action="CDocZ_MAG.aspx?Stat=DocZoom_DocZoom&&E=29YL53ZJBIEZ&DT=ALB&Pass=&Total=104&Pic=1&o=" > id="ZoomControl1_Form1" onkeydown="JavaScript:Navigation_ie();"> > > ... > > language="javascript" id="ZoomControl1_Imagebutton2" > src="../Images/Btn_GoImage.gif" border="0" /> > > ... > > > > So write below code to 'click' the image button, > > forms = ParseResponse(urlopen(url)) > > form = forms[0] > urlopen(form.click("ZoomControl1:Imagebutton2")) > > unfortunatly, however, when the code run, it just got a page which is > not the one i desired ( i actually wish to get the same page as i > 'click' the button). I guess that is "onclick=" statement cause > something weird, but I do not understand it. And, in the source > containing the form, i found nowhere the Page_ClientValidate() resides. > > What's wrong? > > - > narke Similar problem for me. In the form, i have and i don't know how to click this. urlopen(form.click()) doesn't nothing. UserForm is the name of the form. Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
On 17/12/2010 0.51, Steven D'Aprano wrote: Don't get me wrong... spaghetti code is*bad*. But there are other ways of writing bad code too, and hanging around inside a function long after you've finished is also bad: def function(arg): done = False do_something() if some_condition: result = "finished" done = True if not done: do_something_else() if another_condition: result = "now we're finished" done = True if not done: do_yet_more_work() if third_condition: result = "finished this time for sure" done = True if not done: for i in range(100): if not done: do_something_small() if yet_another_condition: result = "finally done!" done = True return result It's far more complicated than it need be, and does*lots* of unnecessary work. This can be written more simply and efficiently as: def function(arg): do_something() if some_condition: return "finished" do_something_else() if another_condition: return "now we're finished" do_yet_more_work() if third_condition: return "finished this time for sure" for i in range(100): do_something_small() if yet_another_condition: return "finally done!" I agree to your point, but I'm afraid you chose a wrong example (AFAIK, and that's not much). Sure, the second version of function(arg) is much more readable, but why do you think the first one would do "*lots* of unnecessary work"? All the overhead in that function would be: if some_condition, three IF tests, and you know that's NOT a lot! if no conditions were met, (worst case) the first version would return an exception (unless result was globally defined) while the second would happily return None. Apart from this, the overhead in the first one would amount to one million IF tests, again not a lot these days. I don't think I would rewrite that function, if I found it written in the first way... I don't mean that the fist example is better, just I'm sure you could imagine a more compelling proof of your concept. Maybe there's something I don't know... in that case, please enlighten me! Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: If/then style question
I'd bet you would stress your point Steven! But you don't need to persuade me, I do already agree. I just meant to say that, when the advantage is little, there's no need to rewrite a working function. And that with modern CPUs, if tests take so little time, that even some redundant one is not so much of a nuisance. in your working example, the "payload" is just a couple of integer calculations, that take very little time too. So the overhead due to redundant if tests does show clearly. And also in that not-really-real situation, 60% overhead just meant less than 3 seconds. Just for the sake of discussion, I tried to give both functions some plough to pull, and a worst-case situation too: >>> t1 = Timer('for x in range(100): print func1(0),', ... 'from __main__ import func1') >>> >>> t2 = Timer('for x in range(100): print func2(0),', ... 'from __main__ import func2') >>> >>> min(t1.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 53.011015366479114 >>> min(t2.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 47.55442856564332 that accounts for a scant 11% overhead, on more than one million tests per cycle. That said, let's make really clear that I would heartily prefer func2 to func1, based both on readability and speed. Thank you for having spent some time playing with me! Francesco On 19/12/2010 1.05, Steven D'Aprano wrote: Well, let's try it with a working (albeit contrived) example. This is just an example -- obviously I wouldn't write the function like this in real life, I'd use a while loop, but to illustrate the issue it will do. def func1(n): result = -1 done = False n = (n+1)//2 if n%2 == 1: result = n done = True if not done: n = (n+1)//2 if n%2 == 1: result = n done = True if not done: n = (n+1)//2 if n%2 == 1: result = n done = True if not done: for i in range(100): if not done: n = (n+1)//2 if n%2 == 1: result = n done = True return result def func2(n): n = (n+1)//2 if n%2 == 1: return n n = (n+1)//2 if n%2 == 1: return n n = (n+1)//2 if n%2 == 1: return n for i in range(100): n = (n+1)//2 if n%2 == 1: return n return -1 Not only is the second far more readable that the first, but it's also significantly faster: from timeit import Timer t1 = Timer('for i in range(20): x = func1(i)', ... 'from __main__ import func1') t2 = Timer('for i in range(20): x = func2(i)', ... 'from __main__ import func2') min(t1.repeat(number=10, repeat=5)) 7.3219029903411865 min(t2.repeat(number=10, repeat=5)) 4.530779838562012 The first function does approximately 60% more work than the first, all of it unnecessary overhead. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
hehehehehehe... On 17/12/2010 2.01, Steven D'Aprano wrote: On Thu, 16 Dec 2010 23:34:21 +, BartC wrote: In terms of a more realistic function (admittedly still a little contrived, as the loop would be written differently), I tried this: def p2(n): p=1 while True: if n<=p: return p p<<=1 return 0 for i in xrange(100): x=p2(i) p2() calculates the smallest power of 2>= it's operand. Using while True as shown, it took 3.4 seconds. Using While 1, it took 2.6 seconds (Python 2.5). Right. And a saving of 0.8 microseconds per iteration is a micro- optimization which is likely to be invisible in any real situation. I mean, yes, you saved almost an entire second. Wow. Save another 179 of them and you'll almost have enough time to make yourself a coffee. Bart, we get it. Nobody denies that the optimization is real, only that it is generally meaningful. Who cares whether it takes 2 seconds or 4 seconds to generate one million results if the rest of the application takes 3 minutes to run? *If* your application is such that saving 0.8 microseconds per iteration actually is useful, AND your loop has to be written as a while True loop, then this *may* be a useful micro-optimization to save 0.8 microseconds per iteration. That's a vanishingly tiny proportion of all code written. If your code happens to meet those conditions, then by all means use "while 1". Or move to Python 3, where "while True" has the same optimization performed. But in general, such micro-optimizations are not terribly useful. If you shave off 1 second off a program that runs in 3 seconds, chances are nobody is even going to notice. Two seconds or three, who cares? Either way, it's too short to do anything else, and not long enough to matter. If you shave off an hour off a program that takes 20 hours, who is going to care? But so long as it doesn't introduce bugs, or make maintenance harder, or add complexity, such micro-optimizations don't harm either. HEY! That was MY argument! ;-)) Newsgroups: comp.lang.python Subject: Re: If/then style question Date: Tue, 21 Dec 2010 20:54:02 +0100 I'd bet you would stress your point Steven! But you don't need to persuade me, I do already agree. I just meant to say that, when the advantage is little, there's no need to rewrite a working function. And that with modern CPUs, if tests take so little time, that even some redundant one is not so much of a nuisance. in your working example, the "payload" is just a couple of integer calculations, that take very little time too. So the overhead due to redundant if tests does show clearly. And also in that not-really-real situation, 60% overhead just meant less than 3 seconds. Just for the sake of discussion, I tried to give both functions some plough to pull, and a worst-case situation too: >>> t1 = Timer('for x in range(100): print func1(0),', ... 'from __main__ import func1') >>> >>> t2 = Timer('for x in range(100): print func2(0),', ... 'from __main__ import func2') >>> >>> min(t1.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 53.011015366479114 >>> min(t2.repeat(number=1, repeat=1)) -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 47.55442856564332 that accounts for a scant 11% overhead, on more than one million tests per cycle. That said, let's make really clear that I would heartily prefer func2 to func1, based both on readability and speed. Thank you for having spent some time playing with me! Francesco On 19/12/2010 1.05, Steven D'Aprano wrote: > Well, let's try it with a working (albeit contrived) example. This is > just an example -- obviously I wouldn't write the function like this in > real life, I'd use a while loop, but to illustrate the issue it will do. > > def func1(n): > result = -1 > done = False > n = (n+1)//2 > if n%2 == 1: > result = n > done = True > if not done: > n = (n+1)//2 > if n%2 == 1: > result = n > done = True > if not done: > n = (n+1)//2 > if n%2 == 1: > result = n > done = True > if not done: > for i in range(100): &
python only prints integers
I'm pretty new in Python language. I have a problem with numbers: it seems python doesn't know any more how to count! I get only the down rounded integer 20/8 = 2 8/3=2 I probably changed some option to round the numbers, but I don't remember how. Is there a way to reset the number of digits to default? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: python only prints integers
On 6 Gen, 23:59, Ian wrote: > On Jan 6, 3:49 pm, francesco wrote: > > > I'm pretty new in Python language. I have a problem with numbers: it > > seems python doesn't know any more how to count! > > I get only the down rounded integer > > 20/8 = 2 > > 8/3=2 > > I probably changed some option to round the numbers, but I don't > > remember how. > > Is there a way to reset the number of digits to default? > > In Python 2, the '/' operator performs integer division by default > when both its operands are integers. To change this, either place > this at the top of the file: > > from __future__ import division > > or convert your numbers to floats: > > >>> 20.0 / 8.0 > 2.5 > >>> float(20) / float(8) > > 2.5 > > In Python 3, the '/' operator always performs true division. Thanks to all! Very quick answer! I fixed the problem by using floats. Thanks again -- http://mail.python.org/mailman/listinfo/python-list
EuroPython 2012: Call for Proposal is Open! [Please spread the word]
Hi guys, I'm Francesco and I am writing on behalf of EuroPython Staff (www.europython.eu). We are happy to announce that the Call for Proposals is now officially open! DEADLINE FOR PROPOSALS: MARCH 18TH, 23:59:59 CET For those who have never been at EuroPython (or similar conferences) before, the Call for Proposals is the period in which the organizers ask the community to submit proposals for talks to be held at the conference. Further details about Call for Proposal are online here: http://ep2012.europython.eu/call-for-proposals/ EuroPython is a conference run by the community for the community: the vast majority of talks that are presented at the conference will be proposed, prepared and given by members of the Python community itself. And not only that: the process that selects the best talks among all the proposals will also be public and fully driven by the community: it's called Community Voting, and will begin right after the Call for Proposals ends. CFP: Talks, Hands-On Trainings and Posters -- We're looking for proposals on every aspect of Python: programming from novice to advanced levels, applications and frameworks, or how you have been involved in introducing Python into your organisation. There are three different kind of contribution that you can present at EuroPython: - Regular talk. These are standard "talk with slides", allocated in slots of 45, 60 or 90 minutes, depending on your preference and scheduling constraints. A Q&A session is held at the end of the talk. - Hands-on training. These are advanced training sessions for a smaller audience (10-20 people), to dive into the subject with all details. These sessions are 4-hours long, and the audience will be strongly encouraged to bring a laptop to experiment. They should be prepared with less slides and more source code. - Posters. Posters are a graphical way to describe a project or a technology, printed in large format; posters are exhibited at the conference, can be read at any time by participants, and can be discussed face to face with their authors during the poster session. We will take care of printing the posters too, so don't worry about logistics. More details about Call for Proposal are online here: http://ep2012.europython.eu/call-for-proposals/ Don't wait for the last day --- If possible, please avoid submitting your proposals on the last day. It might sound a strange request, but last year about 80% of the proposals were submitted in the last 72 hours. This creates a few problems for organizers because we can't have a good picture of the size of the conference until that day. Remember that proposals are fully editable at any time, even after the Call for Proposals ends. You just need to login on the website, go to the proposal page (linked from your profile page), and click the Edit button. First-time speakers are especially welcome; EuroPython is a community conference and we are eager to hear about your experience. If you have friends or colleagues who have something valuable to contribute, twist their arms to tell us about it! We are a conference run by the community for the community. Please help to spread the word by distributing this announcement to colleagues, mailing lists, your blog, Web site, and through your social networking connections. All the best, -- Francesco Pallanti - fpalla...@develer.com Develer S.r.l. - http://www.develer.com/ .software .hardware .innovation Tel.: +39 055 3984627 - ext.: 215 -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
On 11 Giu, 11:41, Asen Bozhilov wrote: > Hi all, > I am beginner in Python. What is interesting for me is that Python > interpreter treats in different way dot and square bracket notations. > I am coming from JavaScript where both notations lead prototype chain > lookup. > > In Python it seems square bracket and dot notations lead lookup in > different "store". > > Simple example with dict object: > > d = {"key" : "value"} > > print d["key"] #value > > print d.key #AttributeError > > I found an implementation of dict which uses both notations for its > keys lookup, which I think is stupid idea when obviously both > notations lead different lookup. It will confuse me as a reader of the > code. > > Anyway, I would like to know more about the lookup for key of dict and > lookup for property of any object with dot notation. Any materials and > explanations are highly appreciated. Since python is not javascript ( duh :-), [] and . notations are used for different purposes and, although they share some commonalities as I try to show later in this post, they should not be intermixed without a very good reeason ( and "it's cool" is not a good reason IMO). Broadly speaking, square brackets are used to access element in array, dict, tuples and sequences. The dot nootation is used to get the attributes and methods of instances. User classes - that is the ones you define with the class statement - can implement support for the squared bracket and dot notations: - the expression myinstance[index] is sort of translated into of myinstance.__getitem__(index) - the expression myinstance.myattribute is sort of translated of myinstance.__getattr__("myattribute") Classes also exposes a __dict__ attributes that allows to access to instance attributes and methods using dictionary semantics. That is, myistance.__dict__["myattribute"] should give the same result as myinstance.myattribute. I believe this is because in the beginning class instances actually had a dictionary storing the instance attributes. Nowadays it is more complex than that, I think, but the interface is kept to allow dynamic access to instance contents, although the reccomended way to do it this is getattr(myinstance, "myattribute"). Of course it is only useful to use __dict__ or getattr when the parameter is not a constant string but a variable referring to a string computed at run time ( this is what I mean for 'dynamic access' ). HTH. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Maximize already running tkinter program on invocation
On 27 Lug, 10:18, Steven Kauffmann wrote: > Hi all, > > I have written a small GUI application in python 3.x using the tkinter > module. Program is running fine, but multiple instances of the program > can now be created. I would like to reduce the number of instances of > the program to only 1 instance. I know that this is possible by using > a singleton class. This way it's possible to check if the program is > already running or not. > > When I invoke the program and it detects that the program is already > running, is it then possible to maximize the already running program? > > I can find a lot of examples about singleton classes in python on the > web, but nothing about showing the already running application when 1 > instance of the program already exists. Is there a way to realize this > in python? > > I'm now doing the development on a linux machine, but the final > program should work on Windows. > > Cheers, > > The multiprocesing module could help you in making sure that two instances of the same program are not started ( for instance using multiprocessing.Queue) as well as to signal the already running instance that it sould maximize its window ( for instance using multiprocessing.Queue ). Just make sure that what you use is supoorted on your target operating system(s). However, the integration of any form of inter-process communication with Tkinter main loop is going to be tricky ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any python library that parse c++ source code statically
On 13 Mar, 10:14, kuangye wrote: > Hi, all. I need to generate other programming language source code > from C++ source code for a project. To achieve this, the first step is > to "understand" the c++ source code at least in formally. Thus is > there any library to parse the C++ source code statically. So I can > developer on this library. > > Since the C++ source code is rather simple and regular. I think i can > generate other language representation from C++ source code. The problem is that C++ is a beast of a language and is not easy to find full parsers for it. I've never done it, but sometime I researched possible ways to do it. The best idea I could come with is doing it in 2 steps: - using gcc-xml ( http://www.gccxml.org/HTML/Index.html ) to generate an xml representation of the code - using one of the many xml library for python to read the xml equivalent of the code and then generate the equivalent code in other languages ( where you could use a template engine, but I found that the python built-in string formatting libraries are quite up to the task ). HTH Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
unittest.Testsuite and execution order
Hello! I'm reading the documentation of unittest.TestSuite (Python 2 and 3), but I can't find any explicit sentence stating that TestSuite will honor the order. I can only read that TestSuite can group test cases together. Please blame it on my poor English skills if I'm not interpreting the documentation correctly. My use case: my SUT is split into modules. Besides writing unit tests for each module, I want to write an integration test, and I also need to perform some actions between two calls to the SUT. In my case, the order of the execution is important. Now, the current implementation of TestSuite uses a list, internally, so, today, the order is honored if I create a TestSuite calling addTest() in the proper order, or if I pass a list to the constructor. I've seen examples like this: class MyTestCode(unittest.TestCase): def test_func_1(self): # do something to test func_1 on the SUT sut.func_1() self.assert(...) def perform_intermediate_step(self): # do something between func_1 and func_2 def test_func_2(self): # do something to test func_2 on the SUT sut.func_2() self.assert(...) suite = unittest.TestSuite() suite.addTest(MyTestCode("test_func_1")) suite.addTest(MyTestCode("perform_intermediate_step")) suite.addTest(MyTestCode("test_func_2")) Such an example works, today, since TestSuite uses a list, and addTest() appends to the list. My question is: is this something that I can rely on for the future? I definitely don't want to rely on the current implementation, unless I see it in the documentation. If it's something that I can't rely on for the future, then I'd rather write my test code in a different way. Regards, Francesco P.S.: I strongly believe that there are better ways to implement a test like the one I just described, but what I'm interested in now is whether TestSuite is meant to be future-proof for such a case. -- Francesco Russo The White Rabbit put on his spectacles. 'Where shall I begin, please your Majesty?' he asked. 'Begin at the beginning,' the King said gravely, 'and go on till you come to the end: then stop.' -- https://mail.python.org/mailman/listinfo/python-list
Re: unittest.Testsuite and execution order
On 18/04/18 20:26, Chris Angelico wrote: > On Thu, Apr 19, 2018 at 2:51 AM, Francesco Russo > wrote: >> My use case: my SUT is split into modules. Besides writing unit tests for >> each module, I want to write an integration test, and I also need to >> perform some actions between two calls to the SUT. In my case, the order of >> the execution is important. > > In that case, make these tests into a single test. If you have to do > the steps together to correctly test it, they're not separate tests, > they're separate parts of the same test. Clear, thank you. >> class MyTestCode(unittest.TestCase): >>def test_func_1(self): >> # do something to test func_1 on the SUT >> sut.func_1() >> self.assert(...) >> >>def perform_intermediate_step(self): >> # do something between func_1 and func_2 >> >>def test_func_2(self): >> # do something to test func_2 on the SUT >> sut.func_2() >> self.assert(...) > > This is a bad idea. Each function that starts test_ should be > completely independent. You should be able to run any one of them on > its own (say, if you're trying to figure out why your latest change > caused a test failure), and it should have the same result. > > Make it so that test_func_1 and test_func_2 are completely > independent, and then, if you need a single test that uses both, have > a test that calls on each function. I'm not sure I understand you here. I understood that (besides, or instead of, making an integration test by making those tests into one test, as you wrote above) I could make a test for func_2 making it independent from func_1, for example this way: class MyTestFunc2(unittest.TestCase): def setUp(self): # Prepare preconditions for func_2 def test_func_2(self): sut.func_2() self.assert(...) Such a test case wouldn't even need a test suite. Is this what you meant? >> Such an example works, today, since TestSuite uses a list, and addTest() >> appends to the list. >> My question is: is this something that I can rely on for the future? I >> definitely don't want to rely on the current implementation, unless I see >> it in the documentation. > > I would say no, you can't rely on it. If you can't find it in the > docs, don't assume it's true. Test order randomization can be > controlled with a simple command line flag. > > ChrisA The official "unittest" web pages for Python 2 and 3 say this, for the TestSuite class: *This class represents an aggregation of individual tests cases and test suites* saying nothing about the order. But the docstring of the TestSuite class says: *It will run the individual test cases in the order in which they were added, aggregating the results* Can I consider the docstring an official documentation as well? -- Francesco Russo The White Rabbit put on his spectacles. 'Where shall I begin, please your Majesty?' he asked. 'Begin at the beginning,' the King said gravely, 'and go on till you come to the end: then stop.' -- https://mail.python.org/mailman/listinfo/python-list
I wrote my very basic mkdocs plugin, hoping that it will inspire you to write your owns
I wanted to write mkdocs plugins, so I read the docs (well, at least part of them) and I wrote a very simple, very basic plugin. I called it "Hello dolly", because when I wrote it I was inspired by the (once built-in) WordPress plugin of the same name that teached me the basic of plugin writing for that blog platform. It does a very simple, very basic tasks. In each document, the plugin looks for the specific tag {{dolly}} and replaces it with a random line from the "Hello dolly!" lyrics; I tried to keep the code as simple as possible, so you won't find any unit-testing code and even the search and replace part was done by using the str.replace method instead of using a regular expression. I tried to comment the code whenever possible, but english is not my native language and you're likely to find a lot of grammar mistakes and typos in my comments, but I hope that my code will speak better than my own words. If, like me, you're looking forward writing your own plugin then you might find useful to have a look at it. You'll find it here: https://github.com/fmaida/hello-dolly-mkdocs-plugin If you have any questions, please contact me on GitHub and I'll try to help you. Thank you for your time and best regards -- https://mail.python.org/mailman/listinfo/python-list
Re: What should a decorator do if an attribute already exists?
On 10/05/2016 17:45, Steven D'Aprano wrote: I have a decorator that adds an attribute to the decorated function: def decorate(func): instrument = make_instrument() @functools.wraps(func) def inner(*args): instrument.start() result = func(*args) instrument.finish() return result inner.instrument = instrument return inner The actual nature of the instrumentation isn't important: depending on the decorator, it might count the number of function calls made, how long it takes, count cache hits, or something else. My question is, what should I do if the decorated function already has an instrument attribute? 1. raise an exception? 2. raise a warning, and over-write the attribute? 3. raise a warning, and skip adding the attribute? 4. raise a warning, and rename the existing instrument to something else before writing my own instrument? 5. silently over-write the attribute? I think 5 is clearly wrong, 4 is too difficult, and 3 seems pointless. So I think either 1 or 2 is the right thing to do. Thoughts? CAVEAT: I speak out of utter ignorance, please don't slap me if i'm saying something blatantly stupid... From your example, it seems that you use your instrument only inside your decorator. So I think "instrument" could be a "private variable". What if you called your instrument "__instrument", taking advantage of name mangling? This would, IMHO, solve entirely the name clash problem, and you could even access your instrument from outside, using its "mangled" name. This, of course, leads to another question: what happens to name mangling in a decorator? What will be actually called the variable "__instrument"? And what happens if you want to add another instrument, decorating the target twice? Francesco -- https://mail.python.org/mailman/listinfo/python-list
Re: Arguments for button command via Tkinter?
Il Mon, 31 Oct 2005 06:23:12 -0800, [EMAIL PROTECTED] ha scritto: > And yet the stupidity continues, right after I post this I finnally > find an answer in a google search, It appears the way I seen it is to > create a class for each button and have it call the method within that. > If anyone else has any other ideas please tell. This is how I do it: Supposing I have three buttons b1, b2 and b3, and I want for each button to call the same callback with, as argument, the button itself: def common_callback(button): # callback code here class CallIt(objetc): def __init__(function, *args ): self.function, self.args = function, args def __call__(self, *ignore): self.function(button, *self.args) b1['command']= CallIt(common_callback, b1) b2['command']= CallIt(common_callback, b2) b3['command']= CallIt(common_callback, b3) This way you need only one class (a sort of custom callable) and its instances gets called by Tkinter and in turn calls your callback with the proper arguments. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows - Need to process quotes in string...
Il Mon, 31 Oct 2005 07:18:31 -0800, Ernesto ha scritto: > I'm trying to use a $ delimeter, but it doesn't seem to work. Here is > the code: > > > launchWithoutConsole("devcon.exe",d'$enable > "@USB\VID_0403&PID_6010&MI_00\7&15E4F68&1&"$) > > I want to send the string parameter: > > enable "@USB\VID_0403&PID_6010&MI_00\7&15E4F68&1&" > > to the program devcon. > > The argument itself is a string, but has quotes inside too. I've tried > it many different ways and I keep getting syntax errors. > > Thanks, Use the single quote to delimit the string, so you can use the double quote inside it. Like this: 'enable "@USB\VID_0403&PID_6010&MI_00\7&15E4F68&1&"' Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Arguments for button command via Tkinter?
Il Mon, 31 Oct 2005 19:23:18 +, Steve Holden ha scritto: > Francesco Bochicchio wrote: >> Il Mon, 31 Oct 2005 06:23:12 -0800, [EMAIL PROTECTED] ha scritto: >> >> >>>And yet the stupidity continues, right after I post this I finnally >>>find an answer in a google search, It appears the way I seen it is to >>>create a class for each button and have it call the method within that. >>>If anyone else has any other ideas please tell. >> >> >> This is how I do it: Supposing I have three buttons b1, b2 and b3, and I >> want for each button to call the same callback with, as argument, the >> button itself: >> >> >> def common_callback(button): >> # callback code here >> >> >> class CallIt(objetc): >> def __init__(function, *args ): >> self.function, self.args = function, args >> def __call__(self, *ignore): >> self.function(button, *self.args) >> >> b1['command']= CallIt(common_callback, b1) >> b2['command']= CallIt(common_callback, b2) >> b3['command']= CallIt(common_callback, b3) >> >> This way you need only one class (a sort of custom callable) and >> its instances gets called by Tkinter and in turn calls your >> callback with the proper arguments. >> > I don't see why this is preferable to having the callback as a bound > method of the button instances. What's the advantage here? It looks > opaque and clunky to me ... > > regards > Steve I'm not saying that my method is better or even 'preferable'. Just different. The reason I came up this approach (years ago) is because I was used to other toolkits that always pass the widget as argument of the callback. So this was a fast solution to 'normalize' Tkinter with respect to what I perceived (and still do) as a limitation. As a bonus, you can also pass to the callback as many other arguments as you want. Another reason is that my basic approach to coding GUI is to use a class for each window. To put the code to handle button callbacks in a separate class feels to me a bit too much dispersive and potentially cumbersome if callback code has to interact with other window elements (although in Python nothing is impossible). Ciao - FB why I sometime -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Alert: Help me store constants pythonically
Il Sun, 06 Nov 2005 08:33:17 -0800, Brendan ha scritto: > Hi all > > I'm new to Python (and programming in general), and I can't decide what > is the most 'pythonic' way to approach a problem. Your advice would be > appreciated. > > I have a bunch of 'scans', containing the data measured from one of > several types of 'model'. Each 'model' has different values for a list > of constants I want to create 'analyses' which interpret the data from > the scans, with reference the appropriate model. So far, I have come > up with three strategies to store this information, illustrated below > (I've simplified the constant list to just two): > > 1) Store the model constants as class instances: > > class Model: > def __init__(self, numBumps, sizeOfBumps): > self.__dict__.update(locals()); del self.self > > MODEL1 = Model(1, 2) > MODEL2 = Model(3, 4) > #etc > > class Analysis: > def __init__(self, scanData, model): > #do analysis > > 2) Store the model constants as class variables: > > class MODEL1: > numBumps = 1 > sizeOfBumps = 2 > > class MODEL2: > numBumps = 3 > sizeOfBumps = 4 > > class Analysis: > #as with 1 > > 3) Store the model constants as class variables of the analysis class: > > class Model1Analysis: > numBumps = 1 > sizeOfBumps = 2 > > def __init__(self, scanData): >#do analysis > > class Model2Analysis(Model1Analysis): > numBumps = 3 > sizeOfBumps = 4 > > There may be more options, but at this point I became paralyzed with > choice. I worry about getting stuck with an unworkable structure since > I don't have the experience to decide the merits of each in advance. I > get way too frustrated about these things :) >Brendan My vote would go to the first option, but I don't understand why you use such a complicate way to set instance attributes. I would do simply class Model: def __init__(self, numBumps, sizeOfBumps): self.numBumps = numBumps self.sizeofBumps = sizeOfBumps or, if you want to generalize the arguments of the constructor: class Model: def __init__(self, **model_attributes): for attname, attvalue in model_attributes.items(): setattr(self, attname, attvalue) As for why to choose the first option... is the one that causes you to avoid useless code repetitions and to keep the Analysis code nicely generic. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
How to list the global functions from a C program
Hi all, I'm a Python newbie and I'm trying to add to my C++ program a limited support for scripts written in python. In particular, I'd like to load user scripts written in python, list all the functions he defined in the script file and then call them. To begin I wrote into my C++ program (correctly linked to python 2.3.2): == /* create the main module */ m_pModule = PyImport_AddModule("__main__"); m_pDict = PyModule_GetDict(m_pModule); m_pGlobals = m_pDict; m_pLocals = m_pDict;// is this right (globals==locals) ?? /* to try out python, I want just to force the creation of a simple function and then call it from C */ PyRun_StringFlags("def donothing():\n\treturn 'hello'\n", Py_file_input, m_pGlobals, m_pLocals, 0); /* scan all the contents of the __main__ module... */ PyObject *list = PyObject_Dir(m_pGlobals); if (!list || PyList_Check(list) == FALSE) return; for (int i=0,max=PyList_Size(list); i PyObject *elem = PyList_GetItem(list, i); if (PyCallable_Check(elem) != 0) { /* this should be a function.. */ /* HERE IS THE PROBLEM: this code is never reached */ PyObject *str = PyObject_GetAttrString(elem, "func_name"); } } == Everything seems to work but then when scanning the list returned by PyObject_Dir() I never find any callable object what am I doing wrong ? Thanks indeed, Francesco Montorsi == The perverse principle of programming: there is always another bug. (Murphy) == -- http://mail.python.org/mailman/listinfo/python-list
Re: How to send broadcast message over network and collect all the IP address?
Sandeep Arya wrote: >Hello to all > >Well this is my first mail on this list. I am facing a problem associated >with collecting IP address on my network. > >What i thought is to send broadcast packet over the network and then >recieving back the reply from the computers and bridges connected to my >network and then adding their IP Address in a list. > >How this can be achieved? Say my computer on which application will run's IP >is 192.168.100.254 and subnetmask is 255.255.255.0 > >How to do this in core Python? > >Sandeep > >_ >7000 classifieds >http://www.sulekha.com/classifieds/cllist.aspx?nma=IN&ref=msn -Chennai, >Mumbai, Hyderabad Bangalore. > > > I'm leaving from office now so i can not give a more complete answer ... i would use an ARP Request to all network address on your network and check who answer. Check out libdnet (http://libdnet.sf.net) for a python module implementing networking funcions. bye Francesco -- http://mail.python.org/mailman/listinfo/python-list
twistedSnmp and hexadecimal values ...
Hi all ml. I'm tryng to use TwistedSnmp to make query and walk directly inside my python code. The problem i'm facing is that any time there is an hexadecimal value to be returned by the snmpwalk it is returened in a weird and useless way... does anyone had any (successfull) experience with twistedsnmp and hexadecimal values (as Mac Addresses)? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python declarative
Some time ago I played with Tkinter trying a more declarative way of coding the GUI building part and I come out with this: top = Tk( 'top' ).add ( Frame( 'frame' ).add ( Pack( side = 'top' ), Frame ( 'panel1' ).add ( Pack( side='left'), Label ( 'label', text="Entry 1 : " ), Entry ( 'entry' ) ), Frame( 'panel2' ).add ( Pack( side='left'), Label ( 'label', text="Entry 2 : " ), Entry( 'entry' ) ), Pack( side = 'bottom' ), # packing change Button( 'button', text='Click Me' )) ) top.frame.button["command"] = functools.partial(button_cb, top) top.realize().mainloop() which, without changing the underlying plumbing, may also be written this way, which avoid nesting but still looks declarative-ish : top = Tk( 'top' ) top.add( Frame( 'frame' ) ) top.frame.add ( Pack( side = 'top' ), Frame ( 'panel1' ), Frame( 'panel2' ), Pack( side = 'bottom' ), # packing change Button( 'button', text='Click Me', command = functools.partial(button_cb, top) ) ) top.frame.panel1.add( Pack( side='left'), Label ( 'label', text="Entry 1 : " ), Entry ( 'entry' ) ) top.frame.panel2.add( Pack( side='left'), Label ( 'label', text="Entry 1 : " ), Entry( 'entry' ) ) top.realize().mainloop() The underlying plumbing for those two examples is just two classes amounting to about fifty lines of code, plus one-liner wrappers for each kind of widgets/geometry This just to tell you that yes, with python you can write declarative-looking code ... if you don't mind parenthesis :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python declarative
Looking at my own code after four years, I just realized that most of parentheses can be avoided by redefining the += operators to be a synonym of the add method. Go figure, I guess that with age it _does_ come a little wisdom ... :-) Ciao - FB -- https://mail.python.org/mailman/listinfo/python-list
Re: I love the decorator in Python!!!
On 8 Dic, 12:22, K.-Michael Aye wrote: > On 2011-12-08 08:59:26 +, Thomas Rachel said: > > > > > Am 08.12.2011 08:18 schrieb 8 Dihedral: > >> I use the @ decorator to behave exactly like a c macro that > >> does have fewer side effects. > > >> I am wondering is there other interesting methods to do the > >> jobs in Python? > > > In combination with a generator, you can do many funny things. > > > For example, you can build up a string: > > > def mkstring(f): > > """Turns a string generator into a string, > > joining with ", ". > > """ > > return ", ".join(f()) > > > def create_answer(): > > @mkstring > > def people(): > > yield "Anna" > > yield "John" > > yield "Theo" > > > return "The following people were here: " + people > > > Many other things are thinkable... > > > Thomas > > I am still perplexed about decorators though, am happily using Python > for many years without them, but maybe i am missing something? > For example in the above case, if I want the names attached to each > other with a comma, why wouldn't I just create a function doing exactly > this? Why would I first write a single name generator and then decorate > it so that I never can get single names anymore (this is the case, > isn't it? Once decorated, I can not get the original behaviour of the > function anymore. > So, above, why not > def mkstring(mylist): > with the same function declaration and then just call it with a list of > names that I generate elsewhere in my program? > I just can't identify the use-case for decorators, but as I said, maybe > I am missing something. > > Michael I had/have similar feelings. For instance, this is something that I tought useful, but then I never used in real code. The idea was to find a way to automate this code pattern, which I do a lot: class SomeClass: def __init__(self, some, attribute, here ): self.some, self.attribute, self.here = some, attribute, here In other words, I often define classes in which the constructor list of arguments corresponds one-to-one to class attributes. So I thought of this (it uses class decorators so it only works with Python 3.x ) : class FieldsDecorator: def __init__(self, *names): self.names = names def __call__(self, cls): def constructor(instance, **kwds): for n,v in kwds.items(): if n in self.names: setattr(instance, n, v) else: raise TypeError("%s is not a valid field" % s ) setattr(cls, '__init__', constructor ) return cls @FieldsDecorator("uno", "due") class Prova: pass p = Prova(uno=12, due=9) print (p.uno, p.due ) It works and it is nice, but I don't find it compelling enough to use it. I keep assigning directly the attributes, which is more readable. Decorators are really useful when you have lot of repetitive boilercode that you _want_ to hide, since it has little to do with the problem logic and more to to with the technicalities of the programming language or of some framework that you are using. It is called "separating of concerns" I think, and is one of the principles of Aspect-Oriented Programming (and with decorators you can do some nice AOP exercises ... ). Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Deleted System default Python on Leopard
Hello everyone, recently I've started to be try Python on my Mac OS X 10.5.8 Leopard and I've already messed up with it... I was compiling a Python souce code but didn't succeed and so I decided to install a newer version of Python. But before that, I did a stupid thing: I deleted manually all the folders of the Leopard's system default Python 2.5.1... Before when I was using the system Python, the program namebench worked perfectly. After that I messed everything up and installed MacPython 2.5 from the site python.org, now namebench always crashes. On the problem report system of Apple it gives me these errors: http://bpaste.net/show/21904/ While this is the Console: http://bpaste.net/show/21905/ What problem can it be? Can I clean up all the Pythons and restore the system one? Thanks everyone. Regards, Francesco Zhu -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb and dictcursor
On 7/24/06, Christoph Haas <[EMAIL PROTECTED]> wrote: On Monday 24 July 2006 14:06, borris wrote:> doesn anyone know a good reference, tute or examples of> MySQLdb's dictCursor> I want to pass dictionaries into the sql exec statements.> I could only succeed with text as values A german linux magazin has an article about passing a *list* of items athttp://www.linux-magazin.de/Artikel/ausgabe/2002/06/python-api/python-api.html For those who don't understand german here comes an example on how to passlists:cursor.execute("""INSERT INTO Adressen (Name, Strasse, PLZ, Ort) VALUES (%s, %s, %s, %s)""", [ ('Dr. Hans Mustermann', 'Musterstraße 13', 50823, 'Köln'), ('Peter Lustig', 'Im Bauwagen 2', 50827, 'Porz'), ('Edmund Stoiber', 'Spendensumpf 1', 47011, 'Bimbesdorf'), ('Onkel Hotte', 'Im Siff 42', 57072, 'Siegen'), ('Gerhard Schröder', 'Großmaulweg 2', 11901, 'Worthülsen') ] )However the DictCursor is helpful for *returning* dictionaries of valuesinstead of just tuples. I always use DictCursor because it makes it clearer which rows I want to access in the result. But DictCursor can'tpass dictionaries in a cursor.execute AFAIKT.But with dict.iteritems that shouldn't be hard to send dictionary items tothe SQL database in a loop either. You can use the same syntax you use for string formatting, even without using DictCursor class:cursor.execute('SELECT * FROM tablename WHERE id = %(id)s', {'id':43})RegardsFrancesco -- http://mail.python.org/mailman/listinfo/python-list
overriding setting
Hello, this is my first post to the list :-) I've looked around a bit before asking, and since I haven't found... I'm here to ask my question. I'm trying to ovveride attribute setting, but I haven't still found the right way to use all the fancy __get__, __set__ and __getattribute__ :-) I would like to retain initialization of an object by use of the = and not as a function call. A simple example is this: I want to define an "enhanced" list class, whose items will be other (built in) lists and providing a "padding" method which fills all the contained lists to the same lenght. An example could be: class myList(list): def __init__(self): self._max = None list.__init__(self) def pad(self): for item in self: if type(item)== list: while len(item) < self._max: item.append("") Now the question is this: I would like to initialize such an object in this way: a = myList() a = [[1, 2, 3], [4, 5, 6, 7]] a.pad() # and now a _should_ contain [[1, 2, 3, ""], [4, 5, 6, 7]] Obviously this doesn't work, because when at the second line I do the initialization, type(a) becomes , and so I get the expected AttributeError since pad cannot be found. A possible solution could be to create a container class, intercepting every attribute accession with __getattribute__. In this case I should refer to Container.myFirstList, Container.mySecondList, which is ugly because of the need to refer to Container first...(not to mention that I'm still working on making the __getattribute__ work properly... :-) ) Do you have any suggestions? or maybe I should simply stop trying to do that and resort to adding some sort of insert or append method (this is what I have done for the time being, but I found this solution less appealing and nice ...) thanks in advance, Francesco -- "Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose vis-à-vis an introduction, so let me simply add that it's my very good honor to meet you and you may call me V." -- V's introduction to Evey -- http://mail.python.org/mailman/listinfo/python-list
Re: overriding setting
On 6/6/07, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Francesco > Guerrieri wrote: > > > Now the question is this: > > I would like to initialize such an object in this way: > > a = myList() > > a = [[1, 2, 3], [4, 5, 6, 7]] > > a.pad() > > # and now a _should_ contain [[1, 2, 3, ""], [4, 5, 6, 7]] > > > > > > Obviously this doesn't work, because when at the second line I do the > > initialization, type(a) becomes , and so I get the > > expected AttributeError since pad cannot be found. > > You don't initialize in the second line, you just rebind `a` to a > completely different object. Names don't have types in Python, objects do. > > `list()` takes an optional argument. Just make sure your derived type > does to and passes this to the base class `__init__()`. Then you can > create an instance like this: > > a = MyList([[1, 2, 3], [4, 5, 6, 7]]) > yes it's true that it is not an initialization :-) It's that I hoped that there was a way to do an init rather than a rebinding of the name. Your suggestion is exactly what I have implemented for the time being... I subclass the builtin list type, I have a pad method which adds the requested whitespaces at the end, an append method which invokes the base class append AND calls the pad method, and finally a __call__ which calls the append. Furthermore, I check that the input is valid... So everything works fine :-) The only problem is that while coding I have the temptation to write a = [[...], [...]) rather than a([1, 2, 3], [5,6, 7, 8]). Plus I find it uglier :-) but if there isn't a reasonable way, I'll give up :-) thanks, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Select one of 2 functions with the same name ?
If the functions are f1, f2, f3 you could go this way: def SimulationRun(): if simulation_level = 1: SimulationFunction = f1 else if simulation_level = 2: SimulationFunction = f2 else and in the rest of the code you can refer to SimulationFunction instead of explicitly calling f1, f2 or f3. I'm sure that there are many smarter methods :-) On 6/10/07, Stef Mientki <[EMAIL PROTECTED]> wrote: > hello, > > For a simulation at different levels, > I need different functions with the same name. > Is that possible ? > > I can realize it with a simple switch within each function, > but that makes the code much less readable: > > def Some_Function(): >if simulation_level == 1: > ... do things in a way >elif simulation_level == 2: > ... do things in another way >elif simulation_level == 3: > ... do things in yet another way > > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose vis-à-vis an introduction, so let me simply add that it's my very good honor to meet you and you may call me V." -- V's introduction to Evey -- http://mail.python.org/mailman/listinfo/python-list
Re: with as a reserved word
Within gnuplot you can shorten "with" to "w", don't know if it can work inside a call to Gnuplot.Data() francesco On 6/11/07, BBands <[EMAIL PROTECTED]> wrote: > I gather that 'with' is on its way to becoming a reserved word. Is > this something that will break? > > import Gnuplot > gp = Gnuplot.Gnuplot(debug=1) > data = Gnuplot.Data([1,2,3,4,3,2,3,4,3,2,1], with='linespoints') > gp.plot(data) > > >>> :3: Warning: 'with' will become a reserved keyword in Python 2.6 > > http://www.gnuplot.info/ > http://gnuplot-py.sourceforge.net/ > > This was run by PyScripter 1.8.7.1 with Python 2.5. > > jab > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose vis-à-vis an introduction, so let me simply add that it's my very good honor to meet you and you may call me V." -- V's introduction to Evey -- http://mail.python.org/mailman/listinfo/python-list
Re: Method much slower than function?
On 6/14/07, Peter Otten <[EMAIL PROTECTED]> wrote: > Gabriel Genellina wrote: > > ... > > py> print timeit.Timer("f2()", "from __main__ import f2").repeat(number=1) > > [0.42673663831576358, 0.42807591467630662, 0.44401481193838876] > > py> print timeit.Timer("f1()", "from __main__ import f1").repeat(number=1) > > > > ...after a few minutes I aborted the process... > > I can't confirm this. [...] > $ python2.5 -m timeit -s 'from join import f1' 'f1()' > 10 loops, best of 3: 212 msec per loop > $ python2.5 -m timeit -s 'from join import f2' 'f2()' > 10 loops, best of 3: 259 msec per loop > $ python2.5 -m timeit -s 'from join import f3' 'f3()' > 10 loops, best of 3: 236 msec per loop On my machine (using python 2.5 under win xp) the results are: >>> print timeit.Timer("f2()", "from __main__ import f2").repeat(number = 1) [0.19726834822823575, 0.19324697456408974, 0.19474492594212861] >>> print timeit.Timer("f1()", "from __main__ import f1").repeat(number = 1) [21.982707133304167, 21.905312587963252, 22.843430035622767] so it seems that there is a rather sensible difference. what's the reason of the apparent inconsistency with Peter's test? Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: "Variable variable name" or "variable lvalue"
On 8/15/07, mfglinux <[EMAIL PROTECTED]> wrote: > > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > Hello, you could use exec to create on the fly the variables as you need them (but be aware that the use of exec can be dangerous and is probably not needed), or you could add the proper name to a relevant dictionary (for example, locals() ). Something like for counter in xrange(3): locals()["Material" + str(counter)] = Material(12.5) But if you need the variables only for calling Slab, you could write something like: material_number = 3 material_list = [Material(12.5) for x in xrange(0, counter)] Period = Slab(sum(material_list)) bye, francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Joining elements in a list to 1 element
On 8/23/07, dimitri pater <[EMAIL PROTECTED]> wrote: > > Dear all, > I am having trouble joining elements in a list into 1 element. > e.g. ['a','b','c'] into ['abc'] so that len(list) returns 1 > > You need to append the joined string to your new list. For instance my_list = ["a", "b", "c"] my_second_list = [] my_second_list.append("".join(my_list)) bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Joining elements in a list to 1 element
On 8/23/07, J. Cliff Dyer <[EMAIL PROTECTED]> wrote: > > What do you want to have happen in this case? > > my_list = [ 'a', 4, 'c' ] > It depends on the requirements of the OP. A possible solution could be: my_second_list = [] try: my_second_list.append("".join(my_list)) except TypeError: my_second_list.append("".join(str(item) for item in my_list) ) But it depends on the the actual requirements, maybe it isn't meaningful for the original list to contain numbers (think for instance of nucleotide sequences...?) Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows)
On 8/27/07, Peter Otten <[EMAIL PROTECTED]> wrote: > Peter Otten wrote: > > > Alex Martelli wrote: > > > >> Integer objects that are once generated are kept around in a "free list" > >> against the probability that they might be needed again in the future (a > > > > Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> x = 1000 > >>>> y = 1000 > >>>> x is y > > False > > Why don't x and y point to the same object then? > > Peter > Oops, I think I got it now. The actual objects are freed, only the memory is > kept around for reuse with other ints... On my (windows) machine, only integer up to 256 are cached... I made two dictionaries with mapping from i to id(i) and then compared. They were equal up to 256. In short, try your example with 256 and 257 and see what happens :-) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: XML File -- dictionary edit/search
On 8/28/07, Nagarajan <[EMAIL PROTECTED]> wrote: > A simple yaml file might just do the trick. > Your yaml file shall look like the following: > > Word-def.yaml > word1: word1's definition > word2: word2's definition > .. > .. > .. > Use pyyaml to handle yaml files. > > import yaml > worddefs = yaml.load( open( "word-def.yaml", "r" ).read() ) > print worddefs > I agree with the suggestion for yaml! Since definitions are to be inputed by the users, it could be better to use yaml.safe_load() to reduce the risks... francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: pure python for sms
On 8/31/07, Gerardo Herzig <[EMAIL PROTECTED]> wrote: > Well, im not triyng to send a SMS `FROM' a cellphone, im trying to send > a SMS `TO' a cellphone. Here (in Argentina) are several sites who lets > you send a sms for free. You also can receive SMS responses via this page > http://sms.personal.com.ar/Mensajes/msn.htm > > While my tries using this page via urllib failed, i dont want to depend > on an external page anyway. The python class you send to me looks like > a pay site (if not, i dont see why the tokenpay() and getbalance() > methods :) > > I was also avaiable to send a sms in the form of an plain email > [EMAIL PROTECTED], but it not seems to work > this way no longer. Again, i dont want to do it that way anyway. > > Thats why im looking for a python implementation of that funcionality. Well but sooner or later you will have to pass your sms through some cellular system network whose services someone has to pay for...no? Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: list index()
On 9/2/07, Zentrader <[EMAIL PROTECTED]> wrote: > > On Aug 30, 11:23 am, [EMAIL PROTECTED] wrote: > > Neil, Steve, > > > > Thanks for the responses on sets. I have not used them before and was > > not even aware Python had them. I will try them out. > > And if there weren't sets you would still not use find or index but a > brute force method or dictionaries > for each in dir_a_list : >if each not in dir_b_list : > print each, "not in dir_b" > This is O(N_a * N_b)... unless the list are always small, it's definitely better (if one is decided not to use sets) to use dictionaries :-) bye francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: So what exactly is a complex number?
On 9/3/07, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote: > > Grzegorz Słodkowicz wrote: > > In fact, a proper vector in physics has 4 features: point of > > application, magnitude, direction and sense. > > > OK, help me out here: What 'direction' does |Ψ> (a state-vector in > quantum mechanics) have? Also, doesn't sense directly follow from the > point of application. For instance, you can apply a force to a point and it can be "outward" or "inward". The direction of a state vector is completely specified by its decomposition (given finite norm and completeness of the basis), just like ordinary vectors. But since actually in quantum mechanics you are dealing with unit rays and everything is defined up to a phase (which could be relevant given the topic of this thread!)... I'd say that kets are not the most recommendable way to introduce the concept of vector, or of complex variables :-) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
On 9/5/07, bambam <[EMAIL PROTECTED]> wrote: > > I have about 30 pages (10 * 3 pages each) of code like this > (following). Can anyone suggest a more compact way to > code the exception handling? If there is an exception, I need > to continue the loop, and continue the list. > > Steve. > > --- > for dev in devs > try: > dev.read1() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read2() > except > print exception > remove dev from devs > > for dev in devs > try: > dev.read3() > except > print exception > remove dev from devs > > etc. > well the first thought is: why don't you put all the calls in a single for loop? for dev in devs: try: call the methods on dev (instead of explicitly elencating all of them there could and should be other solutions more mantainable) except: flag dev as unusable Modifying the sequence you are iterating over can be tricky. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping through File Question
On 9/5/07, planetmatt <[EMAIL PROTECTED]> wrote: > > I am a Python beginner. I am trying to loop through a CSV file which > I can do. What I want to change though is for the loop to start at > row 2 in the file thus excluding column headers. > > At present I am using this statement to initiate a loop though the > records: > > for line in f.readlines(): > > How do I start this at row 2? > you can simply call (and maybe throw away) f.readline() a single time before looping. If the lenght of the first line is fixed, you can also use f.seek to start reading from the second row. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonAlley.com
On 9/5/07, dkeeney <[EMAIL PROTECTED]> wrote: > > > The Python community would benefit from a moderated web-forum along > the lines of > perlmonks.org. > > The Python community online now seems to have two major segments, the > c.l.p newsgroup (here), > and a large selection of blogs. C.l.p is unmoderated and often > hostile. The bloggers > Actually c.l.py is one of the least hostile place (and more helpful for the newcomers, like myself) I ever met on the net. I will concede that I've only been online since twelve years so in the good ol' times surely there were many more place better than this one. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
On 9/5/07, James Stroud <[EMAIL PROTECTED]> wrote: > > > Another way is to make a copy of devs, if devs is short, which makes my > > When I process something of that genre (e.g. files) I prefer not to lose trace of what's happened by removing the "bad items". Instead I prefer to flag or otherwise to store them in some place from where they could get back. Obviously, it depends on the details of the program :) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: concise code (beginner)
On 9/10/07, bambam <[EMAIL PROTECTED]> wrote: > > I have a number of news readers here, but all of them work > better with top-posting, and in none of them is top posting > a problem. What software are you using? > > Steve. > I use gmail and I can assure you that top posting is annoying. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: less obvious "super"
On 9/10/07, Nagarajan <[EMAIL PROTECTED]> wrote: > > Hi group, > I am confused with "super" usage..It seems to be complicated and less > obvious. > Here is what I need to achieve.. > > class A : > def __init__( self ): > self.x = 0 > > class B ( A ): > def __init__( self, something ): > # Use "super" construct here so that I can "inherit" x of A > self.y = something > > How should I use "super" so that I could access the variable "x" of A > in B? > You don't need to use super in this case. You just have to remember to explicitly initialize the classes you are deriving from. In this case, class B(A): def __init__(self, something): A.__init__(self) self.y = something bye, francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: less obvious "super"
On 9/10/07, Nagarajan <[EMAIL PROTECTED]> wrote: > > > > What's the difference b/w: > class A: > and > class A ( object ): > > Thanks. > The first one declares an old-style class. The second one declares a new style class. It's better to use the new-style (always derive from object). See http://www.python.org/doc/newstyle.html for further reading francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Wait For Application Start
On 9/18/07, Robert Rawlins - Think Blue <[EMAIL PROTECTED]> wrote: > This seems like a very logical method, but I'm not sure how to implement it > into my python code? Is there a simple way to make it wait for that file? > Without the need to build my own conditional loop? I'm not sure why how you could avoid a conditional loop. Could something like this work? import os.path import time while True: if os.path.exists(YOUR_FILE): break time.sleep(30) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
On 9/18/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > If I have a file name: AVC1030708.14. How do I strip out certain > characters from the file name? I am so used to using MID, LEFT, and > RIGHT functions, that I have no idea how to do this in python? I have > had trouble as well with most newbies on finding the help. But I have > used the command line built in help, but with no luck. Thanks. > > Kou As a newbie, you would do well to read and study the tutorial which you can find at http://docs.python.org/tut/tut.html In particular there is an interesting section on Strings: http://docs.python.org/tut/node5.html#SECTION00512 and http://docs.python.org/lib/string-methods.html Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Wait For Application Start
On 9/18/07, Michael Bentley <[EMAIL PROTECTED]> wrote: > > > > import os.path > > import time > > > > while True: > > if os.path.exists(YOUR_FILE): > > break > > time.sleep(30) > > or > > while not os.path.exists(YOUR_FILE): > time.sleep(1) I thought of that, but I found more readable the positive form :-) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Sets in Python
On 9/19/07, Paddy <[EMAIL PROTECTED]> wrote: > frozenset over turning the embedded list into a tuple? > The tuple would preserve order in the item (1,2) > a = set([1,2,3, (1,2)]) The OP was probably thinking in mathematical terms as in "the set of all the possible subsets of the set composed by 1, 2 and 3" and thus order would not be important. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: How to know the starting point
On 9/19/07, Raj kumar <[EMAIL PROTECTED]> wrote: > Hi, > I need help regarding the starting point in python project, > As we can find main() function in java class to know the starting class in > java, > what is the starting point in python project? > How to find the starting point. > Thank you > There is no such thing, you can start where you like: try to write a simple .py file defining some functions and classes and then using them. Then launch the app by python your_file.py, and it will just work. You will often find a test like if __name__ == '__main__': do_something() __name__ is the variable which contains the name of the module. If the module is being run as python your_module.py, the __name__ becomes '__main__' and the condition of the if statement is satisfied. This is a common method to define a starting point for a python application. Keep in mind that many python modules are intended to be imported by other modules and not to be used as standalone applications, but rather as libraries. As such, they don't have a starting point, and the if __name__ == '__main__': test could be used for instance to start a test suite. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Find the ID, but how to select/copy the whole string by ID?
On 9/19/07, Leon <[EMAIL PROTECTED]> wrote: > stringID = str(raw_input('Enter the string ID : ')) > file = open('strings.txt') > sourcefile = file.read() > file.close() > sourcefile.find (stringID) > > but how can I select and copy the specific string from to > with id I input? If the file you are parsing is in xml, there are many parser out there which can help you (this is discussed very often on this list, even today) . If the format is very simple and you really want to do it by hand, you could do something like: stringID = raw_input('Enter the string ID:') for line in open('strings.txt'): if line.find(stringID) > -1: print 'Found!' Note that find returns the index where the substring you look for is found, and it returns -1 if the substring is not found. The problem is that -1 is a valid index to refer to a character in a string (actually it refers to the last character of the string), so be careful with interpreting the results of the find method. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Find the ID, but how to select/copy the whole string by ID?
On 9/19/07, Carsten Haese <[EMAIL PROTECTED]> wrote: > , then looking for id 12 is going to match on the wrong ID. Besides, > that code only tells you where something that looks like the ID you're > looking for is in the file. There is no guarantee that the match > actually occurs inside an ID attribute. It also doesn't help in > retrieving the text contents of the tag that has this ID. > > If your input is an XML file, using an actual XML parser is the only > correct solution. You're perfectly right. The code example was purposedly incomplete for this very reason. It could be made less sensitive to false matches by constructing a correct substring, something like pattern = '' and then in the loop: line.find(pattern) but I agree that it would be wrong to proceed this way. The motivation of my reply was more to suggest a better way to iterate over a file than else... but since I've been confusing it probably would have been better to avoid. francesco -- http://mail.python.org/mailman/listinfo/python-list
Mysqldb & stderr
developing a daemon (using python 2.4 and mysqldb 1.2.1_p2) we notes that mysqldb class write on stderr some warnings and error asyncronously (uhmmm it's good written? ;P ). If stderr is closed these function raise up an I/O error (obviously). We spent a lot of time to understand for now we redirected stderr on /dev/null, but.. it's a workaround. Someone knows how stop write on stderr (and stdout) on mysqldb? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 migration plans?
On 9/28/07, TheFlyingDutchman <[EMAIL PROTECTED]> wrote: > On Sep 28, 10:57 am, Steve Holden <[EMAIL PROTECTED]> wrote: > > This is like listening to a four-year-old torment its parents with > > incessant questions. Do you *have* to ask every question that pops into > > your mind? > > > > In this case I asked it as part of the original question and it was > ignored. I have programmed in C and C++ and a little Pascal many years > ago. I don't remember anything about Higher Order Functions and would > like to see exactly how you do it and to verify the contention. You could just google for it. Just in case your connection to google or other similar search engines has been disabled for some reason, here are some links. Try for instance http://okmij.org/ftp/c++-digest/Lambda-CPP-more.html#Ex3 or http://www.cc.gatech.edu/~yannis/fc++/ or http://www.boost.org/libs/mpl/doc/tutorial/higher-order.html francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0 migration plans?
On 9/28/07, TheFlyingDutchman <[EMAIL PROTECTED]> wrote: > Correct me if I am wrong, but none of those examples showed something > in C++ similar to a decorator in Python - that is, unique syntax in > the language for implementing a Higher Order Function. One thing I > will say about those examples is that they make Python decorators look > sweet! That is exactly one of the points in having decorators, as far as I can tell. Namely, that higher order functions are easily implemented, if and when needed. Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: s.split() on multiple separators
On 9/30/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). Have a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342 which contains several ways to solve the problem. You could both translate all your separators to a single one, and then split over it, or (maybe the simpler solution) going for the list comprehension solution. francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: s.split() on multiple separators
On 9/30/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello everyone, > > OK, so I want to split a string c into words using several different > separators from a list (dels). Have a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303342 which contains several ways to solve the problem. You could both translate all your separators to a single one, and then split over it, or (maybe the simpler solution) going for the list comprehension solution. francesco -- http://mail.python.org/mailman/listinfo/python-list
finding out the call (and not only the caller)
Hi, Today I've been thinking a bit about the "python internals". Inspired by this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 I found out a little problem which haven't been able to solve. In short, is there a way to find out how a given name lookup was started? It is not enough to know the name of the caller as given by the recipe. a little example: import inspect class test(object): def __init__(self, a_list): self.my_list = a_list def info(self): for counter, item in enumerate(inspect.getouterframes(inspect.currentframe())): print counter, item return self.my_list data = property(info) if __name__ == '__main__': a = test([,]) def g(a_seq): for item in a_seq: print item, '\n' g(a.data) This prints 0 (, 'myfile.py', 10, 'info', [' for counter, item in enumerate(inspect.getouterframes(inspect.currentframe())):\n'], 0) 1 (, 'myfile.py', 38, '', [' g(a.data)\n'], 0) What I would like is a reference to g itself, and not only to '' which is the caller according to f_code.co_name. I thought of manually parsing the string 'g(a.data)\n' to extract the name but I'm sure that it would be a rather fragile approach, and so I decided that it was time to ask for help :-) To 'get a feeling', I tried to disassemble the code: code = compile('g(a.data)', 'test', 'single') dis.dis(code) and this is the result 0 LOAD_NAME0 (g) 3 LOAD_NAME1 (a) 6 LOAD_ATTR2 (data) 9 CALL_FUNCTION 1 12 PRINT_EXPR 13 LOAD_CONST 0 (None) 16 RETURN_VALUE So ... I'm looking for the first name loaded. Is there a reference to it, somewhere? Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Peoples' Names in Files
On 10/11/07, brad <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > On Oct 11, 5:22 pm, brad <[EMAIL PROTECTED]> wrote: > >> Crazy question, but has anyone attempted this or seen Python code that > >> does? For example, if a text file contained 'Guido' and or 'Robert' and > >> or 'Susan', then we should return True, otherwise return False. > > > > Can't you just use the string function .findall() ? > > > > I mean *any* possible person's name... I don't *know* the names > beforehand :) "I cannot combine some characters dhcmrlchtdj which the divine Library has not foreseen and which in one of its secret tongues do not contain a terrible meaning. No one can articulate a syllable which is not filled with tenderness and fear, which is not, in one of these languages, the powerful name of a god." Jorge Luis Borges, The Library of Babel -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbi Q: Recursively reverse lists but NOT strings?
On 10/15/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > >>> ''.join(reversed("abc")) > 'cba' > >>> list(reversed(range(3))) > [2, 1, 0] > > It doesn't take much to make a more user-friendly version: > > > def myreversed(sequence): > if isinstance(sequence, basestring): > return type(sequence)().join(reversed(sequence)) > else: > return type(sequence)(reversed(sequence)) > > (in fact, that's so simple I wonder why the built-in reversed() doesn't > do that). simple: In the face of ambiguity, refuse the temptation to guess. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbi Q: Recursively reverse lists but NOT strings?
On 10/15/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Mon, 15 Oct 2007 14:47:30 +0200, Francesco Guerrieri wrote: > > >> def myreversed(sequence): > >> if isinstance(sequence, basestring): > >> return type(sequence)().join(reversed(sequence)) > >> else: > >> return type(sequence)(reversed(sequence)) > >> > >> (in fact, that's so simple I wonder why the built-in reversed() doesn't > >> do that). > > > > simple: > > In the face of ambiguity, refuse the temptation to guess. > > What ambiguity? What guess? The above is completely unambiguous: it > returns a sequence of the same type as the input. It doesn't support > xrange objects, but that's not really a great loss. I could say that it depends on the xrange object.. but the truth is that I answered too quickly. Your suggestion was not ambiguous. Sorry :-) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: easy but difficult
On 10/16/07, Beema shafreen <[EMAIL PROTECTED]> wrote: > hi everybody, > I have a file separated by hash: > as shown below, > file: > A#1 > B#2 > A#2 > A#3 > B#3 > > I need the result like this: > A 1#2#3 > B 2#3 > > how will generate the result like this from the above file > can somebody tell me what i have to do.. > My code: > fh =open('abc_file','r') > for line in fh.readlines(): >data = line.strip().split('#') > for data[0] in line > print line > > I tried but i donot know how to create 1#2#3 in a single line > regards This certainly seems to be a homework assignment :) You could try if dictionaries or their variants. There is an example very similar example to the task you are trying to solve in the documentation available online on the site docs.python.org francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: while statements
On 10/16/07, danfolkes <[EMAIL PROTECTED]> wrote: > Instead of: if(cal<=0) > > you could do : > cal=0 > while cal<=0: > cal = int(raw_input("Please enter the number of calories in your > food: ")) > > that would make sure that your input is > 0 Calories could be non integer :) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: calling a function from string
On 10/22/07, james_027 <[EMAIL PROTECTED]> wrote: > hi, > > i have a function that I could like to call, but to make it more > dynamic I am constructing a string first that could equivalent to the > name of the function I wish to call. how could I do that? the string > could might include name of the module. > > for example > > a_string = 'datetime.' + 'today()' > > how could I call a_string as function? you could use getattr: function_name = 'time' # this is a string module_name = 'time' # this is a string, too my_function = getattr(module_name, function_name) # this is the function object, # equivalent to my_function = time.time my_function() # This is the function call, equivalent to time.time() bye francesco -- http://mail.python.org/mailman/listinfo/python-list
Recursive insertion of a line
New to the list and just beginning with Python (Linux B console). Urgent problem before I can correctly program: How to insert "TER" records recursively, i.e. some thousand fold, in a file like in the following example? "H2 WAT" is the only constant characteristic of the line after which to insert "TER"; that distinguishes also for lines for other atoms. Just to illustrate what I want to do - for those unfamiliar with this type of file - a three-line set between two "TER" defines a water molecule, with a set of xyz coordinates for each atom. TER ATOM 27394 O WAT 3966 17.713 13.305 27.101 1.00 0.00 W20 O ATOM 27395 H1 WAT 3966 17.814 13.945 26.397 1.00 0.00 W20 H ATOM 27396 H2 WAT 3966 16.776 13.297 27.297 1.00 0.00 W20 H TER ATOM 27397 O WAT 4144 0.648 8.291 27.112 1.00 0.00 W20 O ATOM 27398 H1 WAT 4144 0.344 8.314 26.205 1.00 0.00 W20 H ATOM 27399 H2 WAT 4144 1.278 7.571 27.144 1.00 0.00 W20 H TER ATOM 27400 O WAT 4178 20.289 4.598 26.491 1.00 0.00 W20 O ATOM 27401 H1 WAT 4178 19.714 3.835 26.423 1.00 0.00 W20 H ATOM 27402 H2 WAT 4178 21.173 4.237 26.554 1.00 0.00 W20 H TER Thanks francesco pietra Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive insertion of a line
Please, see below. --- Gabriel Genellina <[EMAIL PROTECTED]> wrote: > En Mon, 19 Nov 2007 21:15:16 -0300, Henry <[EMAIL PROTECTED]> > escribió: > > > On 19/11/2007, Francesco Pietra <[EMAIL PROTECTED]> wrote: > >> > >> How to insert "TER" records recursively, i.e. some thousand fold, in a > >> file > >> like in the following example? "H2 WAT" is the only constant > >> characteristic of > >> the line after which to insert "TER"; that distinguishes also for lines > > > > If every molecule is water, and therefore 3 atoms, > you can use this fact > > to > > insert TER in the right place. You don't need recursion: > > > > f = open( "atoms.txt", "rt" ) > > lineCount = 0 > > for line in f.xreadlines( ): > > lineCount = lineCount + 1 > > print line > > if lineCount == 3: > > lineCount = 0 > > print "TER" > > f.close( ) > > A small variation can handle the original, more generic condition "insert > TER after the line containing H2 > WAT" > > f = open("atoms.txt", "r") > for line in f: > print line > if "H2 WAT" in line: > print "TER" > f.close() > > (also, note that unless you're using Python 2.2 or earlier, the xreadlines > call does no good) I tried the latter script (which works also if there are other molecules in the file, as it is my case) encountering two problems: (1) "TER" records were inserted, as seen on the shell window. Though, the file on disk was not modified. Your script named "ter_insert.py", in order to get the modified file I used the classic $ python ter_insert.py 2>&1 | tee file.out Now, "file .out" had "TER" inserted where I wanted. It might well be that it was my incorrect use of your script. (2) An extra line is inserted (which was not a problem of outputting the file as I did), except between "TER" and the next line, as shown below: TER ATOM 27400 O WAT 4178 20.289 4.598 26.491 1.00 0.00 W20 O ATOM 27401 H1 WAT 4178 19.714 3.835 26.423 1.00 0.00 W20 H ATOM 27402 H2 WAT 4178 21.173 4.237 26.554 1.00 0.00 W20 H TER ATOM 27403 O WAT 4585 23.340 3.428 25.621 1.00 0.00 W20 O ATOM 27404 H1 WAT 4585 22.491 2.985 25.602 1.00 0.00 W20 H ATOM 27405 H2 WAT 4585 23.826 2.999 26.325 1.00 0.00 W20 H TER ATOM 27406 O WAT 4966 22.359 0.555 27.001 1.00 0.00 W20 O ATOM 27407 H1 WAT 4966 21.820 1.202 27.456 1.00 0.00 W20 H ATOM 27408 H2 WAT 4966 22.554 -0.112 27.659 1.00 0.00 W20 H TER END Where "END" is how Protein Data Bank (pdb) files end. As these files are extremely sensitive, can the script be modified to avoid these extra lines? Not tried (it takes time, because I have to go to the big cluster) if the extra lines really create problems, though, they take a lot of space on the shell window. A nearly perfect script. Thank you francesco > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive insertion of a line
--- Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Tue, 20 Nov 2007 01:16:53 -0800 (PST), Francesco Pietra > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > > > > Now, "file .out" had "TER" inserted where I wanted. It might well be that > it > > was my incorrect use of your script. > > > Well, it looks like, for purposes of demonstration, the supplied > program is using "print" statements, which write to stdout. Not sure why > you needed some sort of pipe/tee call, a simple "> new.output.file" > redirection would have done. I used "2>&1 | tee" because in many cases I want to check the screen. That in ab initio computations, where solving the matrix allows ample vision of the screen. I agree that for the scope of this python script it is redundant. > > > (2) An extra line is inserted (which was not a problem of outputting the > file > > as I did), except between "TER" and the next line, as shown below: > > > A result of using "print"... "print" adds a newline on the data -- > but ".readline()" does not /remove/ the newline on the input data -- so > unmodified lines now end with two newlines.. > > A common .strip() call on those lines might be sufficient... It is indeed. After a few trials (I am quite new to Python and I rarely find time for programming, but this attitude might change with Python), the following script fulfills the scope: f=open("output.pdb", "r") for line in f: line=line.rstrip() if line: print line f.close() Thanks francesco > Or > change the "print" statements to "sys.stdout.write(...)", and ensure > that the "TER" is written /with/ a newline ("TER\n"). > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Science list
It is true that suggestions may arrive from all directions. Nonetheless, this extremely useful list is so crowded that if checking email is not carried out every few hours, it is difficult to detect other messages in the plethora of pythons and spams arrived. What happens if email is disregarded for a few days? Therefore, I support a recent suggestion to establish a "science list", where python-solving problems arising from scientific use of software should appear. Something will be missed by users of the "science list", though things will become manageable. On the present list they are not. Thanks francesco pietra Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
I was trying to suggest a more specific mail-list in order not to be floaded. I am the opinion that python-list@python.org is very informative and useful, though it is hard to find the time for so many mails. f. --- Bjoern Schliessmann <[EMAIL PROTECTED]> wrote: > Francesco Pietra wrote: > > Nonetheless, this extremely useful list is so crowded that if > > checking email is not carried out every few hours, it is difficult > > to detect other messages in the plethora of pythons and spams > > arrived. > > Why don't you use a newsreader to access comp.lang.python? It's > suited much better for tracking long and many threads. > > Regards, > > > Björn > > > -- > BOFH excuse #357: > > I'd love to help you -- it's just that the Boss won't let me near > the computer. > > -- > http://mail.python.org/mailman/listinfo/python-list > Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
Do you know if "free" yahoo.com allows threaded view for python only? I was unable to set that. This also means that there are mailing lists I am interested to view all that is going on (which is two orders less that python), so that i can't sett threated viw for all mailing lists. f. --- nmp <[EMAIL PROTECTED]> wrote: > Bjoern Schliessmann wrote: > > > Francesco Pietra wrote: > >> Nonetheless, this extremely useful list is so crowded that if checking > >> email is not carried out every few hours, it is difficult to detect > >> other messages in the plethora of pythons and spams arrived. > > > > Why don't you use a newsreader to access comp.lang.python? It's suited > > much better for tracking long and many threads. > > Or switch to threaded view in your mail program, most mailers can do it > nowadays. > -- > http://mail.python.org/mailman/listinfo/python-list > Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: reading raw variables from file
On Nov 30, 2007 5:57 AM, Astan Chee <[EMAIL PROTECTED]> wrote: > Hi, > I have a file that might contain literal python variable statements at > every line. For example the file info.dat looks like this: > users = ["Bob", "Jane"] > status = {1:"ok",2:users[0]} > the problem is I want to read this file and load whatever variables > written in it as normal python variable statements so that when i read > the file, my users var will be ["Bob","Jane"] and my status var will be > {1:"ok",2:users[0]} . Is there an easy way of doing this instead of > parsing the files and checking said types? A much safer approach would be to use Yaml, which provides safely and easily the requested feature Give a look at: http://pyyaml.org/ bye, francesco -- http://mail.python.org/mailman/listinfo/python-list
Donloadin mail on the background
Dennis: Why am I using web-based email? As I work on several machines scp linked. I find often useful to see the same mail on different machines around, without downloading anything, just to set up the files on-the-fly for local trial computation before sending a calculation to the mainframe. That I found easy with web-based email. I do not maintain locally on any machine any mail for longer than working on. I am sure you have, or can devise, a better strategy to the same purpose. I am not an expert in software. Regards francesco pietra Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now. http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: "Python" is not a good name, should rename to "Athon"
On Dec 3, 2007 4:40 PM, Russ P. <[EMAIL PROTECTED]> wrote: > As I said before, a name is > just a name. It might as well be called "cockroach" as far as I am > concerned. Unluckily "the Beatles" was already taken :-) francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about subclassing an int
On Jan 4, 2008 11:55 PM, Steven W. Orr <[EMAIL PROTECTED]> wrote: > class S(int): > def __init__(self, value): >self.value = value > def addStr(self, str): >self.doc = str > The original question has already been answered, I only want to suggest to avoid shadowing builtin names, like str in the above example. Bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Delete lines containing a specific word
Please, how to adapt the following script (to delete blank lines) to delete lines containing a specific word, or words? f=open("output.pdb", "r") for line in f: line=line.rstrip() if line: print line f.close() If python in Linux accepts lines beginning with # as comment lines, please also a script to comment lines containing a specific word, or words, and back, to remove #. Thanks francesco pietra Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Delete lines containing a specific word
I forgot to add that the lines to strip are in present case of the type of the following block HETATM 7007 O WAT 446 27.622 34.356 55.205 1.00 0.00 O HETATM 7008 H1 WAT 446 27.436 34.037 56.145 1.00 0.00 H HETATM 7009 H2 WAT 446 27.049 33.827 54.563 1.00 0.00 H occurring in a 300MB file. In present case each three-lines block is followed by line renumbering (7007, 7008, 7009 are line numbers). So, the script is simply to strip the lines containing :WAT". In other cases the block is intermediate. Therefore, a second script would be useful where the line that follow the block are renumbered, e.g, line "HETATM 7010" following the above block renumbered "HEATM 7006". thanks francesco --- Francesco Pietra <[EMAIL PROTECTED]> wrote: > Date: Sun, 6 Jan 2008 09:21:33 -0800 (PST) > From: Francesco Pietra <[EMAIL PROTECTED]> > Subject: Delete lines containing a specific word > To: python-list@python.org > > Please, how to adapt the following script (to delete blank lines) to delete > lines containing a specific word, or words? > > f=open("output.pdb", "r") > for line in f: > line=line.rstrip() > if line: > print line > f.close() > > If python in Linux accepts lines beginning with # as comment lines, please > also > a script to comment lines containing a specific word, or words, and back, to > remove #. > > Thanks > francesco pietra > > > > > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. > http://tools.search.yahoo.com/newsearch/category.php?category=shopping > Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete lines containing a specific word
--- Martin Marcher <[EMAIL PROTECTED]> wrote: > On Sunday 06 January 2008 18:21 Francesco Pietra wrote: > > > Please, how to adapt the following script (to delete blank lines) to > > delete lines containing a specific word, or words? > > > > f=open("output.pdb", "r") > > for line in f: > > line=line.rstrip() > > if line: > > print line > > f.close() > > >>> import re > >>> s = ["hello", "world", "", "\t ", " ", "#asdfasdf"] > >>> pattern = re.compile("^\s*$") > >>> #only "hello" should be printed as "world" is a word we want to skip > >>> for line in s: > ... if "world" in line: > ... continue > ... if pattern.match(line): > ... continue > ... if line.startswith("#"): > ... continue > ... print line > ... > hello > >>> > > you have to adapt it to be able to match more than a single word > > > If python in Linux accepts lines beginning with # as comment lines, please > > also a script to comment lines containing a specific word, or words, and > > back, to remove #. > > yes lines starting with a "#" are comments in python but that shouldn't be > of concern for your input data. I don't quite get what you want here... Leaving the lines commented out would permit to resume them or at least remeber what was suppressed. During trial and error set up of a calculation one never knows exactly the outcome thanks francesco > > hth > martin > > -- > http://noneisyours.marcher.name > http://feeds.feedburner.com/NoneIsYours > > -- > http://mail.python.org/mailman/listinfo/python-list > Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete lines containing a specific word
Steven: Thanks. See below please (of very marginal interest) --- Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > > > Please, how to adapt the following script (to delete blank lines) to > > delete lines containing a specific word, or words? > > That's tricky, because deleting lines from a file isn't a simple > operation. No operating system I know of (Windows, Linux, OS X) has a > "delete line" function. As I am at Debian Linux, I do that with grep -v > > Do you really need to delete the lines in place? It would be much simpler > to leave the original data as-is, and create a new file with just the > lines that aren't deleted. > > > > f=open("output.pdb", "r") > > for line in f: > > line=line.rstrip() > > if line: > > print line > > f.close() > > How to adapt this script: > > First, think about what this script does. That is, it goes through each > line, and if the line is not blank, it prints it. > > What do you want it to do instead? You want it to print the line if the > line doesn't contain a specific word. So that's the first thing you need > to change. > > Secondly, you might want the script to write its output to a file, > instead of printing. So, instead of the line "print line", you want it to > write to a file. may be cumbersome, though I use 2>&1 | tee output file.pdb so that I can see what happens on the screen and have the modified file. > > Before you can write to a file, you need to open it. So you will need to > open another file: you will have two files open, one for input and one > for output. And you will need to close them both when you are finished. > > Does that help you to adapt the script? > > > > If python in Linux accepts lines beginning with # as comment lines, > > please also a script to comment lines containing a specific word, or > > words, and back, to remove #. > > The same process applies. Instead of "delete line", you want to "comment > line". > > > > -- > Steven > > > -- > http://mail.python.org/mailman/listinfo/python-list > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic inheritance question
On Jan 5, 2008 11:31 AM, <[EMAIL PROTECTED]> wrote: > import tok > > class code: > def __init__( self, start, stop ): > startLoc = start > stopLoc = stop > > class token(code): > pass > Apart from the missing self, remember that the __init__(...) of the base classes is not automatically called, unless you do it explicitly or you do not provide one in the derived class. So for instance you could have something like class token(code): def __init__(self, ...): # do the token specific initialization here # Now init the base class code.__init__(self, ) Or, better, you could use super if you were using new-style classes (which you are not...), like in the following: class token(code): def __init__(self, ...): # do your initialization here super(token, self).__init__() which is much better suited to allow multiple inheritance (there has been a discussion in these days about the MRO, look for a paper by Michele Simionato). Quoting Alex Martelli in Python in a nutshell (page 97): "If you get into the habit of always coding superclass calls with super, your classes will fit smoothly even in complicated inheritance structures. There are no ill effects whatsoever if the inheritance structure instead turns out to be simple, as long, of course, as you're only using the new-style object model, as I recommend". bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete lines containing a specific word
--- Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote: > > > Steven: > > Thanks. See below please (of very marginal interest) > > > > --- Steven D'Aprano <[EMAIL PROTECTED]> wrote: > > > >> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote: > >> > >> > Please, how to adapt the following script (to delete blank lines) to > >> > delete lines containing a specific word, or words? > >> > >> That's tricky, because deleting lines from a file isn't a simple > >> operation. No operating system I know of (Windows, Linux, OS X) has a > >> "delete line" function. > > > > As I am at Debian Linux, I do that with grep -v > > grep doesn't delete lines. grep matches lines. If you want to delete > them, you still have to do the rest of the job yourself. Well, I use Debian Linux for scientific purposes, so that I have no much time toget expertise even in the OS. Though, from the command (as user) grep -v theword thefile.pdb I get thefile.pdb without the lines containing "theword". > > > >> Secondly, you might want the script to write its output to a file, > >> instead of printing. So, instead of the line "print line", you want it > >> to write to a file. > > > > may be cumbersome, though I use 2>&1 | tee output file.pdb so that I > > can see what happens on the screen and have the modified file. > > Yes, matching lines and sending them to stdout is a better solution than > trying to delete them from a file. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete lines containing a specific word
As I said I am no expert in OS and commands, except on what concerns mechanical statistical and quantum mechanical calculations. Therefore, better for me (and for all guys here) if I stop on this matter. My reply is only to say that I did the job with: 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() It took time on the billion lines to write, though it worked. About grep may be you are right. At any event, in my job I never edit a file without saving a separate copy of the original. Think that I'll never carry out a computation (that may last weeks) without a raid 1 system. Not to mention certain commercial OS that are carefully avoided for calculations (in my office for everything), also because they need to emulate unix to do that. cheers francesco --- Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Mon, 07 Jan 2008 00:42:01 +, Grant Edwards wrote: > > >> If you want to delete them, you still have to do the rest of the job > >> yourself. > > > > Nonsense. > > > > How is this not doing what the OP asks? > > > >grep -v pattern infile >outfile; mv outfile infile > > It isn't deleting lines. As abstractions go, it comes pretty close, but > just try it on a disk with insufficient free space for the temporary > outfile and watch it break. > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
Strip lines from files
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() to strip lines containing the word WAT from a very long file. A variant need has now emerged, to perform the same task from a very long series of shorter files trp.pdb.1, trp.pdb.2 ,. Could you see how to adapt the above script to the new need? Or adapt grep -v WAT trp.pdb.1 grep -v WAT trp.pdb.2 grep -v WAT trp.pdb.n Unless you can think better to remove that pervasive molecule of water, to avoid performing the calculation ex novo. Thanks francesco pietra Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Paid subscription Python magazines
On Jan 8, 2008 11:17 AM, Jon Harrop <[EMAIL PROTECTED]> wrote: > > Are there any Python magazines that you can pay to subscribe to? (either > paper or on-line). > Python Magazine comes to mind www.pythonmagazine.com I am subscribed and find it very good. Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: copy a numpy array
On Jan 8, 2008 4:32 PM, jimgardener <[EMAIL PROTECTED]> wrote: > hi, > (i posted this to numpy discussion grp couple of days back ..but it > fails to appear..)since it is needed for my work i would appreciate if > anyone can help me with this question > > > i have two ndarrays of 1000 elements each and want to copy all > elements from srcarray to destarray > > srcarray=numpy.array( [3973334.8381791776,,382999.6748692277] ) > > arrsize=1000 > destarray=zeros(arrsize) > > i copied all items from src to dest by using > destarray[0:arrsize]=srcarray[0:arrsize] > > i don't know if this is the right way to do the copying. > is there a better(efficient?) way ? > jim If you want the array to share the data, just use destarray = numpy.array(srcarray) Otherwise you can set the copy flag to False: destarray = numpy.array(srcarray,copy=False) bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: copy a numpy array
On Jan 9, 2008 6:35 AM, jimgardener <[EMAIL PROTECTED]> wrote: > thanx guys for the replies > need a little clarification > > srcarray=array([1.2,2.3,3.4,4.5,5.6]) > destarray=array(srcarray,copy=False) > > then > srcarray[2]=99.9 > will cause the change to be reflected in both src and dest. > doesn't that mean data is shared between both arrays? > > but if i do > destarray=array(srcarray) > or > destarray=srcarray.copy() > then the change in one array will not affect the other,meaning no data > sharing > ...want to know if my understanding is right > jim You're right, I wrote too quickly and so I gave a wront information! sorry! :-) Just try the following: Apart from the copy method (which other have correctly pointed to), the correct version is simply: a = numpy.array([1,2]) b = numpy.array(a) and now try modifying one of them. bye Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Analyzing Python GC output - what is a "cell", and what information is available about it.
On Jan 11, 2008 6:20 PM, John Nagle <[EMAIL PROTECTED]> wrote: > Tried: > print item.dir() > got: > 'cell' object has no attribute 'dir' I don't know nothing about cell objects... but why don't you try dir(item) instead? Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: csv add lines
On Jan 14, 2008 3:52 PM, Alexandru Dumitrescu <[EMAIL PROTECTED]> wrote: > > > Hi, > I'm new to this list and to python. > > I am wondering, am I able to make my program read the *.txt files from a > directory and > > to add, at the top of the file, three new lines which are stored in a *.csv > file? Maybe you are still not able to do it :-) But if you give a look at the csv module you probably will be in a short time. Just read http://docs.python.org/lib/module-csv.html where you will learn how to parse a csv file. bye, Francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter. Why the Need for a Frame, or no Frame?
On Sat, 16 Feb 2008 19:40:51 -0800, W. Watson wrote: > from Tkinter import * > > class App: > def __init__(self, master): > fm = Frame(master) > Button(fm, text='Left').pack(side=LEFT) > Button(fm, text='This is the Center button').pack(side=LEFT) > Button(fm, text='Right').pack(side=LEFT) > fm.pack() > > root = Tk() > root.option_add('*font', ('verdana', 12, 'bold')) > root.title("Pack - Example 2") > display = App(root) > root.mainloop() The obvious question is: why don't you run both and see what happens? Anyway, Tk() already opens a frame, so in the first example the buttons are created inside that frame, while in the second example two frames are created: the one creaded by Tk() il left empty but you should see it (maybe very small in a corner) if you run the program. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyparsing help
Il Sat, 22 Mar 2008 14:11:16 -0700, rh0dium ha scritto: > Hi all, > > I am struggling with parsing the following data: > > test1 = """ > Technology { > name= "gtc" dielectric >= 2.75e-05 unitTimeName > = "ns" timePrecision = 1000 > unitLengthName = "micron" > lengthPrecision = 1000 gridResolution > = 5 > unitVoltageName = "v" voltagePrecision > = 100 unitCurrentName = > "ma" currentPrecision= 1000 > unitPowerName = "pw" powerPrecision > = 1000 unitResistanceName = > "kohm" resistancePrecision = 1000 > unitCapacitanceName = "pf" > capacitancePrecision= 1000 > unitInductanceName = "nh" > inductancePrecision = 100 > } > > Tile"unit" { > width = 0.22 height > = 1.69 > } > > Did you think of using something a bit more sofisticated than pyparsing? I have had a good experience to using ply, a pure-python implementation of yacc/lex tools, which I used to extract significant data from C programs to automatize documentation. I never used before yacc or similar tools, but having a bit of experience with BNF notation, I found ply easy enough. In my case, the major problem was to cope with yacc limitation in describing C syntax (which I solved by "oelaxing" the rules a bit, since I was going to process only already- compiled C code). In your much simpler case, I'd say that a few production rules should be enough. P.S : there are others, faster and maybe more complete python parser, but as I said ply is pure python: no external libraries and runs everywhere. Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
python library to manipulate PALM documents ?
Hi all, anybody knows a python equivalent of the perl PALM::Doc module (and eventually other PALM::). I have a e-book device wich reads mobi-pocket format (among others). I have downloaded from a forum a set of perl scripts to convert HTML to unencripted mobipocket format and vice-versa. It uses the PALM:: package. I would attempt (for my convenience and for the fun of it) to make a python equivalent of that. Hence my quest for a Palm::Doc equivalent. My googling up to now resulted in nothing relevant. Keeping searching ... Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Disable resize button
Il Mon, 24 Mar 2008 04:38:50 -0700, myonov ha scritto: > Hi! > > I need to disable resize button in Tkinter. I inherit the Frame class. > Then in the constructor i make my buttons, labels, etc. Then I pack them > and when move borders of the frame everything changes it's location and > it looks really bad. How can I change that? > That's my code: > # -*- coding: cp1251 -*- > import Tkinter > > class App(Tkinter.Frame): > def click(self): > pass > > def click2(self): > pass > > def __init__(self, master=None): > Tkinter.Frame.__init__(self, master, width = 700, height = > 400,\ >bg = "#99") > self.pack() > > # Buttons > > self.b1 = Tkinter.Button(self, text = u"Добави Книга",\ > command=self.click, font = "Courier", > \ > fg = "red") > self.b2 = Tkinter.Button(self, text = u"Добави читател",\ > command=self.click2, font = "Courier", > \ > fg = "red") > self.b1.place(relx = 0.75, rely = 0.3) self.b2.place(relx = > 0.75, rely = 0.4) > > # Labels > > self.l1 = Tkinter.Label(self, font = "Courier", height = 4,\ > text = u"Информация", fg = "#ff",\ > bg = "#99") > self.l1.place(x = 275, y = 10) > > # Text Control > #self.txt = Tkinter.Text(self, bg = "#124456", ) # > self.txt.pack() > > You could try including the frame in a toplevel window (e.g. passing Tkinter.Tk() as super) and then doing super.wm_resizable(None, None) A better idea would be using pack instead of place, leaving to the toolkit the job of rearranging the widgets when the window is enlarged or reduced. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: python library to manipulate PALM documents ?
Il Mon, 24 Mar 2008 12:08:59 -0300, Guilherme Polo ha scritto: > 24 Mar 2008 13:36:13 GMT, Francesco Bochicchio <[EMAIL PROTECTED]>: >> Hi all, >> >> anybody knows a python equivalent of the perl PALM::Doc module (and >> eventually other PALM::). >> >> I have a e-book device wich reads mobi-pocket format (among others). I >> have downloaded from a forum a set of perl scripts to convert HTML to >> unencripted mobipocket format and vice-versa. It uses the PALM:: >> package. I would attempt (for my convenience and for the fun of it) to >> make a python equivalent of that. Hence my quest for a Palm::Doc >> equivalent. >> >> > I'm not sure if it is what you are after, but it seems to be, check > this: http://pypi.python.org/pypi/PalmDB/1.8.1 > It could be. I read that mobipocket files may have extension .prc. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Shortcutting the function call stack
Il Mon, 24 Mar 2008 15:05:38 -0700, Julien ha scritto: ... > > I'll try to explain a bit more what I'm after, and hopefully that will > be clearer. In fact, what I'm trying to do is to "hijack" (I'm making up > the term) a function: > > def hijacker(arg): > if I_feel_its_necessary: > hijack_caller_function_and_make_it_return(1) > > def my_function1(arg): > hijacker(something) > ... # Continue as normal > return 2 > > def my_function2(arg): > ... # Maybe do some processing here > hijacker(whatever) > ... # Continue as normal > return 3 > > > You could simply do something like: def hijacker(arg): if I_feel_its_necessary: return True, 1 else: return False, 0 def my_function1(arg): abort, code = hijiacker(something); if abort: return code ... # Continue as normal return 2 def my_function2(arg): ... # Maybe do some processing here abort, code = hijiacker(whatever); if abort: return code ... # Continue as normal return 3 Although purists may frown upon the double return statement, it is still a much cleaner code than using some magic to abort the caller function. And tou have only to add two lines - always the same - at each function. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.2.1 and select()
Il Mon, 24 Mar 2008 17:58:42 -0400, Derek Martin ha scritto: > Hi kids! > > I've got some code that uses select.select() to capture all the output > of a subprocess (both stdout and stderr, see below). This code works as > expected on a variety of Fedora systems running Python > 2.4.0, but on a > Debian Sarge system running Python 2.2.1 it's a no-go. I'm thinking > this is a bug in that particular version of Python, but I'd like to have > confirmation if anyone can provide it. > > The behavior I see is this: the call to select() returns: [ corresponding to sub-proc's STDOUT>] [] [] > > If and only if the total amount of output is greater than the specified > buffer size, then reading on this file hangs indefinitely. For what it's > worth, the program whose output I need to capture with this generates > about 17k of output to STDERR, and about 1k of output to STDOUT, at > essentially random intervals. But I also ran it with a test shell > script that generates roughly the same amount of output to each file > object, alternating between STDOUT and STDERR, with the same results. > > Yes, I'm aware that this version of Python is quite old, but I don't > have a great deal of control over that (though if this is indeed a > python bug, as opposed to a problem with my implementation, it might > provide some leverage to get it upgraded)... Thanks in advance for any > help you can provide. The code in question (quite short) follows: > > def capture(cmd): > buffsize = 8192 > inlist = [] > inbuf = "" > errbuf = "" > > io = popen2.Popen3(cmd, True, buffsize) inlist.append(io.fromchild) > inlist.append(io.childerr) > while True: > ins, outs, excepts = select.select(inlist, [], []) for i in ins: > x = i.read() > if not x: > inlist.remove(i) > else: > if i == io.fromchild: > inbuf += x > if i == io.childerr: > errbuf += x > if not inlist: > break > if io.wait(): > raise FailedExitStatus, errbuf > return (inbuf, errbuf) > > If anyone would like, I could also provide a shell script and a main > program one could use to test this function... >From yor description, it would seem that two events occurs: - there are actual data to read, but in amount less than bufsize. - the subsequent read waits (for wathever reason) until a full buffer can be read, and therefore lock your program. Try specifying bufsize=1 or doing read(1). If my guess is correct, you should not see the problem. I'm not sure that either is a good solution for you, since both have performance issues. Anyway, I doubt that the python library does more than wrapping the system call, so if there is a bug it is probably in the software layers under python. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Implementing file reading in C/Python
On Fri, 09 Jan 2009 15:34:17 +, MRAB wrote: > Marc 'BlackJack' Rintsch wrote: >> On Fri, 09 Jan 2009 04:04:41 +0100, Johannes Bauer wrote: >> >>> As this was horribly slow (20 Minutes for a 2GB file) I coded the whole >>> thing in C also: >> >> Yours took ~37 minutes for 2 GiB here. This "just" ~15 minutes: >> >> #!/usr/bin/env python >> from __future__ import division, with_statement >> import os >> import sys >> from collections import defaultdict >> from functools import partial >> from itertools import imap >> >> >> def iter_max_values(blocks, block_count): >> for i, block in enumerate(blocks): >> histogram = defaultdict(int) >> for byte in block: >> histogram[byte] += 1 >> >> yield max((count, byte) >> for value, count in histogram.iteritems())[1] >> > [snip] > Would it be faster if histogram was a list initialised to [0] * 256? I tried it on my computer, also getting character codes with struct.unpack, like this: histogram = [0,]*256 for byte in struct.unpack( '%dB'%len(block), block ): histogram[byte] +=1 yield max(( count, byte ) for idx, count in enumerate(histogram))[1] and I also removed the map( ord ... ) statement in main program, since iter_max_values mow returns character codes directly. The result is 10 minutes against the 13 of the original 'BlackJack's code on my PC (iMac Intel python 2.6.1). Strangely, using histogram = array.array( 'i', [0,]*256 ) gives again 13 minutes, even if I create the array outside the loop and then use histogram[:] = zero_array to reset the values. Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Re: pep 8 constants
On Wed, 14 Jan 2009 08:13:30 +, Steven D'Aprano wrote: > > Absolutely. It's rather sad that I can do this: > > import math > math.pi = 3.0 > > I like the ability to shoot myself in the foot, thank you very much, but > I should at least get a warning when I'm about to do so: > > math.PI = 3.0 # use God-like powers to change a constant > > Constants would be a nice addition in python, sure enough. But I'm not sure that this can be done without a run-time check every time the constant is used, and python is already slow enough. Maybe a check that is disabled when running with optimizing flags ? But I'm sure this discussion has been already made and the FINAL WORD has been already spoken. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: file write collision consideration
On Tue, 20 Jan 2009 11:08:46 -0500, D'Arcy J.M. Cain wrote: > On Tue, 20 Jan 2009 10:57:52 -0500 > RGK wrote: >> I have a thread that is off reading things some of which will get >> written into a file while another UI thread manages input from a user. >> >> The reader-thread and the UI-thread will both want to write stuff to the >> same output file. What first comes to mind is that there may be write >> collisions, ie both trying to write at the same time. > > Why not create a third thread that handles the write? The other > threads can simply add objects to a queue. You will still need > collision handling in the queue adder but it only needs to block for a > small time as opposed to the much longer disk write time. IIRC, Queue.Queue objects handle by themselves multi-thread access, that is there is no need to additional locking mechanism ... Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
New filters? was: Re: Bitwise 2009 ($5000 prize money)
On Tue, Feb 3, 2009 at 6:56 PM, Steve Holden wrote: > Thanks you so much, Christof. The spam filters successfully kept this > URL out of c.l.py until you took the trouble to re-publish it. > > regards > Steve > Speaking of which: it seems to me that the amount of spam that I receive from clpy has greatly reduced in the last month or so. So it seems that the spam filters are doing a great job. Thanks are due to the people managing them :-) Francesco -- http://mail.python.org/mailman/listinfo/python-list