Announce: Linux Desktop Testing Project (LDTP) 1.5.1 released
Greetings all, We are proud to announce the release of LDTP 1.5.1. This release features number of important breakthroughs in LDTP as well as in the field of Test Automation. This release note covers a brief introduction on LDTP followed by the list of new features and major bug fixes which makes this new version of LDTP the best of the breed. Useful references have been included at the end of this article for those who wish to hack / use LDTP. About LDTP: Linux Desktop Testing Project is aimed at producing high quality test automation framework (C / Python) and cutting-edge tools that can be used to test Linux Desktop and improve it. It uses the Accessibility libraries to poke through the application's user interface. The framework also has tools to record test-cases based on user events in the interface of the application which is under testing. We strive to help in building a quality desktop. Whats new in this release: Bug fixes: * Fixes b.g.o # 574787, 574789, 574791, 574793 Bug 574791 – ldtputils.captureimage() ignores coordinate arguments Bug 574793 – Use wnck to get window id instead of LTFX (digwin) Bug 574787 – LDTP package is not installing correctly Bug 574789 – getwindowlist (and others?) don't handle utf8 well Special thanks to Ara Pulido ara at ubuntu.com, Eitan Isaacson ei...@ascender.com and Michael Terry michael.te...@canonical.com Download source tarball - http://download.freedesktop.org/ldtp/1.x/1.5.x/ldtp-1.5.1.tar.gz Binary (openSUSE / Ubuntu / Fedora / Debian / RHEL / CentOS / Mandriva) - http://download.opensuse.org/repositories/home:/anagappan/ (Just scheduled in openSUSE build service, might take time to complete depending upon server load) References: For detailed information on LDTP framework and latest updates visit http://ldtp.freedesktop.org For information on various APIs in LDTP including those added for this release can be got from http://ldtp.freedesktop.org/user-doc/index.html To subscribe to LDTP mailing lists, visit http://ldtp.freedesktop.org/wiki/Mailing_20list IRC Channel - #ldtp on irc.freenode.net Thanks Nagappan -- Linux Desktop (GUI Application) Testing Project - http://ldtp.freedesktop.org http://nagappanal.blogspot.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python-URL! - weekly Python news and links (Mar 11)
QOTW: [Perhaps] it sounds [as though] I'm saying that most prospective users of OSS [open-source software] can't even manage to download it. Let me be clear: that is exactly what I am saying. - Patrick McKenzie http://www.kalzumeus.com/2009/03/07/how-to-successfully-compete-with-open-source-software/ New itertool candidate: like groupby but edge-triggered (or event-triggered): http://groups.google.com/group/comp.lang.python/t/d364e7b16bf151c7/ Is python worth learning as a second language? http://groups.google.com/group/comp.lang.python/t/c444c1229aed90c1/ Other language used to have significant indentation, but is now considering alternatives to allow multiline expressions (like a multiline lambda in Python): http://groups.google.com/group/comp.lang.python/t/52dcdb09b4d73915/ Enumerating all modules imported by a script: http://groups.google.com/group/comp.lang.python/t/86759676867f18e8/ Several attempts to improve a code fragment involving lists, repeated elements, and sorting: http://groups.google.com/group/comp.lang.python/t/453f1c803b8a78e2/ Why are some strings automatically interned, and not other? http://groups.google.com/group/comp.lang.python/t/e4daccae7e77fb0e/ Is it legal to modify an exception before re-raising it? http://groups.google.com/group/comp.lang.python/t/f7a647405fd48f5b/ PHP has == and ===, but they do NOT behave the same as Python's == and is operators http://groups.google.com/group/comp.lang.python/t/a697da8a6885d87f/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish the efforts of Python enthusiats: http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the Planet sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all The old Python To-Do List now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470group_id=5470func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us
Python training for cheminformatics, Leipzig, 27-29 April
My next training course on Python for cheminformatics will be in Leipzig, Germany on 27-29 April. For full details see http://dalkescientific.com/training/ The schedule for the three day course is Day 1: overview of Python and OEChem, Day 2: plotting with matplotlib, communicating with Excel, XML processing, calling command-line programs, numeric computing with NumPy and R. Day 3: SQL databases and web development with Django. The course is designed for working computational chemists who know how to do some programming and want more training in how to use Python effectively for their research. The examples and hands-on exercises are all drawn from cheminformatics. If you have any questions or to register, please contact me. Andrew da...@dalkescientific.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] Pyjamas 0.5 Web Widget Set and python-to-javascript Compiler released
This is the release of Pyjamas 0.5, a python-to-javascript compiler with an AJAX Web Widget set, for creating python desktop-like applications that run in all major web browsers. http://pyjs.org Pyjamas is NOT another AJAX framework where the widgets are predefined, fixed and inflexible. Thanks to the compiler, Pyjamas is a dynamic framework's framework where developers can define their own web framework, in Python classes and modules instead of being forced to write code in pure Javascript. The Pyjamas Web Widget set makes it possible for users to develop Rich Media Applications as if they were writing desktop applications, without having to know any Javascript, or even very much HTML. Developing applications using Pyjamas is much more similar to and has far more in common with developing PyQT4 or PyGtk2 applications than it has with traditional AJAX web development. Yet, thanks to the applications actually running in a Web Browser, developers get the best of both worlds. For those people who prefer to stick to true Desktop development, or who prefer to debug applications in Python rather than rely on the debugging features of Web Browser engines, there is the sister project, Pyjamas-Desktop - http://pyjd.org Pyjamas-Desktop allows the same application source code to be run, unmodified, in both the web browser and as a desktop application. The 0.5 release is a significant functionality update. Additions have been made to the core python-to-javascript compiler such as support for exceptions (try / except), lambda, and a debug option to track and print run-time stack traces, in cases where the deployment of a javascript script debugger is difficult or impossible (IE6 running under Wine). Also, the code-generator has undergone a reorganisation, and now has much better support for local and global variable, function, class and module scopes. Support for Dynamic loading of modules has been added, where each python module now has its own javascript (compiled) cache file. This makes it possible to share the modules across the 5 supported platforms, bringing a dramatic reduction in the amount of compiled javascript that is deployed. Also, support for dynamic module loading makes it much clearer how developers may interact with pyjamas-compiled modules from existing applications which already have an AJAX framework in place. Users of previous versions of Pyjamas should note that the UI widget classes have undergone a restructuring, reducing the 4,000 line ui.py into 70 separate small modules. The reorganisation allows applications to undergo a significant reduction in the amount of compiled javascript, by only importing UI Modules that are needed. Reorganisation scripts can be found in contrib/pyjamas_0.4_0.5_upgrade/ that will help in the conversion of existing applications. Also, to make developers' lives easier in both the testing and deployment of pyjamas applications, buildout has been added, along with a standard setup.py. Finally, an experiment is included, which is the beginnings of a way to speed up the execution of standard python, in a similar way to Python-Psyco. The combination of the pyjs python-to-javascript compiler and PyV8 - http://code.google.com/p/pyv8 - becomes a JIT compiler that supports both ARM and i386 assembler. The use of the Google V8 JIT compiler provides a means to dynamically load standard c-based python modules, and the use of pyjs means that the intermediate javascript is actually still human-readable. These are two distinct advantage over pypy, and the third advantage is that the direct translation, instead of going through an intermediary (RPython) means that the full dynamic semantics of the python language are reflected into javascript, and still available. Downloads are available at: http://code.google.com/p/pyjamas/downloads/list https://sourceforge.net/project/platformdownload.php?group_id=239074 http://pypi.python.org/pypi/Pyjamas/0.5 Pyjamas Book is at: http://pyjs.org/book/output/Bookreader.html#Getting%20Started Links to other documentation is on the main site: http://pyjs.org Development and discussion is at: http://groups.google.com/group/pyjamas-dev Subversion Source repository is at: https://sourceforge.net/scm/?type=svngroup_id=239074 IRC Channel is: #pyjamas at irc.freenode.net IRC Logs (thanks to Tim Riker) at: http://ibot.rikers.org/%23pyjamas -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Regular Toronto Python User's Group on Tuesday the 17th
Topic: OpenGL 3.1: A whole new OpenGL (Mike Fletcher) Further: A preview of the PyCon 2009 presentation on OpenGL 3.1: A whole new OpenGL. We'll be looking at what the legacy-free OpenGL programming model looks like, and how you access it via PyOpenGL. The upcoming OpenGL 3.1 represents the first major backwards incompatible release of OpenGL, and pretty much everything you've read about OpenGL is out the window. The result is a system that is very close to the metal of the modern GPU, a set of two (three in newer cards) programmable engines with generic mechanisms for feeding data in and reading it out. Next month Myles Braithwaite will be presenting Google's AppEngine, so be sure to mark the 21st of April on your calendars. As usual, we'll meet at Linux Caffe, at the corner of Grace and Harbord, one block South of Christie station at 7:00, with the meeting starting at 7:15pm. More details on the NextMeeting page on the web-site: http://www.pygta.org Enjoy yourselves, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Why is lambda allowed as a key in a dict?
Terry Reedy wrote: r wrote: On Mar 11, 3:40 pm, Craig Allen callen...@gmail.com wrote: On Mar 10, 1:39 pm, Paul Rubin http://phr...@nospam.invalid wrote: Identical strings don't necessarily have the same id: A more verbose way to put this is Requesting a string with a value that is the same an an existing string does not necessarily result in reuse of the existing string but mey result in creation of a new, duplicate string. I'd rather go with: All object creation will create a new object; except for immutable for which the object creator may choose to return an equivalent existing object. Immutables are the exception. -- http://mail.python.org/mailman/listinfo/python-list
NameError: name 'execfile' is not defined
Newbie issue: I downloaded http://www.python.org/download/releases/3.0.1/ (windows insaller), opened the interpreter, wrote a print Hello World program in helloworld.py, and in the interpreter typed execfile(helloworld.py) Got back NameError: name 'execfile' is not defined (following tutorial in David Beazley's Python Essential Reference). Is execfile not supported in 3? Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list
Invalid syntax with print Hello World
obviously total mewbiew: My first program in Python Windows print Hello World I select Run/Run Module and get an error: Syntax error, with the closing quote highlighted. Tried with single quotes as well. Same problem. Can someone explain my mistake? Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list
Re: NameError: name 'execfile' is not defined
Henrik Bechmann wrote: Newbie issue: I downloaded http://www.python.org/download/releases/3.0.1/ (windows insaller), opened the interpreter, wrote a print Hello World program in helloworld.py, and in the interpreter typed execfile(helloworld.py) Got back NameError: name 'execfile' is not defined (following tutorial in David Beazley's Python Essential Reference). Is execfile not supported in 3? That's correct. From http://docs.python.org/dev/3.0/whatsnew/3.0.html you can find this line: Removed execfile(). Instead of execfile(fn) use exec(open(fn).read()). Gary Herron Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
Henrik Bechmann wrote: obviously total mewbiew: My first program in Python Windows print Hello World I select Run/Run Module and get an error: Syntax error, with the closing quote highlighted. Tried with single quotes as well. Same problem. Can someone explain my mistake? You are apparently using Python2 syntax in Python3. Python3 has made some incompatible changes from previous version of Python2. In Python2: print Hello World In Python3: print(Hello World) Either download Python2.5 (or 2.6) to go with your tutorial, or find a Python3 tutorial to go with your Python3 installation.Once you are familiar with either version of the language, you will find that the differences are not very large, but using out-of-sync tutorials and implementations will be the source of much frustration. Welcome to Python. Enjoy. Gary Herron Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
obviously total mewbiew: My first program in Python Windows print Hello World I select Run/Run Module and get an error: Syntax error, with the closing quote highlighted. Tried with single quotes as well. Same problem. Can someone explain my mistake? Are you using python 3.0? In this case please see: http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
On Mar 12, 5:57 pm, Henrik Bechmann hbechm...@gmail.com wrote: obviously total mewbiew: My first program in Python Windows What is that you are callind Python Windows? What version of Python are you running? 2.X: print Hello World should work. 3.X: print is now a function, print(Hello World) should work. If that gets you going: read the tutorial that belongs to the version of Python that you are using. If it doesn't, come back here with a bit more detail. BTW, don't indent your first line. Make sure it starts in column 1. HTH, John print Hello World I select Run/Run Module and get an error: Syntax error, with the closing quote highlighted. Tried with single quotes as well. Same problem. Can someone explain my mistake? Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list
Rough draft: Proposed format specifier for a thousands separator
If anyone here is interested, here is a proposal I posted on the python-ideas list. The idea is to make numbering formatting a little easier with the new format() builtin in Py2.6 and Py3.0: http://docs.python.org/library/string.html#formatspec - Motivation: Provide a simple, non-locale aware way to format a number with a thousands separator. Adding thousands separators is one of the simplest ways to improve the professional appearance and readability of output exposed to end users. In the finance world, output with commas is the norm. Finance users and non-professional programmers find the locale approach to be frustrating, arcane and non-obvious. It is not the goal to replace locale or to accommodate every possible convention. The goal is to make a common task easier for many users. Research so far: Scanning the web, I've found that thousands separators are usually one of COMMA, PERIOD, SPACE, or UNDERSCORE. The COMMA is used when a PERIOD is the decimal separator. James Knight observed that Indian/Pakistani numbering systems group by hundreds. Ben Finney noted that Chinese group by ten-thousands. Visual Basic and its brethren (like MS Excel) use a completely different style and have ultra-flexible custom format specifiers like: _($* #,##0_). Proposal I (from Nick Coghlan]: A comma will be added to the format() specifier mini-language: [[fill]align][sign][#][0][minimumwidth][,][.precision][type] The ',' option indicates that commas should be included in the output as a thousands separator. As with locales which do not use a period as the decimal point, locales which use a different convention for digit separation will need to use the locale module to obtain appropriate formatting. The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example: format(n, 6,f).replace(,, _) This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped. format(n, 6,f).replace(,, X).replace(., ,).replace (X, .) Proposal II (to meet Antoine Pitrou's request): Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore.. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision] [type] Examples: format(1234, 8.1f)-- ' 1234.0' format(1234, 8,1f)-- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- '1234' format(1234, 8T,d) -- ' 1,234' This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but it comes at the expense of being a little more complicated to learn and remember. Also, it makes it more challenging to write custom __format__ methods that follow the format specification mini-language. For the locale module, just the T is necessary in a formatting string since the tool already has procedures for figuring out the actual separators from the local context. Comments and suggestions are welcome but I draw the line at supporting Mayan numbering conventions ;-) Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on periods in strings
En Wed, 11 Mar 2009 23:42:45 -0200, Philip Bloom pbl...@crystald.com escribió: Thanks for the welcome :) You're right. Here's with the missed line (I was cutting out commented parts). Hopefully these are all cut/paste-able. #test A #runs in 5.8 seconds. from datetime import datetime testvar2='9a00' startTime = datetime.now() filehandle=open('testwriting.txt','w') for var in range(1000): filehandle.write(testvar2) filehandle.close() print (datetime.now() - startTime) #test B [using '9.00' -- otherwise identical] I do use the same filename, but I've run the tests in different orders and it's made no difference. Repeatedly running the same test results in the same numbers with only minor fluctuations (as would be expected from cache issues). Ten runs in a row of Test B all result in about 11 seconds each. Ten runs in a row of Test A all result in about 6 seconds each. I could not reproduce this. You've got better hardware than mine, certainly (I had to remove a 0 to get reasonable times) but I got almost identical results with both versions. I've tested also with 3.0 (and I had to take another 0 off!) with the same results. I have no idea why you see a difference. Unless the antivirus is interfering, or you have some crazy driver monitoring disk activity and the dot triggers something... Try using a different language - I'd say this is totally unrelated to Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython fast and slow
iu2 isra...@elbit.co.il writes: A question about CallAfter: As I understand, this function is intended to be used from within threads, where it queues the operation to be performed in the GUI queue. I agree with the second half of the sentence but not the first. CallAfter is intended to queue up a delayed call (via the GUI queue), but it can be used anywhere you wish that behavior. Yes, it's also one of the very few functions that can be called from a thread other than the GUI thread, but it works just as well from the GUI thread. Or to quote its docstring: Call the specified function after the current and pending event handlers have been completed. This is also good for making GUI method calls from non-GUI threads. Any extra positional or keyword args are passed on to the callable when it is called. How does it work in this situation? Does it queue the opreation for some idle time or does it perform it right away? You can actually see the source in _core.py in your wx installation. It always executes via a wx.PostEvent call. And another question, if I may, I used to make tight loops in windows API, planting inside them a command that processes messages from the GUI queue and returns when no more messages exists. Something like this: loop { operations process_gui_messages } The loop ran quickly and the GUI remained responsive during the loop. I did it on window API using a function I defined similar to this one: I don't think there's much difference in the above and doing your operations during one of the events. In both cases operations is going to block any further event processing so cannot be lengthy or the GUI will feel unresponsive. Lengthy varies but I'd certainly put it in the neighborhood of small fractions of a second. Your original code took almost 2 seconds for the operations part (before getting back to processing GUI messages through the main loop), which certainly seems too long. void ProcessMessages() { while (PeekMessage()) { TranslateMessage(..); DispatchMessage(..); } } Not quite positive, but if you're talking about implementing this as a nested dispatch loop (e.g., called from within an existing event), you can do that via wxYield. Of course, as with any nested event loop processing, you have to be aware of possible reentrancy issues. This technique is not good for long loops, where the user may activate other long GUI opreations during the tight loop and make a mess. But it carries out the job well where during the time of the loop the user may only access to certain features, such as pressing a button to cancel the operation, operating the menu to exit the program, etc. This scheme saves some state-machine code that is required when using event-based programming. Maybe - for my own part, I'm not completely convinced and tend to far prefer avoiding nested event loop dispatching. There are some times when it might be unavoidable, but I tend to find it indicative that I might want to re-examine what I am doing. It seems to me that as long as you have to keep the operations step of your loop small enough, you have to be able to divide it up. So you'll need some state no matter what to be able to work through each stage of the overall operations in between calls to process the GUI. At that point, whether it's a local variable within the scope of the looping code, or just some instance variables in the object handling the event loop seems about the same amount of state management. For example, in your original code you could probably consider the generator and/or 'x' your local state. But the current step in the movement could just as easily be an instance variable. Does wxPython have something like ProcessMessages? If you just mean a way to process pending messages wxYield may be sufficient. If you want to take over the primary dispatch loop for the application, normally that has been handed off to wxWidgets via wxApp.MainLoop. However, I believe you can build your own main dispatch loop if you want, as there are functions in wxApp like ProcessPendingEvents, Pending, Dispatch and so on. You may need to explicitly continue to support Idle events in your own loop if desired. If you need to get into more details, it's probably better dealt with on the wxPython mailing list. -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: Stopping SocketServer on Python 2.5
Falcolas garri...@gmail.com wrote in message news:1b6a95a4-5680-442e-8ad0-47aa9ea08...@w1g2000prk.googlegroups.com... On Mar 11, 1:11 pm, David George d...@eatmyhat.co.uk wrote: Again, problem here is the issue of being unable to kill the server while it's waiting on a request. In theory, i could force it to continue by sending some sort of junk data with the method i use to stop the server, but that seems a bit hacky, don't you think? Dave, I agree, it does. I'm in a bit over my head at this point, but does setting self.socket.settimeout(0.5) cause the call to get_request (and thus self.socket.accept()) to timeout? If so, that may be your ticket, since socket.error exceptions are already caught by the TCPServer class. Here's the relevant code from Python 2.6's SocketServer.py. It uses select() to see if a request is waiting to be serviced so handle_request won't block. If the poll interval expires the while loop will check the __serving flag. Not ideal, but better than requiring a client to connect before the flag is checked. The comment lists another idea: def serve_forever(self, poll_interval=0.5): Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. self.__serving = True self.__is_shut_down.clear() while self.__serving: # XXX: Consider using another file descriptor or # connecting to the socket to wake this up instead of # polling. Polling reduces our responsiveness to a # shutdown request and wastes cpu at all other times. r, w, e = select.select([self], [], [], poll_interval) if r: self._handle_request_noblock() self.__is_shut_down.set() -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on periods in strings
On Mar 12, 12:42 pm, Philip Bloom pbl...@crystald.com wrote: The range is not actually a meaningful adjustment as the time results are identical switching out xrange (as I believe they should be since in 2.6 range maps to xrange for the most part according to some of the docs). Please do import sys; print sys.version and copy/paste the results into your reply. Sorry, in 2.6 range maps to xrange for the most part is just plain wrong and/or meaningless. In version X.Y, nothing maps to anything else, for any value of X or Y. What you may have read is that in 2.X, range() produces a list, and xrange() produces a magic gadget whose type is 'xrange', and that in 3.X, xrange() has disappeared, range() produces a similar gadget to what xrange() did, and if you want a list, you have to do list(range ()). This is a very interesting phenomenon, but it *doesn't* mean that xrange and range are equivalent for your problem. Note that on my machine (running Python 2.6.1 under Windows XP SP 3) doing y = range(1000) grabs about 154MB of memory. In the absence of any information from you about how much spare memory you have, Gabriel's point was quite valid. What are OS (+ version etc) are you running, and how much physical memory is free when you start running these scripts? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Read a content file from a P7M
On Wed, Mar 11, 2009 at 5:05 PM, Luca luca...@gmail.com wrote: There is standard or sugested way in python to read the content of a P7M file? I don't need no feature like verify sign, or sign using a certificate. I only need to extract the content file of the p7m (a doc, a pdf, ...) I'm there again! I found a document and some exaples related to the M2Crypto library http://eckhart.stderr.org/doc/python-m2crypto-doc/doc/howto.smime.html I tryed to use this: from M2Crypto import BIO, SMIME, X509 p7, data = SMIME.smime_load_pkcs7('/Users/luca/Desktop/testsigned.pdf.p7m') Traceback (most recent call last): File stdin, line 1, in ? File build/bdist.macosx-10.5-i386/egg/M2Crypto/SMIME.py, line 91, in smime_load_pkcs7 M2Crypto.SMIME.SMIME_Error: no content type May be this is the wrong library... but even Google can't help me a lot with this problem :-( -- -- luca -- http://mail.python.org/mailman/listinfo/python-list
Re: A Dangling Tk Entry
On Mar 11, 1:09 am, Marc 'BlackJack' Rintsch bj_...@gmx.net wrote: Then he did it consequently wrong. `frame_delay` is always `None` here so the ``return`` is useless. You asked what this code means and now you don't like the answer that it's somewhat useless code!? Ciao, Marc 'BlackJack' Rintsch Oh this is not the first time Walter has asked for help and then scoffed at those who wish to help him. Just look back through a few of his posts. I had ignored the other rudeness but i won't anymore. -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
On Mar 12, 4:26 am, r rt8...@gmail.com wrote: On Mar 11, 10:09 pm, s...@pobox.com wrote: In fact, graphics were added for several organizations. I believe they will be chosen randomly. NASA is still there. --http://mail.python.org/mailman/listinfo/python-list Whew! Thats good news, i thought we had lost their support. That's pretty much impossible. I am sure NASA uses all programming languages in existence, plus probably many internal ones we never heard of. -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
s...@pobox.com wrote: In fact, graphics were added for several organizations. I believe they will be chosen randomly. NASA is still there. In that case, they must be using the random number generator from Dilbert. You know, the one that said 9, 9, 9, 9,... I, at least, get the same parking lot graphics every time I reload the page. /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
If anyone here is interested, here is a proposal I posted on the python-ideas list. The idea is to make numbering formatting a little easier with the new format() builtin: http://docs.python.org/library/string.html#formatspec Here's a re-post (hopefully without the line wrapping problems in the previous post). Raymond - Motivation: --- Provide a simple, non-locale aware way to format a number with a thousands separator. Adding thousands separators is one of the simplest ways to improve the professional appearance and readability of output exposed to end users. In the finance world, output with commas is the norm. Finance users and non-professional programmers find the locale approach to be frustrating, arcane and non-obvious. It is not the goal to replace locale or to accommodate every possible convention. The goal is to make a common task easier for many users. Research so far: Scanning the web, I've found that thousands separators are usually one of COMMA, PERIOD, SPACE, or UNDERSCORE. The COMMA is used when a PERIOD is the decimal separator. James Knight observed that Indian/Pakistani numbering systems group by hundreds. Ben Finney noted that Chinese group by ten-thousands. Visual Basic and its brethren (like MS Excel) use a completely different style and have ultra-flexible custom format specifiers like: _($* #,##0_). Proposal I (from Nick Coghlan): --- A comma will be added to the format() specifier mini-language: [[fill]align][sign][#][0][minimumwidth][,][.precision][type] The ',' option indicates that commas should be included in the output as a thousands separator. As with locales which do not use a period as the decimal point, locales which use a different convention for digit separation will need to use the locale module to obtain appropriate formatting. The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example: format(n, 6,f).replace(,, _) This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped: format(n, 6,f).replace(,, X).replace(., ,).replace(X, .) Proposal II (to meet Antoine Pitrou's request): --- Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type] Examples: format(1234, 8.1f)-- ' 1234.0' format(1234, 8,1f)-- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- '1234' format(1234, 8T,d)-- ' 1,234' This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but iIt comes at the expense of being a little more complicated to learn and remember. Also, it makes it more challenging to write custom __format__ methods that follow the format specification mini-language. For the locale module, just the T is necessary in a formatting string since the tool already has procedures for figuring out the actual separators from the local context. -- http://mail.python.org/mailman/listinfo/python-list
PythonWin, python thread and PostQuitMessage?
Hi All, I'm not so much involved in any Windows programming however I needed to write a client for the Windows platform. I have this very simple question which I've been unable to answer. I'm listening for keyboard strokes using the pyhook library. I'm doing this in a dedicated thread. The gui just controls the thread. When I want to pause listening for keyboard strokes I wanted to do a PostQuitMessage() to the thread. However this does not work since it either kills the whole app or just does not happen in the thread it's supposed to. I've now made an ugly workaround using PumpWaitingMessages and a delay. def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() while self.log: win32gui.PumpWaitingMessages() time.sleep(0.02) i can now just cancel the process by setting self.log to False. I wanted to do just: def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() win32gui.PumpMessages() However I'm unable to stop this process. Can anyone shred al light here? Rg, Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger wrote: The idea is to make numbering formatting a little easier with the new format() builtin: http://docs.python.org/library/string.html#formatspec [...] Scanning the web, I've found that thousands separators are usually one of COMMA, PERIOD, SPACE, or UNDERSCORE. The COMMA is used when a PERIOD is the decimal separator. James Knight observed that Indian/Pakistani numbering systems group by hundreds. Ben Finney noted that Chinese group by ten-thousands. IIRC, some cultures use a non-uniform grouping, like e.g. 123 456 78.9. For that, there is also a grouping reserved in the locale (at least in those of C++ IOStreams, that is). Further, an that seems to also be one of your concerns, there are different ways to represent negative numbers like e.g. (123) or -456. Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type] Examples: format(1234, 8.1f)-- ' 1234.0' format(1234, 8,1f)-- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- '1234' format(1234, 8T,d)-- ' 1,234' How about this? format(1234, 8.1, tsep=,) -- ' 1,234.0' format(1234, 8.1, tsep=., dsep=,) -- ' 1.234,0' format(123456, tsep= , grouping=(3, 2,)) -- '1 234 56' IOW, why not explicitly say what you want using keyword arguments with defaults instead of inventing an IMHO cryptic, read-only mini-language? Seriously, the problem I see with this proposal is that its aim to be as short as possible actually makes the resulting format specifications unreadable. Could you even guess what 8T.,1f should mean if you had not written this? This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but iIt comes at the expense of being a little more complicated to learn and remember. Too expensive for my taste. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
__import__ with dict values
How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
From what I see most startups are jumping to Python to rapidly setup their prototypes. On Thu, Mar 12, 2009 at 10:38 AM, Mikael Olofsson mik...@isy.liu.se wrote: s...@pobox.com wrote: In fact, graphics were added for several organizations. I believe they will be chosen randomly. NASA is still there. In that case, they must be using the random number generator from Dilbert. You know, the one that said 9, 9, 9, 9,... I, at least, get the same parking lot graphics every time I reload the page. /MiO -- http://mail.python.org/mailman/listinfo/python-list -- http://www.goldwatches.com/ http://www.jewelerslounge.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
I, at least, get the same parking lot graphics every time I reload the page. If you click and more link, you will come to a page of success stories, one of which is this: http://python.org/about/success/usa/ It is not as prominent as the earlier Nasa logo, though. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-ي А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я ä-ö-ü-ß-Ä-Ö-Ü -- http://mail.python.org/mailman/listinfo/python-list
Re: c.Win32_OperatingSystem question.
Hi, well coming back to the project and looking over it I realized I had somehow messed up the names for some Win32 Operating System properties - for example ComputerOrganization instead of Organization. Not sure where I got the values from cause I've just be copying the properties I want from scriptomatic output. Cheers, Bryan Rasmussen On Sat, Feb 28, 2009 at 8:15 PM, Tim Golden m...@timgolden.me.uk wrote: bryan rasmussen wrote: Maybe there's a more specific list I should ask this question on but I don't know what it is. I'm using Tim Golden's wmi stuff, and putting my output into an XML document. I have the following bit of code [.. snip ...] At the end of that thhe only text node thaht comes out is ComputerName, WMI is running - Am I using the wrong names for things here? When I try to get the same values using WScript and WQL to extract from Win32_OperatingSystem I get all the values. I'd love to help here, but you're not making it easy. I'm not clear if you're suggesting there's a problem with WMI or with ElementTree or with something else. Can you narrow down, please so I don't have to invent a code wrapper for your code fragment. Try producing an instantly-runnable piece of code which demonstrates the problem and I'll happily have a look from the WMI perspective at least. TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on periods in strings
Philip Bloom a écrit : (snip) from datetime import datetime startTime = datetime.now() (snip) print (datetime.now() - startTime) A bit OT, but you may want to use timeit.Timer for this kind of microbenchmarks. (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
I have resolved this problem in my code. It has something to do with your current working directory when you append cwd/jars to sys.path and try to import from interactive console -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy aleksandr.gore...@gmail.comwrote: How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
yay, no more exec (import + sys) in my code -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy aleksandr.gore...@gmail.comwrote: I have resolved this problem in my code. It has something to do with your current working directory when you append cwd/jars to sys.path and try to import from interactive console -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy aleksandr.gore...@gmail.com wrote: How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
or eval for that matter -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy aleksandr.gore...@gmail.comwrote: yay, no more exec (import + sys) in my code -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I have resolved this problem in my code. It has something to do with your current working directory when you append cwd/jars to sys.path and try to import from interactive console -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy aleksandr.gore...@gmail.com wrote: How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
note i would still like to be able to do __import__(sys).path maybe if __import__ had __str__ defined, How is my thinking on this? and how would I achieve something like this? -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy aleksandr.gore...@gmail.comwrote: or eval for that matter -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy aleksandr.gore...@gmail.com wrote: yay, no more exec (import + sys) in my code -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I have resolved this problem in my code. It has something to do with your current working directory when you append cwd/jars to sys.path and try to import from interactive console -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy aleksandr.gore...@gmail.com wrote: How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
On Mar 12, 2:25 am, John Machin sjmac...@lexicon.net wrote: On Mar 12, 5:57 pm, Henrik Bechmann hbechm...@gmail.com wrote: obviously total mewbiew: My first program in Python Windows What is that you are callind Python Windows? What version of Python are you running? 2.X: print Hello World should work. 3.X: print is now a function, print(Hello World) should work. If that gets you going: read the tutorial that belongs to the version of Python that you are using. If it doesn't, come back here with a bit more detail. BTW, don't indent your first line. Make sure it starts in column 1. HTH, John print Hello World I select Run/Run Module and get an error: Syntax error, with the closing quote highlighted. Tried with single quotes as well. Same problem. Can someone explain my mistake? Thanks, - Henrik- Hide quoted text - - Show quoted text - Henrik, Welcome to the list. As a newbie myself, I ran into the Python3 vrs 2.6 issue. May I suggest starting with 2.6? There is many more books and internet stuff you can learn with in 2.6 - and the examples will work. As Garry wrote, once you understand 2.6, 3.0 will not be a challenge. Steve Oldner -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
__import__(opt['imp_mod']).options eval(opt['imp_mod']+.+opt['imp_opt']) how to make top work like bottom? -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:56 AM, alex goretoy aleksandr.gore...@gmail.comwrote: note i would still like to be able to do __import__(sys).path maybe if __import__ had __str__ defined, How is my thinking on this? and how would I achieve something like this? -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:44 AM, alex goretoy aleksandr.gore...@gmail.com wrote: or eval for that matter -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:43 AM, alex goretoy aleksandr.gore...@gmail.com wrote: yay, no more exec (import + sys) in my code -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 5:42 AM, alex goretoy aleksandr.gore...@gmail.com wrote: I have resolved this problem in my code. It has something to do with your current working directory when you append cwd/jars to sys.path and try to import from interactive console -Alex Goretoy http://www.goretoy.com On Thu, Mar 12, 2009 at 4:58 AM, alex goretoy aleksandr.gore...@gmail.com wrote: How would I import with __import__ from dict values? I want sys.path value inside d['syspath'], below code doesn't work for me d={} d['sys']='sys' d['path']='path' d['syspath']=__import__(d['sys'],fromlist=[d['path']]) and how come does above line doesn't give me diff value than below line? d['syspath']=__import__(d['sys']) Meaning, when I do this doesn't work. Which makes sense. d['syspath']() d['syspath'].d['path'] but this works both with fromlist and without. d['syspath'].path -Alex Goretoy http://www.goretoy.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
Welcome to the list. As a newbie myself, I ran into the Python3 vrs 2.6 issue. May I suggest starting with 2.6? There is many more books and internet stuff you can learn with in 2.6 - and the examples will work. As Garry wrote, once you understand 2.6, 3.0 will not be a challenge. I do not think that is the best way to go about learning Python. Why learn an arguably depreciating version when the new version is available. I agree that there are not many tutorial written for Python 3 however there are enough to get going: most of the Python 2 tutorials are redundant. Sticking to Python 3 tutorials will give him a higher signal-to-noise ratio in the tutorials that he finds. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-ي А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я ä-ö-ü-ß-Ä-Ö-Ü -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
[Ulrich Eckhardt] IOW, why not explicitly say what you want using keyword arguments with defaults instead of inventing an IMHO cryptic, read-only mini-language? That makes sense to me but I don't think that's the way the format() builtin was implemented (see PEP 3101 which was implemented Py2.6 and 3.0). It is a simple pass-through to a __format__ method for each formattable object. I don't see how keywords would fit in that framework. What is proposed is similar to locale module's existing n specifier except that this lets you say exactly what you want instead of deferring to the locale settings. The mini-language seems to already be the way of things (just as it is many other languages including PHP, C, Fortran, and whatnot). I'm just proposing an addition T, so you add commas as a thousands separator. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Input data from .txt file and object array problem
I want to input data by using pickle First of all, I have a database.txt The content is like: AAA,aaalink BBB,bbblink CCC,ccclink ...,... AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their respective link. I want to store data by using pickle. Meanwhile , I got a problem. #I have created a class: class Lang: def __init__(self,lname=,tlink=,alink=): self.lname = lname #lname is the Language self.tlink = tlink #tlink is the tutorial link self.alink = alink #alink is the a link to school Library finding the first returned Language book def alibrary_link(self,alink): self.alink = alink def tutorial_link(self,tlink): self.tlink = tlink def lang_name(self,lname): self.lname = lname def _display(self): string = +++ + \ + + lname \ + + tlink \ + + alink \ + def Print(self): print self._display() def originData(): fo = (/database.txt,r+) lines = fo.readlines() for line in lines: pair = line.split(,) temp = Lang(); temp.lname = pair[0] temp.tlink = pair[1] temp.alink = findbook(temp.lname) #stopping here, because I don't know how to do here... #I want to use object array here... #Then using pickle to dump the object... # Is this work? Or there is another better method to do so? I hope to create an object array to store all the language and its information from database.txt. How can I do that? I am a beginner to Python. Any help would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
If they were so keen on new graphics, why did 2.6 revert to the same icons that 2.4 used? (At least they did on my machine. After installing 2.6, I no longer had the new 2.5 icons but had reverted to the earlier ones.) Can you be more specific? Is this a Windows thing? Did you submit a bug report? -- Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/ -- http://mail.python.org/mailman/listinfo/python-list
cross platform accessing paths (windows, linux ...)
Hi all, I'd like to ask for some advice on how to acomplish file access in a cross platform way. My application is a kind of viewer of text and corresponding image files (stored in separate subdirectories) and I'm going to deploy it as binaries for windows and source files (again in separate directories); Of course the text and image data should be shared for the source and executable version. The program should be runnable without instalation, e.g. directly from a CD-ROM, flashdisk etc. (supposing the working python ... installation while using the source version). the directory structure looks like: my_viewer - src - bin - txt - img While writing the source on windows, I didn't notice problems, as the simple path ../txt/text_1.txt worked well with open(...). (script file executed with the associated python.exe) However on Linux (Kubuntu 8.0.4) the files in neighbour directories were not found most of the time (probably depending on how the script was run - console; file manager Krusader ...) After a lot of trials and gradually solving some corner issues, I ended up with: def path_from_pardir(path): return os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, path))) # __file__ is substituted with sys.path[0] if not present real_path = path_from_pardir(txt/text_1.txt) The above seems to work both on windows and linux, but it very much looks like woodoo code for me; as I have rather limited experiences on Linux, I'd like to ask, how this would be best done in a cross platform way; or is the above realy the way to go? (I hope, using / as path separator should be fine, as it is also supported on windows and other OS would use the slash anyway; is it true, or do I have to use os.sep (which would complicate the code slightly more)? Are there any issues I'm likely to run into say on Mac with this approach? I'm using python 2.5.4 on windows XPp SP3, and the default python 2.5.2 on Kubuntu 8.0.4; (as I probably can't reasonably use 2.6 here for deployment with py2exe). Any hints or comments are much appreciated; thanks in advance! regards, Vlasta -- http://mail.python.org/mailman/listinfo/python-list
Re: Building python 64-bit on OS 10.5?
Dear all: I've two questions: 1) I've been trying to building python as a 64-bit version on OS 10.5. I'm not too familiar with building python from scratch, and a number of basic attempts made from piecing together things I've seen on the web have failed. (For instance, ./configure --enable-framework --disable-toolbox-glue --with-universal-archs=all --with-gcc=gcc -m64 leads to a failure when I try to do make, as do all other similar variants I've tried.) So, is there a good source where I can find step-by-step 64-bit build instructions? (I'd like to do it if possible as a framework build.) I've looked it up a lot on google but am mostly getting fragments of descriptions of errors with other people's builds. 2) I often use a number of python extensions like matplot, pylab, and ipython. Will these (especially the graphics parts) be able to build on top of my 64-bit installation? Is there some way to find out if they will likely work without actually having to build them? Thanks! Dan -- http://mail.python.org/mailman/listinfo/python-list
multiprocessing + atexit
I have some code that uses atexit (remove old log files). Before converting to use multiprocessing, it worked. Since converting, it seems to not be running the atexit code (old log files are not removed). Any known issues with multiprocessing + atexit? -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on periods in strings
Gabriel I could not reproduce this. Nor can I. I didn't see the original post. What were the hardware parameters and Python version? -- Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
In fact, graphics were added for several organizations. I believe they will be chosen randomly. NASA is still there. MiO In that case, they must be using the random number generator from MiO Dilbert. You know, the one that said 9, 9, 9, 9,... Sorry, randomly chosen whenever the front page is rebuilt by one of the web gnomes. It's not chosen randomly on each page fetch. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform accessing paths (windows, linux ...)
You might want to look at the path module: http://pypi.python.org/pypi/path.py/2.2 It will probably make your code more readable. On Thu, Mar 12, 2009 at 8:10 AM, Vlastimil Brom vlastimil.b...@gmail.comwrote: Hi all, I'd like to ask for some advice on how to acomplish file access in a cross platform way. My application is a kind of viewer of text and corresponding image files (stored in separate subdirectories) and I'm going to deploy it as binaries for windows and source files (again in separate directories); Of course the text and image data should be shared for the source and executable version. The program should be runnable without instalation, e.g. directly from a CD-ROM, flashdisk etc. (supposing the working python ... installation while using the source version). the directory structure looks like: my_viewer - src - bin - txt - img While writing the source on windows, I didn't notice problems, as the simple path ../txt/text_1.txt worked well with open(...). (script file executed with the associated python.exe) However on Linux (Kubuntu 8.0.4) the files in neighbour directories were not found most of the time (probably depending on how the script was run - console; file manager Krusader ...) After a lot of trials and gradually solving some corner issues, I ended up with: def path_from_pardir(path): return os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, path))) # __file__ is substituted with sys.path[0] if not present real_path = path_from_pardir(txt/text_1.txt) The above seems to work both on windows and linux, but it very much looks like woodoo code for me; as I have rather limited experiences on Linux, I'd like to ask, how this would be best done in a cross platform way; or is the above realy the way to go? (I hope, using / as path separator should be fine, as it is also supported on windows and other OS would use the slash anyway; is it true, or do I have to use os.sep (which would complicate the code slightly more)? Are there any issues I'm likely to run into say on Mac with this approach? I'm using python 2.5.4 on windows XPp SP3, and the default python 2.5.2 on Kubuntu 8.0.4; (as I probably can't reasonably use 2.6 here for deployment with py2exe). Any hints or comments are much appreciated; thanks in advance! regards, Vlasta -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger wrote: [snip] Proposal I (from Nick Coghlan): --- A comma will be added to the format() specifier mini-language: [[fill]align][sign][#][0][minimumwidth][,][.precision][type] The ',' option indicates that commas should be included in the output as a thousands separator. As with locales which do not use a period as the decimal point, locales which use a different convention for digit separation will need to use the locale module to obtain appropriate formatting. The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example: format(n, 6,f).replace(,, _) This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped: format(n, 6,f).replace(,, X).replace(., ,).replace(X, .) Proposal II (to meet Antoine Pitrou's request): --- Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision][type] Examples: format(1234, 8.1f)-- ' 1234.0' format(1234, 8,1f)-- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- '1234' format(1234, 8T,d)-- ' 1,234' This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but iIt comes at the expense of being a little more complicated to learn and remember. Also, it makes it more challenging to write custom __format__ methods that follow the format specification mini-language. For the locale module, just the T is necessary in a formatting string since the tool already has procedures for figuring out the actual separators from the local context. [snip] I'd probably prefer Proposal I with . representing the decimal point and , representing the grouping (thousands) separator, although I'd add an L flag to indicate that it should use the locale to provide the actual characters to be used and even the number of digits for the grouping: [[fill]align][sign][#][0][minimumwidth][,][.precision][L][type] Examples: Assuming the locale has: decimal point: , grouping separator: . grouping spacing: 3 format(123456, 10.1f)-- ' 123456.0' format(123456, 10.1Lf) -- ' 123.456,0' format(123456, 10,.1f) -- ' 123,456.0' format(123456, 10,.1Lf) -- ' 123.456,0' -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Ulrich Eckhardt eck...aser.com wrote: IOW, why not explicitly say what you want using keyword arguments with defaults instead of inventing an IMHO cryptic, read-only mini-language? Seriously, the problem I see with this proposal is that its aim to be as short as possible actually makes the resulting format specifications unreadable. Could you even guess what 8T.,1f should mean if you had not written this? +1 Look back in history, and see how COBOL did it with the PICTURE - dead easy and easily understandable. Compared to that, even the C printf stuff and python's % are incomprehensible. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
loop performance in global namespace (python-2.6.1)
In the following snippet, the loop in the global namespace takes twice as long as the loop in the function namespace. Why? limit = 5000 def f1(): counter = 0 while counter limit: counter += 1 time1 = time.time() f1() print(time.time() - time1) print('number of locals: ', len(locals())) time1 = time.time() counter = 0 while counter limit: counter += 1 print(time.time() - time1) print('number of locals: ', len(locals())) -- Yorick -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] loop performance in global namespace (python-2.6.1)
Le Thu, 12 Mar 2009 11:13:33 -0400, Kent Johnson ken...@tds.net s'exprima ainsi: Because local name lookup is faster than global name lookup. Local variables are stored in an array in the stack frame and accessed by index. Global names are stored in a dict and accessed with dict access (dict.__getitem__()). ? I thought this was mainly because a name has first to be searched (unsuccessfully) locally before a global lookup is launched. Also, are locals really stored in an array? How does lookup then proceed? Is it a kind of (name,ref) sequence? Denis -- la vita e estrany -- http://mail.python.org/mailman/listinfo/python-list
Re: Input data from .txt file and object array problem
On Mar 12, 5:03 am, SamuelXiao foolsmart2...@gmail.com wrote: I want to input data by using pickle First of all, I have a database.txt The content is like: AAA,aaalink BBB,bbblink CCC,ccclink ...,... AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their respective link. I want to store data by using pickle. Meanwhile , I got a problem. #I have created a class: class Lang: def __init__(self,lname=,tlink=,alink=): self.lname = lname #lname is the Language self.tlink = tlink #tlink is the tutorial link self.alink = alink #alink is the a link to school Library finding the first returned Language book def alibrary_link(self,alink): self.alink = alink def tutorial_link(self,tlink): self.tlink = tlink def lang_name(self,lname): self.lname = lname def _display(self): string = +++ + \ + + lname \ + + tlink \ + + alink \ + def Print(self): print self._display() def originData(): fo = (/database.txt,r+) lines = fo.readlines() for line in lines: pair = line.split(,) temp = Lang(); temp.lname = pair[0] temp.tlink = pair[1] temp.alink = findbook(temp.lname) #stopping here, because I don't know how to do here... #I want to use object array here... #Then using pickle to dump the object... # Is this work? Or there is another better method to do so? I hope to create an object array to store all the language and its information from database.txt. How can I do that? I am a beginner to Python. Any help would be appreciated. check out the csv module for the parsing of the file http://docs.python.org/library/csv.html -- http://mail.python.org/mailman/listinfo/python-list
Re: can python import class or module directly from a zip package
On Mar 11, 9:47 pm, Lorenzo lolue...@gmail.com wrote: On Mar 10, 2:13 pm, Flank fla...@gmail.com wrote: can python import class or module directly from a zip package ,just like jave does from jar package without extracting the class file into directory so far as i know ,python module should be unzip to file system in order to use them, After a little digging/googling, the answer came right from the docs: http://docs.python.org/library/zipimport.html I think that this module is just right what you need. Cheers! thanks you 2 guys -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Mar 12, 9:56 pm, Raymond Hettinger pyt...@rcn.com wrote: [Ulrich Eckhardt] IOW, why not explicitly say what you want using keyword arguments with defaults instead of inventing an IMHO cryptic, read-only mini-language? That makes sense to me but I don't think that's the way the format() builtin was implemented (see PEP 3101 which was implemented Py2.6 and 3.0). It is a simple pass-through to a __format__ method for each formattable object. I don't see how keywords would fit in that framework. What is proposed is similar to locale module's existing n specifier except that this lets you say exactly what you want instead of deferring to the locale settings. The mini-language seems to already be the way of things (just as it is many other languages including PHP, C, Fortran, and whatnot). I'm just proposing an addition T, so you add commas as a thousands separator. ... and why not C (centum) for hundreds (can't have H(ollerith)) and W for wan (the Chinese word for 10 thousand)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
On 12 Mar, 12:45, Dotan Cohen dotanco...@gmail.com wrote: [starting with 2.6] I do not think that is the best way to go about learning Python. Why learn an arguably depreciating version when the new version is available. I agree that there are not many tutorial written for Python 3 however there are enough to get going: most of the Python 2 tutorials are redundant. Sticking to Python 3 tutorials will give him a higher signal-to-noise ratio in the tutorials that he finds. So we are to conclude that Python 2 is redundant now, are we? I don't think it's bad advice to suggest that people learn Python 2 if they want to get stuff done, and since people keep saying how Python 3 is really the same language, let us entertain that assertion and encourage people to take advantage of its predecessor: the thing which actually powers the overwhelming majority of Python-powered systems today and for the foreseeable future. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
On Mar 12, 7:45 am, Dotan Cohen dotanco...@gmail.com wrote: Welcome to the list. As a newbie myself, I ran into the Python3 vrs 2.6 issue. May I suggest starting with 2.6? There is many more books and internet stuff you can learn with in 2.6 - and the examples will work. As Garry wrote, once you understand 2.6, 3.0 will not be a challenge. I do not think that is the best way to go about learning Python. Why learn an arguably depreciating version when the new version is available. I agree that there are not many tutorial written for Python 3 however there are enough to get going: most of the Python 2 tutorials are redundant. Sticking to Python 3 tutorials will give him a higher signal-to-noise ratio in the tutorials that he finds. -- Dotan Cohen http://what-is-what.comhttp://gibberish.co.il א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-ي А-Б-В-Г-Д-Е-Ё-Ж-З-И-Й-К-Л-М-Н-О-П-Р-С-Т-У-Ф-Х-Ц-Ч-Ш-Щ-Ъ-Ы-Ь-Э-Ю-Я а-б-в-г-д-е-ё-ж-з-и-й-к-л-м-н-о-п-р-с-т-у-ф-х-ц-ч-ш-щ-ъ-ы-ь-э-ю-я ä-ö-ü-ß-Ä-Ö-Ü Thanks everyone! Now that I know what the issue is (2 vs 3), I'll be able to resolve those kinds of issues in the future. Thanks again! - Henrik -- http://mail.python.org/mailman/listinfo/python-list
Re: NameError: name 'execfile' is not defined
On Mar 12, 3:15 am, Gary Herron gher...@islandtraining.com wrote: Henrik Bechmann wrote: Newbie issue: I downloadedhttp://www.python.org/download/releases/3.0.1/(windows insaller), opened the interpreter, wrote a print Hello World program in helloworld.py, and in the interpreter typed execfile(helloworld.py) Got back NameError: name 'execfile' is not defined (following tutorial in David Beazley's Python Essential Reference). Is execfile not supported in 3? That's correct. Fromhttp://docs.python.org/dev/3.0/whatsnew/3.0.htmlyou can find this line: Removed execfile(). Instead of execfile(fn) use exec(open(fn).read()). Gary Herron Thanks, - Henrik -- http://mail.python.org/mailman/listinfo/python-list Excellent. Thanks very much! - Henrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Stopping SocketServer on Python 2.5
On 2009-03-12 08:03:06 +, Mark Tolonen metolone+gm...@gmail.com said: Falcolas garri...@gmail.com wrote in message news:1b6a95a4-5680-442e-8ad0-47aa9ea08...@w1g2000prk.googlegroups.com... On Mar 11, 1:11 pm, David George d...@eatmyhat.co.uk wrote: Again, problem here is the issue of being unable to kill the server while it's waiting on a request. In theory, i could force it to continue by sending some sort of junk data with the method i use to stop the server, but that seems a bit hacky, don't you think? Dave, I agree, it does. I'm in a bit over my head at this point, but does setting self.socket.settimeout(0.5) cause the call to get_request (and thus self.socket.accept()) to timeout? If so, that may be your ticket, since socket.error exceptions are already caught by the TCPServer class. Here's the relevant code from Python 2.6's SocketServer.py. It uses select() to see if a request is waiting to be serviced so handle_request won't block. If the poll interval expires the while loop will check the __serving flag. Not ideal, but better than requiring a client to connect before the flag is checked. The comment lists another idea: def serve_forever(self, poll_interval=0.5): Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. self.__serving = True self.__is_shut_down.clear() while self.__serving: # XXX: Consider using another file descriptor or # connecting to the socket to wake this up instead of # polling. Polling reduces our responsiveness to a # shutdown request and wastes cpu at all other times. r, w, e = select.select([self], [], [], poll_interval) if r: self._handle_request_noblock() self.__is_shut_down.set() -Mark Thanks to everybody for helping me with this matter, but eventually i've had to settle for a simpler and probably far less elegant solution due to time constraints. It seems that SocketServer.py in 2.6 doesn't directly rely on anything that's in Python 2.6, so i've simply copied the code across and i'm using it in place of the version built into Python 2.5. I will probably return to this at a later date and try for a more elegant solution, but right now university deadlines are looming! Thanks all, Dave -- http://mail.python.org/mailman/listinfo/python-list
How to send an email with GMail in Python from Windows
Hi Can somebody help me with sending an email using Python from GMail Here's what I tried but it fails always. import smtplib import base64 smtpserver = 'smtp.gmail.com' AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1 smtpuser = 'u...@gmail.com' # for SMTP AUTH, set SMTP username here smtppass = '*' # for SMTP AUTH, set SMTP password here RECIPIENTS = ['someu...@gmail.com'] SENDER = 'someu...@gmail.com' mssg = open('mssg.txt', 'r').read() # I am reading from this file on the same directory session = smtplib.SMTP(smtpserver,'465') session.ehlo() #session.esmtp_features[auth] = LOGIN PLAIN session.connect(smtpserver,'465') session.ehlo() session.starttls() session.set_debuglevel(1) session.helo() if AUTHREQUIRED: try: session.login(smtpuser, smtppass) except SMTPAuthenticationError, e: # if login fails, try again using a manual plain login method smtp.docmd(AUTH LOGIN, base64.b64encode( smtpuser )) smtp.docmd(base64.b64encode( smtppass ), ) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = for recip in smtpresult.keys(): errstr = Could not delivery mail to: %s Server said: %s %s %s % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr This is the Stack Trace I got when I ran the above script after a very long time(15min) Traceback (most recent call last): File C:\Python26\Mail.py, line 13, in module session = smtplib.SMTP(smtpserver,'465') File C:\Python26\lib\smtplib.py, line 239, in __init__ (code, msg) = self.connect(host, port) File C:\Python26\lib\smtplib.py, line 296, in connect (code, msg) = self.getreply() File C:\Python26\lib\smtplib.py, line 340, in getreply raise SMTPServerDisconnected(Connection unexpectedly closed) smtplib.SMTPServerDisconnected: Connection unexpectedly closed Tool completed with exit code 1 __ Thanks Avinash -- http://mail.python.org/mailman/listinfo/python-list
Re: How to send an email with GMail in Python from Windows
You might want to try - http://libgmail.sourceforge.net/. This is a Python binding for GMail; I've used it a little and it did the job for me. Dorzey -- http://mail.python.org/mailman/listinfo/python-list
Re: How to send an email with GMail in Python from Windows
Howdy Avinash, Here is a simple example for you. from smtplib import SMTP HOST = smtp.gmail.com PORT = 587 ACCOUNT = # put your gmail email account here PASSWORD =# put your gmail email password here def send_email(to_addrs, subject, msg): server = SMTP(HOST,PORT) server.set_debuglevel(1)# you don't need this (comment out to avoid debug messages) server.ehlo() server.starttls() server.ehlo() server.login(ACCOUNT, PASSWORD) server.sendmail(ACCOUNT, to_addrs, From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n.\r\n % ( ACCOUNT, ,.join(to_addrs), subject, msg ) ) server.quit() if __name__ == __main__: send_email( ['somew...@somewhere.com'], 'this is just a test', hello world! ) --gordy -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Mar 12, 3:30 am, Raymond Hettinger pyt...@rcn.com wrote: If anyone here is interested, here is a proposal I posted on the python-ideas list. The idea is to make numbering formatting a little easier with the new format() builtin in Py2.6 and Py3.0: http://docs.python.org/library/string.html#formatspec - Motivation: Provide a simple, non-locale aware way to format a number with a thousands separator. Adding thousands separators is one of the simplest ways to improve the professional appearance and readability of output exposed to end users. In the finance world, output with commas is the norm. Finance users and non-professional programmers find the locale approach to be frustrating, arcane and non-obvious. It is not the goal to replace locale or to accommodate every possible convention. The goal is to make a common task easier for many users. Research so far: Scanning the web, I've found that thousands separators are usually one of COMMA, PERIOD, SPACE, or UNDERSCORE. The COMMA is used when a PERIOD is the decimal separator. James Knight observed that Indian/Pakistani numbering systems group by hundreds. Ben Finney noted that Chinese group by ten-thousands. Visual Basic and its brethren (like MS Excel) use a completely different style and have ultra-flexible custom format specifiers like: _($* #,##0_). Proposal I (from Nick Coghlan]: A comma will be added to the format() specifier mini-language: [[fill]align][sign][#][0][minimumwidth][,][.precision][type] The ',' option indicates that commas should be included in the output as a thousands separator. As with locales which do not use a period as the decimal point, locales which use a different convention for digit separation will need to use the locale module to obtain appropriate formatting. The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example: format(n, 6,f).replace(,, _) This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped. format(n, 6,f).replace(,, X).replace(., ,).replace (X, .) Proposal II (to meet Antoine Pitrou's request): Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore.. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision] [type] Examples: format(1234, 8.1f) -- ' 1234.0' format(1234, 8,1f) -- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- ' 1234' format(1234, 8T,d) -- ' 1,234' This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but it comes at the expense of being a little more complicated to learn and remember. Also, it makes it more challenging to write custom __format__ methods that follow the format specification mini-language. For the locale module, just the T is necessary in a formatting string since the tool already has procedures for figuring out the actual separators from the local context. Comments and suggestions are welcome but I draw the line at supporting Mayan numbering conventions ;-) Raymond As far as I am concerned the most simple version plus a way to swap around commas and period is all that is needed. The rest can be done using one replace (because the decimal separator is always one of two options). This should cover everywhere but the far east. 80% of cases for 20% of implementation complexity. For example: [[fill]align][sign][#][0][,|.][minimumwidth][.precision][type] format(1234, .8.1f) -- ' 1.234,0' format(1234, ,8.1f) -- ' 1,234.0' -- http://mail.python.org/mailman/listinfo/python-list
default shelve on linux corrupts, does different DB system help?
I have the problem that my shelve(s) sometimes corrupt (looks like it has after python has run out of threads). I am using the default shelve so on linux I get the dbhash version. Is there a different DB type I can choose that is known to be more resilient? And if so, what is the elegant way of doing that? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Input data from .txt file and object array problem
SamuelXiao foolsmart2...@gmail.com (S) wrote: S I want to input data by using pickle S First of all, I have a database.txt S The content is like: S AAA,aaalink S BBB,bbblink S CCC,ccclink S ...,... S AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their S respective link. S I want to store data by using pickle. Meanwhile , I got a problem. S #I have created a class: S class Lang: S def __init__(self,lname=,tlink=,alink=): S self.lname = lname #lname is the Language S self.tlink = tlink #tlink is the tutorial link S self.alink = alink #alink is the a link to school Library finding S the first returned Language book S def alibrary_link(self,alink): S self.alink = alink S def tutorial_link(self,tlink): S self.tlink = tlink S def lang_name(self,lname): S self.lname = lname S def _display(self): S string = +++ + \ S + + lname \ S + + tlink \ S + + alink \ S + This will not do very much. The string is calculated and then thrown away. You will need also a return string to make it useful. S def Print(self): S print self._display() S def originData(): S fo = (/database.txt,r+) S lines = fo.readlines() S for line in lines: S pair = line.split(,) S temp = Lang(); S temp.lname = pair[0] S temp.tlink = pair[1] S temp.alink = findbook(temp.lname) Why do you set these attributes directly while you also have methods for this (like lang_name, tutorial_link)? Or better use temp = Lang(pair[0], pair[1], findbook(temp.lname)) S #stopping here, because I don't know how to do here... S#I want to use object array here... S#Then using pickle to dump the object... S# Is this work? Or there is another better method to do so? S I hope to create an object array to store all the language and its S information from database.txt. I guess you want to put them in a list. Then use objList.append(temp) here and objList = [] before the loop. S How can I do that? I am a beginner to Python. Any help would be S appreciated. You can use pickle to store the list is a file after reading. Something like (untested): import pickle # or use the faster cPickle module. output = open('somefile', 'wb') # Pickle object list pickle.dump(objList, output) output.close() But as this is only textual data (I think) there is not much profit in using pickle. Unless you have other things added in your class. You could also write these things to a simple text file, for example with the csv module. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing subservient threads
In article mailman.372.1235151060.11746.python-l...@python.org, Christian Heimes li...@cheimes.de wrote: Gabriel Genellina wrote: 1) make the child window set a flag in the thread (let's say, t.terminate = True). And make the polling thread check the flag periodically (you possibly already have a loop there - just break the loop when you detect that self.terminate became true) threading.Condition() and threading.Event() are especially designed for the job. Please use them appropriately. Personally, I prefer to just use Queue for everything. See http://pythoncraft.com/OSCON2001/index.html for examples, including one with Tkinter. Side note: because of the Subject: line, I have to mention a website for those who haven't seen it (requires Flash enabled): http://www.subservientchicken.com/ -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
question on msvcrt.dll versioning
It appears from sites like http://www.develer.com/oss/GccWinBinaries at the bottom that at least this developer made an effort to link against the same version of msvcrt.dll that the python exe was compiled with [ex: vc2008 - msvcr90.dll]. Is this pain necessary? Are there known drawbacks to not doing this anyone can think of? [just trying to plan releases for windows ruby shtuffs with similar problems]. Thanks! -=roger -- http://mail.python.org/mailman/listinfo/python-list
Re: pymssql text type
[posted and e-mailed, please reply to group] In article 851ed9db-2561-48ad-b54c-95f96a7fa...@q9g2000yqc.googlegroups.com, marc wyburn marc.wyb...@googlemail.com wrote: Hi, I'm trying to pass a text blob to MS SQL Express 2008 but get the follwoing error. (class 'pymssql.OperationalError', OperationalError(SQL Server message 102, severity 15, state 1, line 1:\nIncorrect syntax near 'assigned'.\n,), traceback object at 0x044ABDF0) the string it is having an issue with is (\r\n\r\n\tLogon ID:\t\t(0x0,0xE892A8)\r\n\r\n\tLogon Type:\t2\r\n\r \n') What is the code you're trying to execute and what is the full traceback? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: import not working?
In article mailman.605.1235434737.11746.python-l...@python.org, Rhodri James rho...@wildebst.demon.co.uk wrote: Just so that we're clear, this is a *really* *bad* habit to get into. Not appending to sys.path, though that isn't often a good idea, but failing to escape your backslashes. This works because '\D' happens not to be a valid escape sequence: if your directory had instead been called newtypes then C:\newtypes would not have had the result you were expecting at all. If you really mean a backslash to be in any literal string, you should always double it: sys.path.append(C:\\DataFileTypes) My preference: sys.path.append(rC:\DataFileTypes) This doesn't work if you need to add a trailing backslash, though. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: how to assert that method accepts specific types
In article 3f26a2f1-94cf-4083-9bda-7076959ad...@k19g2000yqg.googlegroups.com, Darren Dale dsdal...@gmail.com wrote: class Test(object): @accepts(int) def check(self, obj): print obj t = Test() t.check(1) but now I want Test.check to accept an instance of Test as well. Does anyone know how this can be accomplished? The following class definition for Test raises a NameError: class Test(object): @accepts(int, Test) def check(self, obj): print obj Are you using Python 2.6 or later? You could probably write a tricky class decorator that re-wraps all wrapped methods -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: Input data from .txt file and object array problem
On Mar 12, 11:17 pm, Piet van Oostrum p...@cs.uu.nl wrote: SamuelXiao foolsmart2...@gmail.com (S) wrote: S I want to input data by using pickle S First of all, I have a database.txt S The content is like: S AAA,aaalink S BBB,bbblink S CCC,ccclink S ...,... S AAA,BBB,CCC is Language name, and aaalink,bbblink,ccclink is their S respective link. S I want to store data by using pickle. Meanwhile , I got a problem. S #I have created a class: S class Lang: S def __init__(self,lname=,tlink=,alink=): S self.lname = lname #lname is the Language S self.tlink = tlink #tlink is the tutorial link S self.alink = alink #alink is the a link to school Library finding S the first returned Language book S def alibrary_link(self,alink): S self.alink = alink S def tutorial_link(self,tlink): S self.tlink = tlink S def lang_name(self,lname): S self.lname = lname S def _display(self): S string = +++ + \ S + + lname \ S + + tlink \ S + + alink \ S + This will not do very much. The string is calculated and then thrown away. You will need also a return string to make it useful. S def Print(self): S print self._display() S def originData(): S fo = (/database.txt,r+) S lines = fo.readlines() S for line in lines: S pair = line.split(,) S temp = Lang(); S temp.lname = pair[0] S temp.tlink = pair[1] S temp.alink = findbook(temp.lname) Why do you set these attributes directly while you also have methods for this (like lang_name, tutorial_link)? Or better use temp = Lang(pair[0], pair[1], findbook(temp.lname)) S #stopping here, because I don't know how to do here... S #I want to use object array here... S #Then using pickle to dump the object... S # Is this work? Or there is another better method to do so? S I hope to create an object array to store all the language and its S information from database.txt. I guess you want to put them in a list. Then use objList.append(temp) here and objList = [] before the loop. S How can I do that? I am a beginner to Python. Any help would be S appreciated. You can use pickle to store the list is a file after reading. Something like (untested): import pickle # or use the faster cPickle module. output = open('somefile', 'wb') # Pickle object list pickle.dump(objList, output) output.close() But as this is only textual data (I think) there is not much profit in using pickle. Unless you have other things added in your class. You could also write these things to a simple text file, for example with the csv module. -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org Hi, odeits, Piet van Oostrum, thanks for your reply. But I found that my school's server have problem with reading csv file. So, I think I have to do it another way. By the way, is there any better way to store data? Actually, what I want to do is like: 1. Given a post or an essay, I want to find any language names in the post or essay matching with data in my database.txt 2. Then insert a href=tutoriallink title=school library book title/a about the matched word. My original version is super slow because each time go to and back from the library website wastes a lot of times. I hope to use class to store the data in database.txt first, then store the book information from library. Then visited matched word no need to go to search again. Just simply insert a.../a about it. But my problem is how to store object array and call it out? Thanks for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Mar 12, 7:51 am, prueba...@latinmail.com wrote: On Mar 12, 3:30 am, Raymond Hettinger pyt...@rcn.com wrote: If anyone here is interested, here is a proposal I posted on the python-ideas list. The idea is to make numbering formatting a little easier with the new format() builtin in Py2.6 and Py3.0: http://docs.python.org/library/string.html#formatspec - Motivation: Provide a simple, non-locale aware way to format a number with a thousands separator. Adding thousands separators is one of the simplest ways to improve the professional appearance and readability of output exposed to end users. In the finance world, output with commas is the norm. Finance users and non-professional programmers find the locale approach to be frustrating, arcane and non-obvious. It is not the goal to replace locale or to accommodate every possible convention. The goal is to make a common task easier for many users. Research so far: Scanning the web, I've found that thousands separators are usually one of COMMA, PERIOD, SPACE, or UNDERSCORE. The COMMA is used when a PERIOD is the decimal separator. James Knight observed that Indian/Pakistani numbering systems group by hundreds. Ben Finney noted that Chinese group by ten-thousands. Visual Basic and its brethren (like MS Excel) use a completely different style and have ultra-flexible custom format specifiers like: _($* #,##0_). Proposal I (from Nick Coghlan]: A comma will be added to the format() specifier mini-language: [[fill]align][sign][#][0][minimumwidth][,][.precision][type] The ',' option indicates that commas should be included in the output as a thousands separator. As with locales which do not use a period as the decimal point, locales which use a different convention for digit separation will need to use the locale module to obtain appropriate formatting. The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example: format(n, 6,f).replace(,, _) This technique is completely general but it is awkward in the one case where the commas and periods need to be swapped. format(n, 6,f).replace(,, X).replace(., ,).replace (X, .) Proposal II (to meet Antoine Pitrou's request): Make both the thousands separator and decimal separator user specifiable but not locale aware. For simplicity, limit the choices to a comma, period, space, or underscore.. [[fill]align][sign][#][0][minimumwidth][T[tsep]][dsep precision] [type] Examples: format(1234, 8.1f) -- ' 1234.0' format(1234, 8,1f) -- ' 1234,0' format(1234, 8T.,1f) -- ' 1.234,0' format(1234, 8T .f) -- ' 1 234,0' format(1234, 8d) -- ' 1234' format(1234, 8T,d) -- ' 1,234' This proposal meets mosts needs (except for people wanting grouping for hundreds or ten-thousands), but it comes at the expense of being a little more complicated to learn and remember. Also, it makes it more challenging to write custom __format__ methods that follow the format specification mini-language. For the locale module, just the T is necessary in a formatting string since the tool already has procedures for figuring out the actual separators from the local context. Comments and suggestions are welcome but I draw the line at supporting Mayan numbering conventions ;-) Raymond As far as I am concerned the most simple version plus a way to swap around commas and period is all that is needed. Thanks for the feedback. FWIW, posted a cleaned-up version of the proposal at http://www.python.org/dev/peps/pep-0378/ Raymond -- http://mail.python.org/mailman/listinfo/python-list
Python/Django forum-building software Snap/SCT, any reviews?
I'm looking for good open-source software for forums. There is a *lot* out there, for instance Lussumo's Vanilla gets good reviews, but most are PHP-based, and I would obviously prefer to use Python, with or without Django. Two packages that are Django-based that I have found, are Snap and SCT. They both look pretty good (and Snap was influenced by Vanilla). Does anyone have any experience with these packages, and comments about them? Thanks John C For all your days, prepare, and meet them ever alike; When you are the anvil, bear - when the hammer, strike. Posted with NewzToolz. Free RAR, PAR, and yEnc decoders. Get your free copy at www.techsono.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger pyt...@rcn.com writes: FWIW, posted a cleaned-up version of the proposal at http://www.python.org/dev/peps/pep-0378/ It would be nice if the PEP included a comparison between the proposed scheme and how it is done in other programs and languages. For example, I think Common Lisp has a feature for formatting thousands. Spreadsheets like Excel probably have something similar. Those programs are pretty well evolved and probably address the important real use cases by now. It might be best to follow an existing example (with adjustments for Pythonification as necessary) to the extent possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: python contextmanagers and ruby blocks
In article c6b9e335-a04d-44cb-b18e-18a52eef1...@k19g2000yqg.googlegroups.com, Alia K alia_kho...@yahoo.com wrote: Aahz wrote: Longer answer: the way in Python to achieve the full power of Ruby blocks is to write a function. You are most likely right... there is probably no need to introduce ruby-like blocks to python where iteration comes naturally with list comprehensions and generators. But for the simple case of entering a block of code as one does with @contextmanager I suppose it would be nice to make a generator with a single yield statement a contextmanager by default such that [...] There has been some discussion of this on the python-ideas mailing list; if this is a subject you care about, you may want to read up on the history and join the list. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
PyCon Update
As of today, we still have rooms at the Hyatt. If you haven't registered yet and want to attend, it is not sold out. http://us.pycon.org/2009/ Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
[Paul Rubin] It would be nice if the PEP included a comparison between the proposed scheme and how it is done in other programs and languages. Good idea. I'm hoping that people will post those here. In my quick research, it looks like many languages offer nothing more than the usual C style % formatting and defer the rest for a local aware module. For example, I think Common Lisp has a feature for formatting thousands. Do you have more detail? Spreadsheets like Excel probably have something similar. I addressed that in the PEP in the section on VB and relatives. Their approach doesn't graft-on to our existing approach. They use format specifiers like: _($* #,##0_). Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Invalid syntax with print Hello World
On Thursday 12 March 2009 07:45:55 am Dotan Cohen wrote: I do not think that is the best way to go about learning Python. Why learn an arguably depreciating version when the new version is available. Because it is not only the language that matters, you also need the libraries to accomplish real-world tasks. As a language, python2 is an impressive one, and python3 is a great improvement over python2, but python3 still lacks some of the libraries and framewoks that makes programming in python so extremely delightful (yes, I like python :D). I don't consider python2 deprecated (can't be deprecated yet!), and as a teacher and/or student, I'd recomment to teach/learn python2.5-2.6, keeping an eye on all those features that are new in python3... and backporting everything that is possible to backport. I agree that there are not many tutorial written for Python 3 however there are enough to get going: most of the Python 2 tutorials are redundant. Sticking to Python 3 tutorials will give him a higher signal-to-noise ratio in the tutorials that he finds. That is true. We need python tutorials aimed at python2.6 :D -- Luis Zarrabeitia (aka Kyrie) Fac. de Matemática y Computación, UH. http://profesores.matcom.uh.cu/~kyrie -- http://mail.python.org/mailman/listinfo/python-list
Re: ipython / vs \ in readline on MS Windows (and ipython help grepper)
On Mar 10, 3:34 pm, bdb112 boyd.blackw...@gmail.com wrote: Q1/ I run a standard python ditribution with ipython and readline under cygwin. The tab filename completion works fine in the OS (bash shell) as expected, and tab filename completion at the ipython command line works, but with MS style path separators (backslash: run examples \test.py) which the run command itself interprets unix style ERROR: File `examplestest.py` not found. Also Q2/ can I less or grep the output from help(my_fun) Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] IPython 0.8.4 -- An enhanced Interactive Python. Cygwin does not magically change the platform you are on, the fact that you are on Windows is hard-coded into the Python.exe binary. Look for references to os.path.sep in IPython. Windows does let you use forward slashes as path separators, though, so I am not entirely sure what your issue is. -- http://mail.python.org/mailman/listinfo/python-list
Re: Candidate for a new itertool
On Mar 7, 8:47 pm, Raymond Hettinger pyt...@rcn.com wrote: The existing groupby() itertool works great when every element in a group has the same key, but it is not so handy when groups are determined by boundary conditions. For edge-triggered events, we need to convert a boundary-event predicate to groupby-style key function. The code below encapsulates that process in a new itertool called split_on(). Would love you guys to experiment with it for a bit and confirm that you find it useful. Suggestions are welcome. Raymond - from itertools import groupby def split_on(iterable, event, start=True): 'Split iterable on event boundaries (either start events or stop events).' # split_on('X1X23X456X', 'X'.__eq__, True) -- X1 X23 X456 X # split_on('X1X23X456X', 'X'.__eq__, False) -- X 1X 23X 456X def transition_counter(x, start=start, cnt=[0]): before = cnt[0] if event(x): cnt[0] += 1 after = cnt[0] return after if start else before return (g for k, g in groupby(iterable, transition_counter)) if __name__ == '__main__': for start in True, False: for g in split_on('X1X23X456X', 'X'.__eq__, start): print list(g) print from pprint import pprint boundary = '--===2615450625767277916==\n' email = open('email.txt') for mime_section in split_on(email, boundary.__eq__): pprint(list(mime_section, 1, None)) print '= = ' * 30 For me your examples don't justify why you would need such a general algorithm. A split function that works on iterables instead of just strings seems straightforward, so maybe we should have that and another one function with examples of problems where a plain split does not work. Something like this should work for the two examples you gave were the boundaries are a known constants (and therefore there is really no need to keep them. I can always add them later): def split_on(iterable, boundary): l=[] for el in iterable: if el!=boundary: l.append(el) else: yield l l=[] yield l def join_on(iterable, boundary): it=iter(iterable) firstel=it.next() for el in it: yield boundary for x in el: yield x if __name__ == '__main__': lst=[] for g in split_on('X1X23X456X', 'X'): print list(g) lst.append(g) print print list(join_on(lst,'X')) -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonWin, python thread and PostQuitMessage?
En Thu, 12 Mar 2009 07:21:35 -0200, arn...@sphaero.org escribió: I'm not so much involved in any Windows programming however I needed to write a client for the Windows platform. I have this very simple question which I've been unable to answer. I'm listening for keyboard strokes using the pyhook library. I'm doing this in a dedicated thread. The gui just controls the thread. When I want to pause listening for keyboard strokes I wanted to do a PostQuitMessage() to the thread. However this does not work since it either kills the whole app or just does not happen in the thread it's supposed to. I've now made an ugly workaround using PumpWaitingMessages and a delay. If you have a GUI, then very likely it has its own message loop, so you should not create another. def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() while self.log: win32gui.PumpWaitingMessages() time.sleep(0.02) i can now just cancel the process by setting self.log to False. I wanted to do just: def run(self): print Wkeylog run called # Hook Keyboard self.hm.HookKeyboard() win32gui.PumpMessages() Then, if you remove PumpMesages and PumpWaitingMessages, there is nothing left... so this thread is useless. Perhaps you want to *process* keyboard events in another thread - in this case, use a Queue object to send events to the worker thread, from the main thread where the message loop resides. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Byte type?
John Nagle wrote: Martin v. Löwis wrote: Please don't call something dumb that you don't fully understand ...- do you have to convert twice? Depends on how you write your code. If you use the bytearray type (which John didn't, despite his apparent believe that he did), then no conversion additional conversion is needed. According to PEP 3137, there should be no distinction between the two for read purposes. In 2.6, there is. That's a bug. If we something like the following for the bytes type in 2.7, perhaps we could improve the 2.X behavior (and make everyone happier). class bytes(str): def __getitem__(self, index): # keep exceptions the same result = super(bytes, self).__getitem__(index) if isinstance(index, int): # Picking out a single char return ord(result) # otherwise, it an extraction, return a similar type. return bytes(result) def __repr__(self): # make a nice visible-in-debugger type return 'b' + super(bytes, self).__repr__() At the very least, you can smuggle this into your programs to check out their behavior. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
[Paul Rubin] I think Common Lisp has a feature for formatting thousands. I found the Common Lisp spec for this and added it to the PEP. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: import not working?
Aahz wrote: In article mailman.605.1235434737.11746.python-l...@python.org, Rhodri James rho...@wildebst.demon.co.uk wrote: ... sys.path.append(C:\\DataFileTypes) My preference: sys.path.append(rC:\DataFileTypes) This doesn't work if you need to add a trailing backslash, though. Also my preference (except, due to aging eyes and bad fonts, I prefer single quotes unless doubles are needed). I solve the trailing backslash problem as so: sys.path.append(r'C:\DataFileTypes' '\\') --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.7 MSI / pywin32 snapshots [was: Windows install to custom location ...]
Tim Golden wrote: Scott David Daniels wrote: Tim Golden wrote: ... Anyhow, at the end I have a working Python 2.7a0 running under Windows. Do you mean 3.1a0? As far as I know, 2.7a0 requires the use of the time machine, as it is expected to be 3 months out. If you do get an installer built, even having a semi-official copy around for those of us not on the MS compiler upgrade train to do a little alpha (and/or beta) testing as well. I've uploaded a couple of installers here: http://timgolden.me.uk/python/downloads/snapshots/ Currently, there's the Python Subversion trunk (py2.7) and the corresponding pywin32, built from the latest CVS. I believe I've got everything in there, altho' the platform test was failing irreproducibly when I last looked. Thanks so much for these. Yes, they work (and I'm happily running little experiments). --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Raw String Question
I'm an experienced Perl developer learning Python, but I seem to be missing something about raw strings. Here's a transcript of a Python shell session: Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. IDLE 3.0 ra\b 'a\\b' ra\ SyntaxError: EOL while scanning string literal (pyshell#45, line 1) ra\ 'a\\ ' ra\ 'a\\' It seems the parser is interpreting the backslash as an escape character in a raw string if the backslash is the last character. Is this expected? -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ with dict values
En Thu, 12 Mar 2009 09:27:35 -0200, alex goretoy aleksandr.gore...@gmail.com escribió: note i would still like to be able to do __import__(sys).path p = __import__(sys).path That's a convoluted way of doing: import sys p = sys.path (except that the latter one inserts sys in the current namespace) maybe if __import__ had __str__ defined, How is my thinking on this? and how would I achieve something like this? __str__ has absolutely nothing to do. __import__(opt['imp_mod']).options eval(opt['imp_mod']+.+opt['imp_opt']) how to make top work like bottom? If you think you have to use eval: you don't. Never. module = __import__(opt['imp_mod']) module.options If the name options is not known until runtime, use getattr: getattr(module, name_of_attribute) The above assumes you want an attribute (like logging.ERROR). If you want a sub-module (a module inside a package) use __import__(dotted.name) and then retrieve the module by name from sys.modules; see http://docs.python.org/library/functions.html#__import__ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger pyt...@rcn.com writes: In my quick research, it looks like many languages offer nothing more than the usual C style % formatting and defer the rest for a local aware module. Hendrik van Rooyen's mention of Cobol's picture (aka PIC) specifications might be added to the list. Cautionary tale: I once had a similar idea and suggested including a bastardized version of PIC in an extension language for something I worked on once. Another programmer then coded a reasonable PIC subset and we shipped it. Turned out that a number of our users were Cobol experts and once we had anything like PIC, they expected the weirdest and most obscure features (of which there were quite a few) of real Cobol PIC to work. We ended up having to assign someone a fairly lengthy task of figuring out the Cobol spec and implementing every last damn PIC feature. But I digress. example, I think Common Lisp has a feature for formatting thousands. Do you have more detail? http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html gives as an example: (format nil The answer is ~:D. (expt 47 x)) = The answer is 229,345,007. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger pyt...@rcn.com writes: I found the Common Lisp spec for this and added it to the PEP. Ah, cool, I simultaneously looked for it and posted about it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw String Question
ra\ SyntaxError: EOL while scanning string literal (pyshell#45, line 1) It seems the parser is interpreting the backslash as an escape character in a raw string if the backslash is the last character. Is this expected? Yep...as documented[1], even a raw string cannot end in an odd number of backslashes. -tkc [1] http://docs.python.org/reference/lexical_analysis.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
Raymond Hettinger wrote: ... a generally interesting PEP... Missing from this PEP: output below the decimal point. show results for something like: format(12345.54321, 15,.5f) -- ' 12,345.543,21' Explain the interaction on sizes and lengths (which numbers are digits, which are length [I vote for length on overall, digits on precision]), and what happens with length-4 -- I'd say explicitly 1000 is show as 1,000 despite style sheets that prefer 1000 and 10,000. FWIW, I agree with pruebano, do the simplest easily usable thing, and provide a way to swap the commas and periods. The rest can be ponied in by string processing. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Building python 64-bit on OS 10.5?
In article 15e4667e0903121005v74d8e971ve57add393cf90...@mail.gmail.com, I've two questions: 1) I've been trying to building python as a 64-bit version on OS 10.5. I'm not too familiar with building python from scratch, and a number of basic attempts made from piecing together things I've seen on the web have failed. (For instance, ./configure --enable-framework --disable-toolbox-glue --with-universal-archs=all --with-gcc=gcc -m64 leads to a failure when I try to do make, as do all other similar variants I've tried.) So, is there a good source where I can find step-by-step 64-bit build instructions? (I'd like to do it if possible as a framework build.) I've looked it up a lot on google but am mostly getting fragments of descriptions of errors with other people's builds. It's hard to diagnose a problem with so little information. What version of python? What failure? In general, though, make sure you have a recent version of Apple's Developer Tools (aka Xcode) installed to get the Apple-supported gcc and friends. There are a number of ways to build either a 64-bit only or a universal build that supports 32- and 64-bit architectures. See, for example, Graham Dumpleton's instructions at the bottom of this page: http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX 2) I often use a number of python extensions like matplot, pylab, and ipython. Will these (especially the graphics parts) be able to build on top of my 64-bit installation? Is there some way to find out if they will likely work without actually having to build them? You may be able to find out more by checking forums specific to those products and/or the Mac python forum. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimilistic Python on Linux?
Thanks, much better. What exactly do I lose when I launch python without site.py? On Wed, Mar 11, 2009 at 10:27 PM, Gabriel Genellina gagsl-...@yahoo.com.arwrote: En Thu, 12 Mar 2009 00:41:18 -0200, Royce Wilson rww...@gmail.com escribió: On Wed, Mar 11, 2009 at 9:33 PM, Royce Wilson rww...@gmail.com wrote: Thanks for the quick responses. When I view sys.modules I get this: sre_compile _collections locale _sre functools encodings site operator io __main__ copyreg _weakref abc builtins encodings.cp437 errno sre_constants re encodings.latin_1 collections ntpath nt genericpath stat zipimport _codecs encodings.utf_8 encodings.cp1252 sys codecs _bytesio _thread os.path _functools _locale keyword signal _stringio _weakrefset encodings.aliases sre_parse os _abcoll _fileio Each module is seperated by a space. Can you give me in instructions on how to remove the site.py dependencies? Start python with the -S option -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: loop performance in global namespace (python-2.6.1)
Poor Yorick org.python.pythonl...@pooryorick.com wrote: In the following snippet, the loop in the global namespace takes twice as long as the loop in the function namespace. Why? Accessing global variables is generally slower than accessing local variables. Locals are effectively stored in a vector so the bytecode can go straight to the first local or the second local. Globals require a dictionary lookup. -- http://mail.python.org/mailman/listinfo/python-list
Re: loop performance in global namespace (python-2.6.1)
Poor Yorick wrote: In the following snippet, the loop in the global namespace takes twice as long as the loop in the function namespace. Why? Locals are known to have no outside interaction, and so are not looked up by name. your code could have a thread that did, global counter while True: time.sleep(.1) counter *= 2 For that matter, it could do ... del counter ... and force a NameError in your second loop. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: What happened to NASA at Python? :(
On Mar 12, 3:31 am, Michele Simionato michele.simion...@gmail.com wrote: That's pretty much impossible. I am sure NASA uses all programming languages in existence, plus probably many internal ones we never heard of. True but... all([NASA.does_endorse(lang) for lang in NASA['languages']]) False As the code suggests NASA doesn't sport an endorsement of X languages on every X language's webpage, which i feel is very important for Python's image, along with Google(Even more important!!), ILM, and others. I am really not worried if NASA *actually* uses Python or not(or to what extent), just as long as they say they do is good enough for me. *wink-wink* -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw String Question
Tim Chase wrote: ra\ SyntaxError: EOL while scanning string literal (pyshell#45, line 1) It seems the parser is interpreting the backslash as an escape character in a raw string if the backslash is the last character. Is this expected? Yep...as documented[1], even a raw string cannot end in an odd number of backslashes. -tkc [1] http://docs.python.org/reference/lexical_analysis.html OK, I'm curious as to the reasoning behind saying that When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. which sounds reasonable, but then saying in effect Oh wait, let's introduce a special case and make it impossible to have a literal backslash as the last character of a string without doubling it. So you have a construct (r'...') whose sole reason for existence is to ignore escapes, but it REQUIRES an escape mechanism for one specific case (which comes up frequently in Windows pathnames). I would suggest that this is pathologically inconsistent (now donning my flameproof underwear -) At the very least the all backslashes are left in the string quote from the Lexical Analysis page (rendered in italics no less) needs to be reworded to include the exception instead of burying this in a parenthetical side-comment. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw String Question
Jim Garrison jgarri...@troux.com wrote: ra\b 'a\\b' ra\ SyntaxError: EOL while scanning string literal (pyshell#45, line 1) ra\ 'a\\ ' ra\ 'a\\' It seems the parser is interpreting the backslash as an escape character in a raw string if the backslash is the last character. Is this expected? Yes http://docs.python.org/reference/lexical_analysis.html#string-literals Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). The usual way round this is like this ra \\ 'a\\' Which isn't terribly elegant, but it doesn't happen very often. -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
RE: Question on periods in strings
Thanks. I now know the cause of this, the suggestion to fling it in a few languages made it obvious. All of them were sharing the issue. Specifically that Trend MicroOffice Scan was the stalling factor, which was significantly boosting write times and if the write had any periods it would send it way off into the moon. So yeah, the antivirus program was the culprit. Python was interestingly less affected than C# which saw a 15 times slowdown from the same effect. Anyhow, sorry for bothering the list on what is clearly not a python problem, but thanks as well for helping lead me to the bottom of this mystery. -Original Message- From: python-list-bounces+pbloom=crystald@python.org [mailto:python-list-bounces+pbloom=crystald@python.org] On Behalf Of Gabriel Genellina Sent: Thursday, March 12, 2009 12:42 AM To: python-list@python.org Subject: Re: Question on periods in strings En Wed, 11 Mar 2009 23:42:45 -0200, Philip Bloom pbl...@crystald.com escribió: Thanks for the welcome :) You're right. Here's with the missed line (I was cutting out commented parts). Hopefully these are all cut/paste-able. #test A #runs in 5.8 seconds. from datetime import datetime testvar2='9a00' startTime = datetime.now() filehandle=open('testwriting.txt','w') for var in range(1000): filehandle.write(testvar2) filehandle.close() print (datetime.now() - startTime) #test B [using '9.00' -- otherwise identical] I do use the same filename, but I've run the tests in different orders and it's made no difference. Repeatedly running the same test results in the same numbers with only minor fluctuations (as would be expected from cache issues). Ten runs in a row of Test B all result in about 11 seconds each. Ten runs in a row of Test A all result in about 6 seconds each. I could not reproduce this. You've got better hardware than mine, certainly (I had to remove a 0 to get reasonable times) but I got almost identical results with both versions. I've tested also with 3.0 (and I had to take another 0 off!) with the same results. I have no idea why you see a difference. Unless the antivirus is interfering, or you have some crazy driver monitoring disk activity and the dot triggers something... Try using a different language - I'd say this is totally unrelated to Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list __ This email has been scanned by the MessageLabs Email Security System. For more information please visit http://www.messagelabs.com/email __ __ This email has been scanned by the MessageLabs Email Security System. For more information please visit http://www.messagelabs.com/email __ -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform accessing paths (windows, linux ...)
On Thu, Mar 12, 2009 at 8:10 AM, Vlastimil Brom vlastimil.b...@gmail.com wrote: Hi all, I'd like to ask for some advice on how to acomplish file access in a cross platform way. ... Any hints or comments are much appreciated; thanks in advance! regards, Vlasta 2009/3/12 Mike Mazurek mike.mazu...@gmail.com: You might want to look at the path module: http://pypi.python.org/pypi/path.py/2.2 It will probably make your code more readable. Hi Mike, thank you for the tip, I didn't know that module. Actually I was trying to reduce the external dependencies (python and wxpython only sofar); I'll look into it to see the improvement. I guess, the need for such module actually seems to confirm, that the path manipulation can be tricky in some cases ... Thanks again Vlasta -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw String Question
Jim Garrison jgarri...@troux.com wrote: OK, I'm curious as to the reasoning behind saying that When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. which sounds reasonable, but then saying in effect Oh wait, let's introduce a special case and make it impossible to have a literal backslash as the last character of a string without doubling it. So you have a construct (r'...') whose sole reason for existence is to ignore escapes, but it REQUIRES an escape mechanism for one specific case (which comes up frequently in Windows pathnames). You have a construct whose primary intent is to make it easier to write regular expressions without doubling all the backslashes. Regular expressions are quite likely to contain both single and double quote marks, so you need some way to include both kinds of quote marks. Regular expressions also cannot end with a single backslash. If you need Windows pathnames then you can almost always just write them using forward slashes (and use os.path.normpath() on them if you really need backslashes). There are many other strings which cannot be easily represented as a raw string: they are a convenience but not a replacement for ordinary string literals. -- http://mail.python.org/mailman/listinfo/python-list
Re: Raw String Question
Tim Chase wrote: ra\ SyntaxError: EOL while scanning string literal (pyshell#45, line 1) It seems the parser is interpreting the backslash as an escape character in a raw string if the backslash is the last character. Is this expected? Yep...as documented[1], even a raw string cannot end in an odd number of backslashes. So how do you explain this? r'a\'b' a\\'b The backslash is kept, but it causes the following quote to be escaped. -- http://mail.python.org/mailman/listinfo/python-list
Getting final url when original url redirects
I'm processing RSS content from a # of given sources. Most of the time the url given by the RSS feed redirects to the real URL (I'm guessing they do this for tracking purposes) For example. This is a url that I get from and RSS feed, http://www.pheedcontent.com/click.phdo?i=d22e9bc7641aab8a0566526f61806512 It redirects to http://www.macsimumnews.com/index.php/archive/klipsch_developing_headphones_for_new_ipod_shuffle/ I want to record the final URL and not the URL I get from the RSS feed (However sometimes there is no redirect so I might want the original URL) I've tried sniffing the header and don't see any Location:... I think sites are using different ways to redirect. Does anyone have any suggestions on how I might handle this? -- http://mail.python.org/mailman/listinfo/python-list