ANN: progressbar 2.2 - Text mode progressbar for console applications
Text progressbar library for python. http://cheeseshop.python.org/pypi/progressbar This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when the terminal size is changed. It's also efficient, because the text is only updated if need, with a minimum overhead in the case there is no need for updating. It was tested and works under windows, linux and macosx. And should also work in many other untested operating systems. You may get it from pypi: http://cheeseshop.python.org/pypi/progressbar Thanks, Nilton. -- Nilton Volpato email: [EMAIL PROTECTED] % ('nilton', 'volpato') -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
PyYAML-3.01: Initial Release
PyYAML: YAML parser and emitter for Python == YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. You may download PyYAML from http://pyyaml.org/wiki/PyYAML. Example === import yaml yaml.load( ... name: PyYAML ... version: 3.01 ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... ) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'version': 3.01, 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} print yaml.dump(_) homepage: http://pyyaml.org/wiki/PyYAML version: 3.01 name: PyYAML keywords: [YAML, serialization, configuration, persistance, pickle] description: YAML parser and emitter for Python Links = PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.01.win32.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core Changes === * Initial release. The version number reflects the codename of the project (PyYAML 3000) and differenciates it from the abandoned PyYaml module. Copyright = The PyYAML module is written by Kirill Simonov [EMAIL PROTECTED]. PyYAML is released under the MIT license. -- xi -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
released: RPyC 2.55
Remote Python Call (RPyC) - transparent and symmetrical python RPC and distributed computing library download and info: http://rpyc.wikispaces.com full changelog: http://rpyc.wikispaces.com/changelog release notes: http://rpyc.wikispaces.com/release+notes major changes: * added isinstance and issubclass for remote objects * moved to tlslite for authentication and encryption * added server discovery (using UDP broadcasts) * refactoring -tomer -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: A critic of Guido's blog on Python's lambda
Tomasz Zielonka [EMAIL PROTECTED] wrote: ... Also, having anonymous functions doesn't take your common sense away, so you still have a chance. I've seen many people (presumably coming from Lisp or Scheme) code Python such as: myname = lambda ... rather than the obvious Python way to do it: def myname(... ((they generally do that right before they start whining that their absurd choice doesn't let them put statements inside the unnamed function that they need to assign to a name)). _THAT_ is what having many semantically overlapping (or identically equivalent) ways to perform the same task does to people: it takes the common sense away from enough of them that I'm statistically certain to have to wrestle with some of them (be it as suppliers, people I'm trying to help out on mailing lists etc, students I'm mentoring -- at least being at Google means I don't have to fear finding such people as my colleagues, but the memories and the scars of when I was a freelance consultant are still fresh, and my heart goes out to the 99% of sensible Pythonistas who don't share my good luck). As long as Guido planned to remove lambda altogether in Python 3.0, I could console myself with the thought that this frequent, specific idiocy wasn't one I would have to wrestle with forever; now I know I will have no such luck -- it's back to the dark ages. ((If I ever _DO_ find a language that *DOES* mercilessly refactor in pursuit of the ideal only one obvious way, I may well jump ship, since my faith in Python's adherence to this principle which I cherish so intensely has been so badly broken by GvR's recent decisions to keep lambdas, keep [genexp] as an identical synonym for list(genexp), add {1,2,3} as an identical synonym for set((1,2,3))...); though, being a greedy fellow, I'll probably wait until all my Google options have vested;-)). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Patrick May [EMAIL PROTECTED] wrote: ...an alleged reply to me, which in fact quotes (and responds to) only to statements by Brian, without mentioning Brian... Mr May, it seems that you're badly confused regarding Usenet's quoting conventions. You may want to repeat your answer addressing specifically the poster you ARE apparently answering. Nevertheless, I'll share my opinions: Using lambda in an expression communicates the fact that it will be used only in the scope of that expression. Another benefit is that declaration at the point of use means that all necessary context is available without having to look elsewhere. Those are two pragmatic benefits. You still need to look a little bit upwards to the point of use, almost invariably, to see what's bound to which names -- so, you DO have to look elsewhere, nullifying this alleged benefit -- looking at the def statement, immediately before the point of use, is really no pragmatic cost when you have to go further up to get the context for all other names used (are they arguments of this function, variables from a lexically-containing outer function, assigned somewhere...), which is almost always. And if you think it's an important pragmatic advantage to limit potential scope drastically, nothing stops you from wrapping functions just for that purpose around your intended scope -- me, I find that as long as functions are always kept small (as they should be for a host of other excellent reasons anyway), the ambiguity of scope being between the def and the end of the containing function is nil (literally nil when the statement right after the def, using the named function, is a return, as is often the case -- pragmatically equivalent to nil when the statements following the def are 1 but sufficiently few). Your pragmatic benefits, if such they were, would also apply to the issue of magic numbers, which was discussed in another subthread of this unending thread; are you therefore arguing, contrary to widespread opinion [also concurred in by an apparently-Lisp-oriented discussant], that it's BETTER to have magic unexplained numbers appear as numeric constants out of nowhere smack in the middle of expressions, rather than get NAMED separately and then have the names be used? If you really believe in the importance of the pragmatic benefits you claim, then to be consistent you should be arguing that...: return total_amount * 1.19 is vastly superior to the alternative which most everybody would deem preferable, VAT_MULTIPLIER = 1.19 return total_amount * VAT_MULTIPLIER because the alternative with the magic number splattered inexplicably smack in the middle of code communicated the fact that it's used only within that expression, and makes all context available without having to look elsewhere (just one statement up of course, but then this would be identically so if the one statement up was a def, and we were discussing named vs unnamed functions vs magic numbers). 3. It adds another construction to the language. That's a very minimal cost relative to the benefits. To my view of thinking, offering multiple semantically equivalent ways (or, perhaps worse, nearly equivalent but with subtle differences ones) to perform identical tasks is a *HUGE* conceptual cost: I like languages that are and stay SMALL and SIMPLE. Having only one obvious way to do it is just an ideal, but that's no reason to simply abrogate it when it can so conveniently be reached (my only serious beef with Python it has it *HAS* abdicated the pursuit of that perfect design principle by recent decisions to keep lambda, and to keep the syntax [genexp] as an identical equivalent to list(genexp), in the future release 3.0, which was supposed to simplify and remove redundant stuff accreted over the years: suddenly, due to those decisions, I don't really look forward to Python 3.0 as I used to - though, as I've already mentioned, being a greedy fellow I'll no doubt stick with Python until all my Google options have vested). You haven't made your case for named functions being preferable. I think it's made at least as well as the case for using constant-names rather than magic numbers numeric constants strewn throughout the code, and THAT case is accepted by a wide consensus of people who care about programming style and clarity, so I'm pretty happy with that. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Ken Tilton wrote: Alexander Schmolck wrote: [trimmed groups] Ken Tilton [EMAIL PROTECTED] writes: yes, but do not feel bad, everyone gets confused by the /analogy/ to spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief period I swore off the analogy because it was so invariably misunderstood. Even Graham misunderstood it. Count me in. g But looking at what it says: Think of the slots as cells in a spreadsheet (get it?), and you've got the right idea. , if you follow the analogy (and know that slot means data member in other OO models) you also know that Serge's Spreadsheet example would have scored a big fat zero on the Miller Analogy Test. Serge in no way made slots in Python classes behave like cells in a spreadsheet. He simply started work on a Spreadsheet application, using Python classes along the way. Bzzt. While everyone makes the mistake, it is only because few of us (me included) read very carefully. Especially if they are more interested in flaming than learning what someone is saying. I don't really mean any disrespect here, but if an analogy is not interpreted correctly by a large group of people, the analogy is crap, not the people. Yes, I understood it, specifically because I have spent enough time dinking around with cell functions in a spreadhseet to understand what you meant. Maybe it would help to change the wording to functions with cell references in a spreadsheet instead of cells in a spreadsheet. Yes, you lose the quippy phrasing but as it is most people use spreadsheets as simple database with informal ad hoc schema and mostly ignore the more powerful features anyways, so explicit language would probably help the analogy. I'm guessing if you made some vague allusions to how sum(CellRange) works in most spreadsheets people would get a better idea of what is going on. -- http://mail.python.org/mailman/listinfo/python-list
ANN: progressbar 2.2 - Text mode progressbar for console applications
Text progressbar library for python. http://cheeseshop.python.org/pypi/progressbar This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when the terminal size is changed. It's also efficient, because the text is only updated if need, with a minimum overhead in the case there is no need for updating. It was tested and works under windows, linux and macosx. And should also work in many other untested operating systems. You may get it from pypi: http://cheeseshop.python.org/pypi/progressbar Thanks, Nilton. -- Nilton Volpato email: [EMAIL PROTECTED] % ('nilton', 'volpato') -- http://mail.python.org/mailman/listinfo/python-list
Re: why _import__ only works from interactive interpreter?
You are absolutely right, it's that empty entry that allows the absolute path to work. I'll probably add the path to sys.path, but as this is only a config file from which I need just a few vars, I'll try to use execfile, looking in past threads it looks like a better option for this use, I really don't need the new path, it could introduce subtle bugs as it is not something expected. Any equivalent way of doing the same with execfile? -- http://mail.python.org/mailman/listinfo/python-list
New pyparsing wiki
I've converted the pyparsing project home page to a wiki, hosted at http://pyparsing.wikispaces.com/ Please come and visit the new pyparsing project site, and add your contributions to the public Tips and Documentation pages! Thanks! -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Why list.sort() don't return the list reference instead of None?
L = [4,3,2,1] L=L.sort() L will refer to None, why L.sort() don't return the L? I want to ask why the designer of Python do so? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
[EMAIL PROTECTED] wrote: L = [4,3,2,1] L=L.sort() L will refer to None, why L.sort() don't return the L? I want to ask why the designer of Python do so? http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
[EMAIL PROTECTED] wrote: L = [4,3,2,1] L=L.sort() L will refer to None, why L.sort() don't return the L? I want to ask why the designer of Python do so? Because that's the convention that signifies that a Python method mutates the object rather than returns a new one. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis Sitting in the den and / Looking at the phone as if it owed / Owed me a favor -- Blu Cantrell -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
[EMAIL PROTECTED] [EMAIL PROTECTED] writes: I want to ask why the designer of Python do so? I'm not a Python core developer nor a designer but I've always known that sort() is a in-place sort and since the list is a mutable object it mutates the list sending the sort() message. If you want to get back a sorted iterable use... sorted :) L = [3, 1, 2] ls = sorted(L) now ls is your list, sorted. -- Lawrence - http://www.oluyede.org/blog Nothing is more dangerous than an idea if it's the only one you have - E. A. Chartier -- http://mail.python.org/mailman/listinfo/python-list
Re: Only one obvious way...
If I ever _DO_ find a language that *DOES* mercilessly refactor in pursuit of the ideal only one obvious way, I may well jump ship, since my faith in Python's adherence to this principle which I cherish so intensely has been so badly broken ... The phrase only one obvious way... is nearly the most absurd marketing bullshit I have ever heard; topped only by it fits your brain. Why are so many clearly intelligent and apparently self-respecting hard-core software engineers repeating this kind of claptrap? It sounds more like a religious cult than a programming language community. If one of my students answered the question: Why use X for Y? with X fits your brain. or There's only one obvious way to do Y in X. I'd laugh out loud before failing them. -- http://mail.python.org/mailman/listinfo/python-list
Re: which is better, string concatentation or substitution?
fuzzylollipop wrote: niether .join() is the fastest Please quote what you're replying to. No, it's the slowest: [EMAIL PROTECTED]:~$ python -m timeit 'p%s/p\n\n' % 'foobar' 100 loops, best of 3: 0.607 usec per loop [EMAIL PROTECTED]:~$ python -m timeit 'p' + 'foobar' + '/p\n\n' 100 loops, best of 3: 0.38 usec per loop [EMAIL PROTECTED]:~$ python -m timeit ''.join(['p', 'foobar', '/p\n\n']) 100 loops, best of 3: 0.817 usec per loop -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a column from a file
f = open(datafile.txt, r) data = [line.split('\t') for line in f] f.close() pressure = [float(d[1]) for d in data] temp = [float(d[2]) for d in data] --- This will parse the file into a matrix stored in 'data'. The last two lines simply iterate through second and third columns respectively, converting each element to a float (from string as it was read in from file) and assign to the appropriate vars. -- http://mail.python.org/mailman/listinfo/python-list
Tkfont.families does not list all installed fonts
Hi, I have installed a truetype font (.ttf) on a linux machne (SUSE linux 10, KDE) by copying it to my .fonts folder. I can use the font in all applications like open-office and firefox browser. However, I cannot use the font in a python app that I am writing. The list returned by Tkfont.families does not contain this particular font. Any suggestions ? Regards, -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting HTTP responses - a python linkchecking script.
[EMAIL PROTECTED]: with urllib2 it doesn't seem possible to get HTTP status codes. except urllib2.HTTPError, e: if e.code == 403: -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: why _import__ only works from interactive interpreter?
Sorry to follow up myself, I've finally used the execfile approach, passing an empty dict for capturing locals and then just processing it: new_settings = {} execfile(self.SETTINGS_MODULE, new_settings) # returns its locals in new_settings # assign UPPER_CASE vars for setting in new_settings.keys(): setting_value = new_settings[setting] # do what you want with the vars It looks like a better solution than polluting the namespace and allows to use any file as a config file withou the need to have it on sys.path. -- http://mail.python.org/mailman/listinfo/python-list
ANN: progressbar 2.2 - Text mode progressbar for console applications
Text progressbar library for python. http://cheeseshop.python.org/pypi/progressbar This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when the terminal size is changed. It's also efficient, because the text is only updated if need, with a minimum overhead in the case there is no need for updating. It was tested and works under windows, linux and macosx. And should also work in many other untested operating systems. You may get it from pypi: http://cheeseshop.python.org/pypi/progressbar Thanks, Nilton. -- Nilton Volpato email: [EMAIL PROTECTED] % ('nilton', 'volpato') -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
[EMAIL PROTECTED] [EMAIL PROTECTED] writes: However, I wonder why L.sort() don't return the reference L, the performance of return L and None may be the same. It's not the same. sort() does not return anything. Why? I've just explained to you and so the others: by default operations on mutable objects are in place. s = abc s.upper() does return another string. String are immutable references. -- Lawrence - http://www.oluyede.org/blog Nothing is more dangerous than an idea if it's the only one you have - E. A. Chartier -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting HTTP responses - a python linkchecking script.
Rene Pijlman wrote: [EMAIL PROTECTED]: with urllib2 it doesn't seem possible to get HTTP status codes. except urllib2.HTTPError, e: if e.code == 403: Thanks. Is there documentation for this available somewhere online, I can't see it to obviously in the library reference? Cheers, -Blair -- http://mail.python.org/mailman/listinfo/python-list
Python's regular expression?
Hi all, I am a C/C++/Perl user and want to switch to Python (I found Python is more similar to C). Does Python support robust regular expression like Perl? And Python and Perl's File content manipulation, which is better? Any suggestions will be appreciated! Best regards, Davy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Davy [EMAIL PROTECTED] writes: Does Python support robust regular expression like Perl? Yep, Python regular expression is robust. Have a look at the Regex Howto: http://www.amk.ca/python/howto/regex/ and the re module: http://docs.python.org/lib/module-re.html -- Lawrence - http://www.oluyede.org/blog Nothing is more dangerous than an idea if it's the only one you have - E. A. Chartier -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
[EMAIL PROTECTED] enlightened us with: However, I wonder why L.sort() don't return the reference L, the performance of return L and None may be the same. It's probably because it would become confusing. Many people don't read the documentation. If L.sort() returns a sorted version of L, they would probably assume it didn't do an in-place sort. The effects of an unexpected in-place sort are much harder to track down and debug than a function returning None. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
printing out elements in list
hi i have a list with contents like this alist = ['QWER' , 'askfhs', 'REWR' ,'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' ] how can i convert this list into a dictionary such that dictionary = { 'QWER':'askfhs' , 'REWR' : 'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' } thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting HTTP responses - a python linkchecking script.
[EMAIL PROTECTED]: Rene Pijlman wrote: [EMAIL PROTECTED]: with urllib2 it doesn't seem possible to get HTTP status codes. except urllib2.HTTPError, e: if e.code == 403: Thanks. Is there documentation for this available somewhere online, I can't see it to obviously in the library reference? No, this seems to be missing from the documentation. -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi Davy wrote: I am a C/C++/Perl user and want to switch to Python OK (I found Python is more similar to C). ;-) More similar than what? Does Python support robust regular expression like Perl? It supports them fairly good, but it's not 'integrated' - at least it feels not integrated for me ;-) If you did a lot of Perl, you know what 'integrated' means ... And Python and Perl's File content manipulation, which is better? What is a 'file content manipulation'? Did you mean 'good xxx level file IO', where xxx means either 'low' or 'high'? Any suggestions will be appreciated! Just try to start a small project in Python - from source that you already have in C or Perl or something. Regards Mirco -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
Using slices and built-in zip: alist = ['QWER' , 'askfhs', 'REWR' ,'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' ] dict(zip(alist[::2], alist[1::2])) {'QWER': 'askfhs', 'FGDG': 'sdfsdgffdgfdg', 'REWR': 'sfsdf'} Slightly more efficient might be to use izip from itertools: from itertools import izip dict(izip(alist[::2], alist[1::2])) {'QWER': 'askfhs', 'FGDG': 'sdfsdgffdgfdg', 'REWR': 'sfsdf'} And perhaps using islice from iterools might improve efficiency even more: from itertools import islice, izip dict(izip(islice(alist, 0, None, 2), islice(alist, 1, None, 2))) {'QWER': 'askfhs', 'FGDG': 'sdfsdgffdgfdg', 'REWR': 'sfsdf'} (I didn't try to time any of these solutions so I have no real idea which is more efficient, but using iterators from the itertools-module should in theory mean you create less temporary objects; especially with large lists this can be a win) Cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: which is better, string concatentation or substitution?
Leif K-Brooks wrote: fuzzylollipop wrote: niether .join() is the fastest Please quote what you're replying to. No, it's the slowest: [EMAIL PROTECTED]:~$ python -m timeit 'p%s/p\n\n' % 'foobar' 100 loops, best of 3: 0.607 usec per loop [EMAIL PROTECTED]:~$ python -m timeit 'p' + 'foobar' + '/p\n\n' 100 loops, best of 3: 0.38 usec per loop [EMAIL PROTECTED]:~$ python -m timeit ''.join(['p', 'foobar', '/p\n\n']) 100 loops, best of 3: 0.817 usec per loop If you are only concatenating a few strings together, then straight concatenation will be faster, but when joining many strings together concatenating strings can be much slower compared to join. In the OP's original example: def p(self, paragraph): self.source += 'p' + paragraph + '/p\n\n' it is the concatenation to self.source which is could become the bottleneck, it doesn't really matter how the text of the paragraph assembled. For most purposes use what looks clearest at the time: it isn't worth the hassle of obfuscating your code until you've identified a real cpu hog. On the other hand, the str.join idiom is sufficiently common in Python that sometimes it wins on clarity and simplicity as well. e.g. If you build a list of lines to join then you don't have to repeat '\n' on the end of each component line. BTW, be careful using timeit. I nearly got caught out running your tests: C:\Python25python -m timeit ''.join(['p', 'foobar', '/p\n\n']) 100 loops, best of 3: 0.872 usec per loop C:\Python25python -m timeit 'p' + 'foobar' + '/p\n\n' 1000 loops, best of 3: 0.049 usec per loop C:\Python25python -m timeit 'p%s/p\n\n' % 'foobar' 1000 loops, best of 3: 0.0495 usec per loop C:\Python25cd \python24 C:\Python24python -m timeit ''.join(['p', 'foobar', '/p\n\n']) 100 loops, best of 3: 1.05 usec per loop C:\Python24python -m timeit 'p' + 'foobar' + '/p\n\n' 100 loops, best of 3: 0.359 usec per loop Spot the really fast concatenations in Python 2.5 which is now detecting the constant strings and concatenating them once only. It also does that for the string formatting which only leaves poor old join to actually do any work in these tests. -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
On Mon, 08 May 2006 00:44:39 -0700, micklee74 wrote: i have a list with contents like this alist = ['QWER' , 'askfhs', 'REWR' ,'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' ] how can i convert this list into a dictionary such that dictionary = { 'QWER':'askfhs' , 'REWR' : 'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' } This strikes me as a little bit voodish, but you could do: dictionary = dict(zip(alist[::2], alist[1::2])) -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
thanks for all your replies...I will go test them out.. I was wondering what does this mean alist[1::2]? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Why list.sort() don't return the list reference instead of None?
So you write: for key in sorted(dict.iterkeys()): ... do it ... dict.iterkeys() returns an iterable which doesn't even have a sort-method; and somehow I find it unnatural to apply a 'sort' method to an iterator whereas I find it perfectly natural to feed an iterator to a function that does sorting for anything iterable... Cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
[EMAIL PROTECTED] wrote: When you consider that there was just a big flamewar on comp.lang.lisp about the lack of standard mechanisms for both threading and sockets in Common Lisp (with the lispers arguing that it wasn't needed) I find it curious that someone can say Common Lisp scales well. In comp.lang.python there are often discussions about which is the best web framework or what is the best gui. There seems to be some common meme in these kinds of discussions and the lambda controversy. I'm even ready to expand the concept even more and include documentation problems and polymorphic typing. So what is the big advantage of using parens then that is making people give up documenting their code by naming functions? (See, I'm getting into the right kind of lingo for discussing these kind of questions) Well, there seems to be some advantage to conceptually decoupling a function from what it is doing *now* (which can be easily named) and what it is doing in some other situation. Naming things is only a ballast and makes the mental model not fit the brain (introducing pythonic terminology here for the lispers). This is a lot like polymorphic functions. For example an adding function sometimes adds integers and sometimes floats or complex variables and it can be defined just once without specifying which type of parameters it is going to get. I assume this to be a piece of cake for most lispers and pythoneers, but possibly this could still confuse some static typers. An anonymous function is like a polymorphic function in that it is possible to make the mental model about it polymorphic, instead of just its parameters. This enables the lispers to just take what it does and paste it where that needs to be done (inventing crypto speak here). This is a very effective way of handling operations and it would surprise me if not 99 percent of the Python coders do things mentally this way too and only add names and documentation at the last possible moment (mental compile time documentation procedure). So here we're integrating mental models concerning polymorphism into the way we talk and think about code, and naming things explicitly always seems to be a burden. But now we let the other side of our brain speak for a moment, it was always the side that translated everything we wanted to say to each other here into mental Unicode so that we can hear what the others are saying (further diving into the linguistic pit I am digging here). Yes, communication is what suffers from *not* naming things, and right after it documentation and standardization. How else are we going to communicate our findings verbally to the non coders and the trans coders? Also naming functions and variables can help us create appropriate mental models that 'fix' certain things in place and keep them in the same state, because now they are 'documented'. This promotes people being able to work together and also it enables measuring progress, very important aspects for old world companies who won't understand the way things are evolving (even if they seem to have roaring success at the moment). Not to say that I invented something new, it was always a theme, but now it's a meme,(he, he), the conflict between the scripture and the mysticism. It's such a pity that everyone understands some way or another that mysticism is the way things work but that none wants to acknowledge it. What am I doing here coding Python one might ask, well, the knowledge has to be transfered to my brain first *somehow*, and until someone finds a better way to do that or until there is so much procedural information in my head that I can start autocoding (oh no) that seems to be the better option. Anton -- http://mail.python.org/mailman/listinfo/python-list
Re: python 2.5a2, gcc 4.1 and memory problems
[EMAIL PROTECTED] wrote: Michele Petrazzo wrote: I haven't tried to recompile py 2.4 myself with gcc 4.1 because it is already compiled with it (4.0.3), so I think (only think) that is a py 2.5 problem. I'm right? or I have to compile it with something other switches? Sounds like a gcc problem to me. Try adding --with-pydebug in the configure options. My guess is that it will work. This option enables asserts, but more importantly disables optimization. Yes, with this option it work, but has very bad performances. My guess is that this is an optimization problem with gcc. I assume -fno-strict-aliasing is one of the gcc flags. It should be as this is required for building python. Yes, I specify that flag for compiling, but still the same... Always problems. Also tried with --without-pymalloc and no changes. Cheers, n I think that I'll wait for the firsts debian packages, or compile it with gcc 3.3. Thanks, Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Image SIG ML Moderator does not respond
Calvin Spealman wrote: I have tried repeatedly to make a post to the Image SIG ML, and get nothing but automated responses that I must wait for word from the moderator to approve my posting on the list. I have gotten no reply, positive or not, in over a month. I am assuming the Image SIG moderator is currently MIA. is this the post you're talking about ? http://article.gmane.org/gmane.comp.python.image/2093 /F -- http://mail.python.org/mailman/listinfo/python-list
data entry tool
This post seeks advice on whether python would be appropriate for a task, or whether you can suggest another approach. The project is to transcribe historical records such as schools admissions, ship passenger lists, birth/death/marriages, etc for genealogy studies. What we need is a simple software tool that will give the user a form set out like the page being transcribed, do some simple validation and put the data in a file (can be fixed field length plain text). Data files from volunteers will be compiled into a master database. This software tool needs to work on a variety of different computers; Win95, Win98, WinXP, Mac, Linux. So, would python be a good choice for this, and how should I go about it? I'm not a programmer and have only done a few little python scripts that run from the command line. TIA Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: Need to send email on HIGH Disk usage
[C Saha] | I am looking for a py script which will send me email when | ever my disk becomes more than 90% full. By the way my OS is Win XP. | | If anybody have already has written same type of script or | something very similar kind of script will also be great. You can certainly do this with a WMI event. You might start by combining this example: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#percentage_free with one like this: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#monitor_error_even ts For the event type, you'll need to use Modification. I'm happy to put together an example script for you, but I didn't want to take away the fun of learning! TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: the tostring and XML methods in ElementTree
[EMAIL PROTECTED] wrote: I wanted to see what would happen if one used the results of a tostring method as input into the XML method. What I observed is this: a) beforeCtag.text is of type type 'str' b) beforeCtag.text when printed displays: I'm confused c) afterCtag.text is of type type 'unicode' d) afterCtag.text when printed displays: I?m confused the XML file format isn't a Python string serialization format, it's an XML infoset serialization format. as stated in the documentation, ET always uses Unicode strings for text that contain non-ASCII characters. for text that *only* contains ASCII, it may use either Unicode strings or 8-bit strings, depending on the implementation. the behaviour if you're passing in non-ASCII text as 8-bit strings is undefined (which means that you shouldn't do that; it's not portable). to learn more about Unicode in Python, google for python unicode. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
alist[::2] means taking a slice. You should look up slice-syntax in the tutorials and reference manual. in general, alist[1:5] means: take list elements position 1 up to (excluding) 5. (List indexing starts at position 0, so the first element in the list is not included!) alist[0:5] means: take list elements position 0 up to (excluding) 5; in other words: the first 5 elements. A shortcut for this is: alist[:5] -- omitting an index position means a default of 'start' resp. 'end'. So to take all elements from the 5th to the end of list, you write: alist[4:] (remember that indexing starts at position 0, so 0 is your first element, 4 is your 5th). To take a slice that is the whole list, write: alist[:] Slices discussed so far take all elements in the indicated range, however you can specify a 'step' with your slices. Default step is 1, but to skip every other element you write: alist[::2] Which takes all elements of your list, starting at position 0, adding 2 to the index each step, so next is item 2, then 4, etc, until end of list. Now we have all the 'even-numbered' elements in the list, to get the 'odd-numbered elements' write: alist[1::2] I hope this helps. Cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this with python ?
Your question is insufficiently clear for me to answer. Do you want to know how to read from standard-input in a Python program? Do you want to know how to start an external program from Python, and then connect something to that programs standard input? Do you want to know something else? Please specify! Cheers, --Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
[EMAIL PROTECTED] writes: Alex Martelli wrote: Steve R. Hastings [EMAIL PROTECTED] wrote: ... But the key in the whole thread is simply that indentation will not scale. Nor will Python. This is a curious statement, given that Python is famous for scaling well. I think ridiculous is a better characterization than curious, even if you're seriously into understatement. When you consider that there was just a big flamewar on comp.lang.lisp about the lack of standard mechanisms for both threading and sockets in Common Lisp (with the lispers arguing that it wasn't needed) I find it curious that someone can say Common Lisp scales well. You really need to get better at distinguishing between reality and usenet flamewars. While some comp.lang.lispers were bitching back and forth about this, others of us were in Hamburg listening to Martin Cracauer from ITA talking about Common Lisp in a high-performance search environment. In case you aren't aware, ITA is the company that makes the search engine behind Orbitz. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CHM Doc Contains Broken Links on Linux in xCHM.
Is this a problem with the chm docs themselves OR is it a problem with xCHM? The same chm works just fine on Windows whereas on Linux I am having problems. Anyone experiencing the same? is a fix coming? It's already been fixed. You're running an old version (the screenshot says 1.2). The latest official release version is 1.7.1. I believe that problem has been fixed since 1.7. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a good use of __metaclass__?
Answering to the title of your post, no, this is not a good use of metaclasses. Your problem seems a textbook example of multiple dispatch, so I suggest you to look at PEAK with has an implementation of multimethods/generic functions. Notice that Guido seems to be intentioned to add support for generic functions in future versions of Python, so that solution would likely have the blessing of the BDFL ;) The problem you have with your metaclass version, is the infamous metaclass conflict. It can be solved by hand or automatically (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197) but it is best to avoid it altogether. Just use PEAK or an hand made dispatcher, like for instance this one: class SimpleDispatcher(object): # this is on purpose not object oriented A dispatcher is a callable object that looks in a namespace for callable objects and calls them with the signature ``dispatcher(callablename, dispatchtag, *args, **kw)`` The namespace can be a module, a class, a dictionary, or anything that responds to ``getattr`` or (alternatively) to ``__getitem__``. Here is an example of usage: call = SimpleDispatcher(globals()) def manager_showpage(): ...return 'Manager' def member_showpage(): ... return 'Member' def anonymous_showpage(): ... return 'Anonymous' call('showpage', 'anonymous') 'Anonymous' call('showpage', 'manager') 'Manager' call('showpage', 'member') 'Member' def __init__(self, ns): self._ns = ns def __call__(self, funcname, classname, *args, **kw): try: func = getattr(self._ns, '%s_%s' % (classname, funcname)) except AttributeError: func = self._ns['%s_%s' % (classname, funcname)] return func(*args, **kw) if __name__ == __main__: import doctest; doctest.testmod() BTW, the usual advice holds here: if you can find an workable solution not involving metaclasses and decorators, don't use them. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: data entry tool
Peter wrote: This post seeks advice on whether python would be appropriate for a task, or whether you can suggest another approach. The project is to transcribe historical records such as schools admissions, ship passenger lists, birth/death/marriages, etc for genealogy studies. What we need is a simple software tool that will give the user a form set out like the page being transcribed, do some simple validation and put the data in a file (can be fixed field length plain text). Data files from volunteers will be compiled into a master database. This software tool needs to work on a variety of different computers; Win95, Win98, WinXP, Mac, Linux. So, would python be a good choice for this, and how should I go about it? I'm not a programmer and have only done a few little python scripts that run from the command line. Make it a webapp. That will guarantee to make it runnable on the list of OSses you gave. Use Django/TurboGears/ZOPE for the application itself- whichever suits you best. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Dispatching operations to user-defined methods
Michele Simionato writes: Apparently Guido fell in love with generic functions, so (possibly) in future Python versions you will be able to solve dispatching problems in in an industrial strenght way. Looks interesting, I'll keep an eye on that. Sometimes however the simplest possible way is enough, and you can use something like this : class SimpleDispatcher(object): (...) That doesn't make use of any subclass hierarchies the user defines though. But maybe it's just as well to scan his class for names once he has defined it, and build the dispatch table myself. -- Hallvard -- http://mail.python.org/mailman/listinfo/python-list
Modifying PyObject.ob_type
I've got some fixed-size types with identical object layout defind in C. The only differences are: Which methods they have, the name, and some are subtypes of others. Can I modify the ob_type of their instances, to switch between which of these types an object has? -- Hallvard -- http://mail.python.org/mailman/listinfo/python-list
How to get a part of string which follows a particular pattern using shell script
Hi all, I need to get a part of string which follows a pattern 'addr=' For example: a)test=192.168.1.17:/home/ankur/nios_fson/mnt/tmptype nfs(rw,addr=192.168.1.17) b)test=/dev/root on / typr nfs (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93) I need to get the ipaddress from the above two strings a and b which follows 'addr='. I tried to use cut, but it accepts only single charter as delimiter. If I give delimiter as 'addr=' for cut command it gives me a error. So please help me. A bunch of thanks in advance. Regards, P.R.Hariram -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
thanks for the detailed explaination... i know about basic lists slicing..just havn't seen one with steps yet.. thanks again...clp rocks. -- http://mail.python.org/mailman/listinfo/python-list
yahoo sender name
You can go to Options menu, then klikMail menu. Under Management tab, klik Mail Adresses Then edit your account there.. regards, faino ---hey...I know this is off the "python" topicbut I have yahoo mail and would like to change my "sender name" I have gone to the "edit account" area and have changed all names that can be edited to a consistent name other than the current sender name...but for some reason it will not change the sender name...is anybody familiar with yahoo mail and changing names? -thanks in advance- How low will we go? Check out Yahoo! Messengers low PC-to-Phone call rates.-- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi Mirco, Thank you! More similar than Perl ;-) And what's 'integrated' mean (must include some library)? I like C++ file I/O, is it 'low' or 'high'? Regards, Davy -- http://mail.python.org/mailman/listinfo/python-list
List of lists of lists of lists...
I would like to have a list of lists N times deep, and my solution is (in pseudocode): def deep(x): a=[x] return a mylist=[] for N: mylist=deep(mylist) Is there a more elegant way to do it? The maine idea is: from a list having the numbre of steps along N dimensions, generate a list with an item at each possible point. Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] -- Ángel Gutiérrez Rodríguez - [EMAIL PROTECTED] Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Química Física y Analítica Universidad de Oviedo - c/Julián Clavería 8 33006 - Oviedo Asturias - Spain E-mail: [EMAIL PROTECTED] Telf.: +34-985103687 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
By the way, is there any tutorial talk about how to use the Python Shell (IDE). I wish it simple like VC++ :) Regards, Davy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a part of string which follows a particular pattern using shell script
Hari wrote: Hi all, I need to get a part of string which follows a pattern 'addr=' For example: a)test=192.168.1.17:/home/ankur/nios_fson/mnt/tmptype nfs(rw,addr=192.168.1.17) b)test=/dev/root on / typr nfs (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93) I need to get the ipaddress from the above two strings a and b which follows 'addr='. I tried to use cut, but it accepts only single charter as delimiter. If I give delimiter as 'addr=' for cut command it gives me a error. Regular Expressions are probably the easiest way to do this. Example: import re str = a)test=192.168.1.17:/home/ankur/nios_fson/mnt/tmptype nfs(rw,addr=192.168.1.17) b)test=/dev/root on / typr nfs (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93) m = re.search(addr=(\d+\.\d+\.\d+\.\d+), str) print m.group(1) - Prints: 192.168.1.17 Read the Python manual on Regular Expressions (module re) or google for Python regular expression tutorials if your search is more complex than this (or if you want to know what's going on). If you want a good in-depth text on the subject, I'd recommend J. Friedls Mastering Regular Expressions. Have fun. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] PyYAML-3.01: YAML parser and emitter for Python
PyYAML: YAML parser and emitter for Python == I am pleased to announce the initial release of PyYAML. YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. You may download PyYAML from http://pyyaml.org/wiki/PyYAML. Example === import yaml yaml.load( ... name: PyYAML ... version: 3.01 ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... ) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'version': 3.01, 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} print yaml.dump(_) homepage: http://pyyaml.org/wiki/PyYAML version: 3.01 name: PyYAML keywords: [YAML, serialization, configuration, persistance, pickle] description: YAML parser and emitter for Python Links = PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.01.win32.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core Changes === * Initial release. The version number reflects the codename of the project (PyYAML 3000) and differenciates it from the abandoned PyYaml module. Copyright = The PyYAML module is written by Kirill Simonov [EMAIL PROTECTED]. PyYAML is released under the MIT license. -- xi -- http://mail.python.org/mailman/listinfo/python-list
Web framework comparison video
http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/ Thought this might be interesting to y'all. (I can't watch it 'cos I'm at work, so any comments about it would be appreciated :) Iain -- http://mail.python.org/mailman/listinfo/python-list
get Windows file type
Using Python on Windows XP, I am able to get almost all file and path info using os.path or stat, but I don't see a way to retrieve the file type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what is listed in the Type column in the Windows Explorer box. Thanks, rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Eggs Just install in *ONE* place? Easy to uninstall?
But not matter where eggs are installed they are never spread across multiple places on hard drive right? An egg is all under one node of tree right? From what I've seen, no. For example installing TurboGears will also install the tg-admin script in /usr/bin/ and there are a lot of other projects that install custom scripts. -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: get Windows file type
BartlebyScrivener enlightened us with: Using Python on Windows XP, I am able to get almost all file and path info using os.path or stat, but I don't see a way to retrieve the file type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what is listed in the Type column in the Windows Explorer box. I'm afraid you'll have to get that from the registry. That will only give you the descriptive name of the extension, though, and not the type of contents of the file, i.e. if you have a HTML file named 'somefile.avi', Windows recognises it as an AVI and not an HTML file. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Logging vs printing
alisonken1 [EMAIL PROTECTED] writes: Leo Breebaart wrote: I am writing fairly large console scripts in Python. They have quite a few command-line options, which lead to configuration variables that are needed all over the program (e.g. the --verbose option alone is used by just about every function and method). SNIP One question I have is about the --verbose option. If you're doing something that is equivalent to logging to file | console, rather than continuing to pass the '--verbose' flag around, why not just use the built-in logging facility to manage the extra output? Good point. It's not a real conscious decision, and I have one or two other projects lying around where I do in fact use logging. I think the main reason why I am not using it by default is because, when all is said and done, it still comes easier to me to resort to guarded print statements then to set up and use the logging machinery. This may well be a false economy in the long run, but it is nevertheless how I perceive it in day-to-day programming. (Related to this is that while I found e.g. the optparse documentation very clear and relevant to my needs, the logging documentation and examples, while readable, just never seem to relate to what I actually need. This is not a complaint -- just a subjective observation.) But you are right. Especially for the larger projects I really should bite the bullet and start using the logging module. -- Leo Breebaart [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging vs printing
Leo Breebaart enlightened us with: I think the main reason why I am not using it by default is because, when all is said and done, it still comes easier to me to resort to guarded print statements then to set up and use the logging machinery. The logging machinery isn't that huge nor is it difficult to set up: == import logging logging.basicConfig() log = logging.getLogger('your.module.name') == and that's all there is to it. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
Adam Jones wrote: Ken Tilton wrote: Alexander Schmolck wrote: [trimmed groups] Ken Tilton [EMAIL PROTECTED] writes: yes, but do not feel bad, everyone gets confused by the /analogy/ to spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief period I swore off the analogy because it was so invariably misunderstood. Even Graham misunderstood it. Count me in. g But looking at what it says: Think of the slots as cells in a spreadsheet (get it?), and you've got the right idea. , if you follow the analogy (and know that slot means data member in other OO models) you also know that Serge's Spreadsheet example would have scored a big fat zero on the Miller Analogy Test. Serge in no way made slots in Python classes behave like cells in a spreadsheet. He simply started work on a Spreadsheet application, using Python classes along the way. Bzzt. While everyone makes the mistake, it is only because few of us (me included) read very carefully. Especially if they are more interested in flaming than learning what someone is saying. I don't really mean any disrespect here, but if an analogy is not interpreted correctly by a large group of people, the analogy is crap, not the people. No, I do not think that follows. I reiterate: people (inluding me!) read too quickly, and this analogy has a trap in it: spreadsheets are /also/ software. The analogy is fine and the people are fine, but as you suggest there is a human engineering problem to be acknowledged. btw, I have a couple of links to papers on similar art and they all use the spreadshett metaphor. It is too good not to, but... Yes, I understood it, specifically because I have spent enough time dinking around with cell functions in a spreadhseet to understand what you meant. Maybe it would help to change the wording to functions with cell references in a spreadsheet instead of cells in a spreadsheet. g We could do a study. I doubt your change would work, but, hey, that is what studies are for. I think probably the best thing to do with the human engineering problem is attack the misunderstanding explicitly. Now if you are like most people, you think that means X. It does not. And then give an example, and then again say what it is not. Anyone who comes away from /that/ with the wrong idea just is not trying. But I would not put that in the project synopsis, and that is all the original confused poster read. Just not trying. kenny -- Cells: http://common-lisp.net/project/cells/ Have you ever been in a relationship? Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi Davy More similar than Perl ;-) But C has { }'s everywhere, so has Perl ;-) And what's 'integrated' mean (must include some library)? Yes. In Python, regular expressions are just another function library - you use them like in Java or C. In Perl, it's part of the core language, you use the awk-style (eg: /.../) regular expressions everywhere you want. If you used regexp in C/C++ before, you can use them in almost the same way in Python - which may give you an easy start. BTW. Python has some fine extensions to the perl(5)-Regexes, e.g. 'named backreferences'. But you won't see much regular expressions in Python code posted to this group, maybe because it looks clunky - which is unpythonic ;-) Lets see - a really simple find/match would look like this in Python: import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): print t which prints the text 't' because of the positive pattern match. In Perl, you write: use Acme::Pythonic; $t = 'blue socks and red shoes' if ($t =~ /(blue|white|red)/): print $t which is one line shorter (no need to compile the regular expression in advance). I like C++ file I/O, is it 'low' or 'high'? C++ has afaik actually three levels of I/O: (1) - (from C, very low) operating system level, included by io.h which provides direct access to operating system services (read(), write(), lseek() etc.) (2) - C-Standard-Library buffered IO, included by stdio.h, provides structured 'mid-level' access like (block-) fread()/ fwrite(), line read (fgets()) and formatted I/O (fprintf()/ fscanf()) (3) - C++/streams library (high level, fstream, iostream, sstream), which abstracts out the i/o devices, provides the same set of functionality for any abstract input or output. Perl provides all three levels of I/O, the 'abstracting' is introduced by modules which tie 'handle variables' to anything that may receive or send data. Python also does a good job on all three levels, but provides the (low level) operating system I/O by external modules (afaik). I didn't do much I/O in Python, so I can't say much here. Regards Mirco -- http://mail.python.org/mailman/listinfo/python-list
A better way to split up a list
The code below works fine, but it is less than nice to look at and somewhat long winded. Is there a better way to do the docstring task? This is the first working version, and can proabably be compacted a bit (list comprehensions etc) but I am looking for a better basic approach. Any help much appreciated :) from itertools import islice def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen 3: parlen = 3 stoplist=[0];exit = 0 while exit len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist movelist = [1,2,3,4,5,6,7,8,9,10,11] print chopupmoves(movelist) -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing Plug-in Systems in Python
mystilleef wrote: Are there any good tutorials on how to design good plug-in systems with Python, or any language? What are the best practices for designing plug-in systems in Python? How would you go about designing one? What are common pitfalls in designing one? Any pointers, suggestions, resources and advice is welcome. I am liking to use setuptools and its entry points. With this, your program can check for a specific thing and load all modules that provides something like myapp.plugins. Take a look at it. -- Jorge Godoy [EMAIL PROTECTED] Quidquid latine dictum sit, altum sonatur. - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging vs printing
Sybren Stuvel [EMAIL PROTECTED] writes: Leo Breebaart enlightened us with: I think the main reason why I am not using [logging] by default is because, when all is said and done, it still comes easier to me to resort to guarded print statements then to set up and use the logging machinery. The logging machinery isn't that huge nor is it difficult to set up: == import logging logging.basicConfig() log = logging.getLogger('your.module.name') == and that's all there is to it. I did say: it comes easier *to me* -- I am aware that my own tastes, which may not be shared by others, or be entirely logical, feature into this. Having said that, I do think it's also not *quite* as trivial as you claim. In order to duplicate what I already have (if config.verbose: print msg), I probably need to log at the DEBUG level, and I need to change the format so that that output looks like the 'print' output (no timestamping cruft etc.) Okay, you say, that's still easy. It's just: logging.basicConfig(level=logging.DEBUG, format='%(message)s') logging.debug('A debug message') And that's true, but I did have to go and look this up, and I made a couple of false starts first. I can only repeat that the workings of the logging framework are rarely intuitive to me. Also, assume that I have set it up as above. Now I want certain other print statements to go to sys.stderr alone. If I understand the docs correctly (possibly I don't), the way to do this is to start attaching explicit StreamHandlers and whatnot. Whereas with print, I can say print sys.stderr, msg. I know that it won't take much for a script to become so complex that the extra stuff logging buys you vastly overpowers the convenience of the print statements. I have just not needed that often enough for it to become second nature to use in smaller scripts as well. -- Leo Breebaart [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
On 8/05/2006 10:31 PM, Mirco Wahab wrote: [snip] Lets see - a really simple find/match would look like this in Python: import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): What do you expect when t == green socks and red shoes? Is it possible that you mean to use search() rather than match()? print t which prints the text 't' because of the positive pattern match. In Perl, you write: use Acme::Pythonic; $t = 'blue socks and red shoes' if ($t =~ /(blue|white|red)/): print $t which is one line shorter (no need to compile the regular expression in advance). There is no need to compile the regex in advance in Python, either. Please consider the module-level function search() ... if re.search(rblue|white|red, t): # also, no need for () in the regex. -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
On Sun, 07 May 2006 10:36:00 -0400, Ken Tilton [EMAIL PROTECTED] wrote: [...] Your spreadsheet does not have slots ruled by functions, it has one slot for a dictionary where you store names and values/formulas. Go back to your example and arrange it so a and b are actual slots (data members? fields?) of the spreadsheet class. You can just stuff numbers in a: sheet1.a = 42 but b should be somehow associated with a rule when sheet1 is created. As I said in the other post, also associate an on-change callback with slots a and b. I must be missing something - seems this should be easy using __setattr__ and __getattr__. Then _literally_ there's just a dict containing names and functions, but when you _use_ the class it looks just like the above: [...] When that is done we can look at a working example and see how well Python fared without macros and full-blown lambda. No lambda in the non-programmer-half-hour implementation below. You need to define a named function for each cell to use as a callback. Except for that what are Cells supposed to do that the implementation below doesn't do? PyCells.py class Cell: def __init__(self, name, owner, callback): self.name = name self.callback = callback self.owner = owner def onchange(self, value): self.value = value self.callback(self, value) class Cells: def __init__(self): #self.slots = {} #Oops, don't work so well with __setattr__: self.__dict__['slots'] = {} def __setattr__(self, name, value): self.slots[name].onchange(value) def __getattr__(self, name): return self.slots[name].value def AddCell(self, name, callback): self.slots[name] = Cell(name, self, callback) *** Sample use: cells = Cells() def acall(cell, value): cell.owner.slots['b'].value = value + 1 cells.AddCell('a',acall) def bcall(cell, value): cell.owner.slots['a'].value = value - 1 cells.AddCell('b',bcall) cells.a = 42 print cells.a, cells.b cells.b = 24 print cells.a, cells.b David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Mirco Wahab wrote: Lets see - a really simple find/match would look like this in Python: import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): print t which prints the text 't' because of the positive pattern match. In Perl, you write: use Acme::Pythonic; $t = 'blue socks and red shoes' if ($t =~ /(blue|white|red)/): print $t which is one line shorter (no need to compile the regular expression in advance). There is no need to compile the regular expression in advance in Python either: t = 'blue socks and red shoes' if re.match('(blue|white|red)', t): print t The only advantage to compiling in advance is a small speed up, and most of the time that won't be significant. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this with python ?
Tim N. van der Leeuw wrote: Your question is insufficiently clear for me to answer. Do you want to know how to read from standard-input in a Python program? Do you want to know how to start an external program from Python, and then connect something to that programs standard input? Do you want to know something else? Please specify! Cheers, --Tim Thanks. For example, I can call vim and do something like this in a shell script, #!/bin/sh vim a.file-EOF :some_vim_command :some_vim_command :w :q EOF I want to know how to call vim and to the same thing with python. Regrads, -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CHM Doc Contains Broken Links on Linux in xCHM.
Thank you Razvan. You're right. I downloaded the 1.7.1 source and built it and the links do work just fine. Thank you for pointing that out! -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to split up a list
The code below works fine, but it is less than nice to look at and somewhat long winded. Is there a better way to do the docstring task? This is the first working version, and can proabably be compacted a bit (list comprehensions etc) but I am looking for a better basic approach. Any help much appreciated :) It looks like there may be some problems with your code, such that it doesn't work fine...particularly in lists with 1, 2, or 3 elements. The below chopupmoves2 function does what you describe, and is nice and short. A bunch of test-cases get generated and compared so you can see their output. The chopupmoves2() function regularly returns your described results, while things seem a bit off with the chopupmoves() HTH, -tkc from itertools import islice def chopupmoves2(movelist): size = len(movelist) / 3 return [ movelist[:size], movelist[size:size*2], movelist[size*2:]] def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen 3: parlen = 3 stoplist=[0];exit = 0 while exit len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist # test them with a bunch of test-cases movelist =[] for i in xrange(1,12): movelist.append(i) print Movelist:, movelist print \toriginal:, chopupmoves(movelist) print \tTim's: , chopupmoves2(movelist) -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging vs printing
Leo Breebaart enlightened us with: Okay, you say, that's still easy. It's just: logging.basicConfig(level=logging.DEBUG, format='%(message)s') I always use a separate logger, as per my example. That would then just require an additional line: log.setLeveL(logging.DEBUG) And that's true, but I did have to go and look this up, and I made a couple of false starts first. I can only repeat that the workings of the logging framework are rarely intuitive to me. If you're just writing software for yourself, that's fine. If you want to share your software, things that are intuitive to you might not be to others. In such a case (and usually software is going to be shared at some point or another) it's generally a good idea to spend a few minutes learning how to use such a system, because then other people will see your code using things they are already familiar with. Reusing other people's code instead of writing your own logging, also means that other people will fix bugs for you. I know that it won't take much for a script to become so complex that the extra stuff logging buys you vastly overpowers the convenience of the print statements. I have just not needed that often enough for it to become second nature to use in smaller scripts as well. I don't use the logging module in small scripts either, but as soon as it gets over 100 lines, I do. It's quite easy to get it going, once you get the hang of it. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi John import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): What do you expect when t == green socks and red shoes? Is it possible that you mean to use search() rather than match()? This is interesting. What's in this example the difference then between: import re t = 'blue socks and red shoes' if re.compile('blue|white|red').match(t): print t and t = 'blue socks and red shoes' if re.search('blue|white|red', t): print t There is no need to compile the regex in advance in Python, either. Please consider the module-level function search() ... if re.search(rblue|white|red, t): # also, no need for () in the regex. Thats true. Thank you for pointing this out. But what would be an appropriate use of search() vs. match()? When to use what? I answered the posting in the first place because also I'm coming from a C/C++/Perl background and trying to get along in Python. Thanks, Mirco -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework comparison video
Iain King enlightened us with: http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/ Thought this might be interesting to y'all. (I can't watch it 'cos I'm at work, so any comments about it would be appreciated :) It's a nice video, I really enjoyed it. Even though the website you linked says it's a 60 minute vid, it's only just over 30 minutes. So far, I've created my own web framework - mostly because I didn't see a simple to use framework that could do what I wanted it to do: properly handle client-side caching. Looking at the Plone website, it looks like they do support that. Perhaps I'll look into Plone for my site in the future ;-) For now, I'm very happy with my own framework (http://www.unrealtower.org/engine) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to split up a list
On 8/05/2006 10:45 PM, [EMAIL PROTECTED] wrote: The code below works fine, but it is less than nice to look at and somewhat long winded. Is there a better way to do the docstring task? This is the first working version, and can proabably be compacted a bit (list comprehensions etc) but I am looking for a better basic approach. Any help much appreciated :) from itertools import islice def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen 3: parlen = 3 What's this for? It causes weird things to happen with short lists. stoplist=[0];exit = 0 while exit len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist movelist = [1,2,3,4,5,6,7,8,9,10,11] print chopupmoves(movelist) Unless I've totally misunderstood your spec, you don't need all that islice and stoplist stuff. def chopupmoves2(movelist): parlen = len(movelist) // 3 return [movelist[:parlen], movelist[parlen:parlen*2], movelist[parlen*2:]] for k in range(13): mlist = range(k) print print v1, chopupmoves(mlist) print v2, chopupmoves2(mlist) -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a column from a file
Check out the csv module. -Larry Bates Gary Wessle wrote: Hi I have a file with data like location pressure temp str flootfloot I need to read pressure and temp in 2 different variables so that I can plot them as lines. is there a package which reads from file with a given formate and returns desired variables? or I need to open, while not EOF read, parse, build list, return? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi Duncan There is no need to compile the regular expression in advance in Python either: ... The only advantage to compiling in advance is a small speed up, and most of the time that won't be significant. I read 'some' introductions into Python Regexes and got confused in the first place when to use what and why. After some minutes in this NG I start to get the picture. So I narrowed the above regex-question down to a nice equivalence between Perl and Python: Python: import re t = 'blue socks and red shoes' if re.match('blue|white|red', t): print t t = 'blue socks and red shoes' if re.search('blue|white|red', t): print t Perl: use Acme::Pythonic; $t = 'blue socks and red shoes' if $t =~ /blue|white|red/: print $t And Python Regexes eventually lost (for me) some of their (what I believed) 'clunky appearance' ;-) Thanks Mirco -- http://mail.python.org/mailman/listinfo/python-list
Re: which is better, string concatentation or substitution?
In article [EMAIL PROTECTED], John Salerno [EMAIL PROTECTED] wrote: My initial feeling is that concatenation might take longer than substitution, but that it is also easier to read: def p(self, paragraph): self.source += 'p' + paragraph + '/p\n\n' vs. def p(self, paragraph): self.source += 'p%s/p\n\n' % paragraph Is there a preference between these two ways? One may be marginally faster, but they both require copying the source string, and are thus both O(n). If you're just doing one or a small fixed number of these, it really doesn't matter. Pick whichever one you think is easier to read. On the other hand, if you're doing a lot of them (i.e. in a loop), the entire loop will now be O(n^2), which is a killer. If that's the case, what you want to do is accumulate the individual substrings in a list, then join the list elements all at once: parts = [] for paragraph in foo: parts.append ('p') parts.append (paragraph) parts.append ('p\n\n') # or maybe instead of that ... # parts += ['p', paragraph, 'p\n\n'] self.source = .join (parts) This only requires a single copy, and thus you're back to being O(n), which beats the heck out of O(n^2). -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework comparison video
Sybren Stuvel enlightened us with: Perhaps I'll look into Plone for my site in the future ;-) I take that back. The Plone webserver is hosted by XS4ALL, the best ISP in The Netherlands, which resides in Amsterdam. I happen to live in Amsterdam too, so you'd expect the site to be fast. Well, it took 5 to 15 seconds to get a page from their FAQ[1], which is just way too slow. As a comparison, the XS4ALL website[2] took only 0.4 seconds. I tested it using time lynx -dump $URL /dev/null. [1] http://plone.org/documentation/faq/products-for-plone [2] http://www.xs4all.nl/ For now, I'm very happy with my own framework (http://www.unrealtower.org/engine) Looks like I'll be happy a while longer! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled
Tim I did this under a debug build of Python Perhaps this is the reason why you were not able to reproduce the problem. Could you try again with a standard build of Python? I am a bit surprised that nobody else has tried running the short Python program above on a hyper-threading or dual core / dual processor system. Olaf -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
On 8/05/2006 11:13 PM, Mirco Wahab wrote: Hi John import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): What do you expect when t == green socks and red shoes? Is it possible that you mean to use search() rather than match()? This is interesting. What's in this example the difference then between: I suggest that you (a) read the description on the difference between search and match in the manual (b) try out search and match on both your original string and the one I proposed. import re t = 'blue socks and red shoes' if re.compile('blue|white|red').match(t): print t and t = 'blue socks and red shoes' if re.search('blue|white|red', t): print t [snip] But what would be an appropriate use of search() vs. match()? When to use what? ReadTheFantasticManual :-) -- http://mail.python.org/mailman/listinfo/python-list
PYTHONPATH vs PATH?
Hello: Someone on my team tried out installing my Python code and found that setting PYTHONPATH does not work, but setting PATH environment variable works the way PYTHONPATH should. Is that how it supposed to be, or is that a bug or feature? -Original Message- (parts deleted) Subject: question on Python for windows I ran into trouble getting our software to work with the debuggers based on the user guide (updated after the CDROM). PYTHONPATH=.;..;DIRECTORY-CONTAINING-scenarios.py Where DIRECTORY-CONTAINING-PYTHON-SCRIPTS.py is the directory containing the Python scripts . this actually is the PATH, not PYTHONPATH, and is correct if you installed the Python scripts to the Python scripts folder, and then start up from the Python scripts folder, which I would say is normally not going to be the case. I installed our software to C:\sp I installed Python to E:\Python24 (the default is the same folder on C drive, I just changed the drive letter) when I installed the additional 3 packages they knew where Python was already and all I did was pick the default choices. but, the trouble was that the PYTHONPATH using . and .. does not find the Python scripts folder if you are in C:\sp I used this to make it work (based on Python in E:\Python24 and in C:\sp) set PATH=%PATH%;E:\Python24;E:\Python24\Scripts now I start in my C:\sp folder (where the config.txt file is) and everything works fine I did try just setting PYTHONPATH but it is actually PATH that matters. If you don't include the Python base and Scripts folders in the PATH it does not work. I verified that not setting PYTHONPATH but just set PATH to include the Python base and scripts folders does work. Thanks in advance: -- http://mail.python.org/mailman/listinfo/python-list
Re: utility functions within a class?
[EMAIL PROTECTED] wrote: John Salerno wrote: What I originally meant was that they would not be called from an instance *outside* the class itself, i.e. they won't be used when writing another script, they are only used by the class itself. Yep, so you want to encapsulate the functionality that those methods provide, which is the whole point of building them in a class in the first place. And you want them to be private to the class so that they do not form part of the classes public/external interface. But it's right that they should still be regular instance methods? So from within the class I still call them as self._generate_head(), etc.? -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to split up a list
Argh, embarassment on my part due to incomplete spec. movelist is used to store a list of chess moves and splitting it up in this way is so it can be printed in a space that is 3 lines high but quite wide. Thus the way the list grows as it is appended to in chopupmoves is intended. -- http://mail.python.org/mailman/listinfo/python-list
Re: which is better, string concatentation or substitution?
Roy Smith wrote: One may be marginally faster, but they both require copying the source string, and are thus both O(n). Sorry, I'm not familiar with the O(n) notation. If you're just doing one or a small fixed number of these, it really doesn't matter. Pick whichever one you think is easier to read. Thanks guys. I have a handful of methods that each do this task once per call, so I suppose this counts as not a lot, at least not at one time. And it seems like a good point that the real problem could be constantly concatenating with self.source, rather than the smaller pieces being put together. -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to split up a list
[EMAIL PROTECTED] wrote: The code below works fine, but it is less than nice to look at and somewhat long winded. Is there a better way to do the docstring task? This is the first working version, and can proabably be compacted a bit (list comprehensions etc) but I am looking for a better basic approach. Any help much appreciated :) from itertools import islice def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen 3: parlen = 3 stoplist=[0];exit = 0 while exit len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist movelist = [1,2,3,4,5,6,7,8,9,10,11] print chopupmoves(movelist) Try something like this: def chopupmoves(movelist): return [movelist[0:3], movelist[3:6], movelist[6:]] -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: A better way to split up a list
[EMAIL PROTECTED] wrote: The code below works fine, but it is less than nice to look at and somewhat long winded. Is there a better way to do the docstring task? This is the first working version, and can proabably be compacted a bit (list comprehensions etc) but I am looking for a better basic approach. Any help much appreciated :) from itertools import islice def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen 3: parlen = 3 stoplist=[0];exit = 0 while exit len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist movelist = [1,2,3,4,5,6,7,8,9,10,11] print chopupmoves(movelist) Try something like this: def chopupmoves(movelist): return [movelist[0:3], movelist[3:6], movelist[6:]] -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH vs PATH?
Michael Yanowitz wrote: Someone on my team tried out installing my Python code and found that setting PYTHONPATH does not work, but setting PATH environment variable works the way PYTHONPATH should. Is that how it supposed to be PATH is used by the operating system to find executables, and PYTHONPATH is used by Python to find Python modules. why setting the PATH helped in your case is impossible to tell, without knowing exactly what your application does. /F -- http://mail.python.org/mailman/listinfo/python-list
Scaled Vector Graphics
I have been asked to write a routine to merge documents in pfd and svg formats into a single file (preferably pfd format). Currently we send the pdf image to the printer followed by the svg image (a scan of a health care claim) but this is not a satisfactory solution. We have as many as 3000 document pairs daily (another project in development will send all the information to out clients electronically via EDI X12 format). Does Python offer support for working with svg files? I've looked at the PIL and Reportlab packages and Googled around but have not found anything. My other option is to snag one of the routines I've found that claim to convert scg to pdf and then merge them as pdf files. Any help or suggestions you may supply will be greatly appreciated,Greg LindstromNovaSys HealthLittle Rock, Arkansas (USA) -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a column from a file
Check out the csv module. -Larry Bates Gary Wessle wrote: Hi I have a file with data like location pressure temp str flootfloot I need to read pressure and temp in 2 different variables so that I can plot them as lines. is there a package which reads from file with a given formate and returns desired variables? or I need to open, while not EOF read, parse, build list, return? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
On Mon, 08 May 2006 08:05:38 -0500, David C. Ullrich [EMAIL PROTECTED] wrote: [...] def acall(cell, value): cell.owner.slots['b'].value = value + 1 Needing to say that sort of thing every time you define a callback isn't very nice. New and improved version: PyCells.py class Cell: def __init__(self, name, owner, callback): self.name = name self.callback = callback self.owner = owner def onchange(self, value): self.value = value self.callback(self, value) def __setitem__(self, name, value): self.owner.slots[name].value = value class Cells: def __init__(self): self.__dict__['slots'] = {} def __setattr__(self, name, value): self.slots[name].onchange(value) def __getattr__(self, name): return self.slots[name].value def AddCell(self, name, callback): self.slots[name] = Cell(name, self, callback) Sample: cells = Cells() def acall(cell, value): cell['b'] = value + 1 cells.AddCell('a',acall) def bcall(cell, value): cell['a'] = value - 1 cells.AddCell('b',bcall) cells.a = 42 print cells.a, cells.b cells.b = 24 print cells.a, cells.b #OR you could give Cell a __setattr__ so the above #would be cell.a = value - 1. I think I like this #version better; in applications I have in mind I #might be iterating over lists of cell names. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's regular expression?
Hi John But what would be an appropriate use of search() vs. match()? When to use what? ReadTheFantasticManual :-) From the manual you mentioned, i don't get the point of 'match'. So why should you use an extra function entry match(), re.match('whatever', t): which is, according to the FM, equivalent to (a special case of?) re.search('^whatever', t): For me, it looks like match() should be used on simple string comparisons like a 'ramped up C-strcmp()'. Or isn't ist? Maybe I dont get it ;-) Thanks Mirco -- http://mail.python.org/mailman/listinfo/python-list
Re: which is better, string concatentation or substitution?
Duncan Booth wrote: If you build a list of lines to join then you don't have to repeat '\n' on the end of each component line. How would that work? Wouldn't the last line in the list still need the newlines? -- http://mail.python.org/mailman/listinfo/python-list
Re: utility functions within a class?
John Salerno wrote: [EMAIL PROTECTED] wrote: John Salerno wrote: What I originally meant was that they would not be called from an instance *outside* the class itself, i.e. they won't be used when writing another script, they are only used by the class itself. Yep, so you want to encapsulate the functionality that those methods provide, which is the whole point of building them in a class in the first place. And you want them to be private to the class so that they do not form part of the classes public/external interface. But it's right that they should still be regular instance methods? So from within the class I still call them as self._generate_head(), etc.? I tried the underscore method, but I was still able to call it as a regular instance method in the interpreter. Is that what's supposed to happen? -- http://mail.python.org/mailman/listinfo/python-list
Re: Scaled Vector Graphics
On Monday 08 May 2006 2:58 pm, Greg Lindstrom wrote: I have been asked to write a routine to merge documents in pfd and svg formats into a single file (preferably pfd format). Currently we send the pdf image to the printer followed by the svg image (a scan of a health care claim) but this is not a satisfactory solution. We have as many as 3000 document pairs daily (another project in development will send all the information to out clients electronically via EDI X12 format). Does Python offer support for working with svg files? I've looked at the PIL and Reportlab packages and Googled around but have not found anything. My other option is to snag one of the routines I've found that claim to convert scg to pdf and then merge them as pdf files. Any help or suggestions you may supply will be greatly appreciated, PyQt4 supports the rendering of SVG images onto PDF via the QSvgRenderer and QPrinter classes. Phil -- http://mail.python.org/mailman/listinfo/python-list
hyperthreading locks up sleeping threads
Below are 2 files. The first is a Python program that isolates the problem within less than 1 hour (often just a few minutes). The second is a C++ program that shows that the Win32 Sleep() function works as expected (ran from Friday afternoon until Monday morning). Note, the Python programs hangs (stops responding) with hyper-threading turned on (a BIOS setting), but works as expected with hyper-threading turned off. This problem happens on Windows only (not on Linux for days). Variations of the Python program also lock up: Tried importing win32api instead of time and using the win32api.GetTickCount() and win32api.Sleep() methods. Tried using lock = threading.Event() and lock.wait() instead of time.sleep(). Tried import Queue using q = Queue.Queue() and q.get(True, self.t). Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional. winmsd.exe shows: 2CPUs: x86 Family 15 Model 4 Stepping 1 GenuineIntel ~3000 MHz Version: 5.1.2600 Service Pack 2 Build 2600 Could someone with a hyper-threading (or dual core or multi processor) CPU please confirm this bug? Many Thanks Olaf Here is the expected output of both programs (the progam has locked up if the numbers stop printing): python testsleep.py thread 1 started, sleep time 0.010 thread 2 started, sleep time 0.003 1 1 1 2 1 1 1 2 1 1 1 2 1 1 1 1 2 1 1 1 # testsleep.py import threading import time class Task(threading.Thread): def __init__(self, n, t): threading.Thread.__init__(self) self.n = n # thread id self.t = t # sleep time def run(self): print 'thread %d started, sleep time %.3f' % (self.n, self.t) count = 0 printCount = int(10 / self.t) while True: start = time.clock() time.sleep(self.t) stop = time.clock() if stop - start 1.0: print 'thread', self.n, stop - start count += 1 if count printCount: count = 0 print self.n, # print sign of live def test(): thread1 = Task(1, 0.01) # thread 1, sleep 10 ms thread2 = Task(2, 0.003) # thread 2, sleep 3 ms thread1.start() thread2.start() test() -- // testsleep.cpp // Compiled with Visual C++ version 6 as a Win32 console application. #include windows.h #include stdio.h #include time.h typedef struct { int id; int ms; } param_s; DWORD WINAPI threadFunction(LPVOID param) { param_s* p = (param_s*)param; long elapsedTime; long time1, time2; long printCount = long(1 / p-ms); // loop iterations in 10 seconds long count = 0; printf(thread %d started, sleep time: %d ms \n, p-id, p-ms); while(true) { time1 = GetTickCount(); Sleep(p-ms); time2 = GetTickCount(); elapsedTime = time2 - time1; if(elapsedTime 1000) printf(thread %d slept for %d ms \n, p-id, elapsedTime); count++; if(count printCount) { count = 0; printf(%d , p-id); // print sign of live } } return 0; } int main(int argc, char* argv[]) { long time1, time2; param_s p1, p2; p1.id = 1; p1.ms = 10; p2.id = 2; p2.ms = 3; time1 = GetTickCount(); while(true) { time2 = GetTickCount(); if (time1 != time2) { printf(clock resolution: %d ms \n, time2 - time1); break; } } CreateThread(NULL, 0, threadFunction, (void*)p1, 0, NULL); CreateThread(NULL, 0, threadFunction, (void*)p2, 0, NULL); getchar(); // wait until the user presses the enter key. return 0; } -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this with python ?
Xiao Jianfeng wrote: Tim N. van der Leeuw wrote: Your question is insufficiently clear for me to answer. Do you want to know how to read from standard-input in a Python program? Do you want to know how to start an external program from Python, and then connect something to that programs standard input? Do you want to know something else? Please specify! Cheers, --Tim Thanks. For example, I can call vim and do something like this in a shell script, #!/bin/sh vim a.file-EOF :some_vim_command :some_vim_command :w :q EOF I want to know how to call vim and to the same thing with python. Regrads, hi, os.popen should do that. Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH vs PATH?
Fredrik Lundh: PATH is used by the operating system to find executables, and PYTHONPATH is used by Python to find Python modules. Yes, but Python also finds modules in its own installation. So changing PATH may cause another installation of Python to be run, which may have some other set of installed modules. When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. http://docs.python.org/tut/node8.html -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Retrieving event descriptors in Tkinter
Does Tkinter provide a function that returns all the event descriptors for a given widget class? I am looking for something similar to what you get in Perl/Tk when you call bind() with a single explicit argument. For example, in Perl/Tk, $widget-bind( Tk::Button ) returns a list like Key-Return Key-space ButtonRelease-1 Is it possible to do the same in Tkinter? I have looked through Fredrik Lundh's on-line reference and also the one by John Shipman. I am unable to locate the function I need. Perhaps I have not looked hard enough. Any help would be much appreciated. Thanks. Avi Kak [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list