Re: Module/package hierarchy and its separation from file structure
On Jan 23, 4:49 am, Peter Schuller [EMAIL PROTECTED] wrote: I do *not* want to simply break out X into org.lib.animal.x, and have org.lib.animal import org.lib.animal.x.X as X. While this naively solves the problem of being able to refer to X as org.lib.animal.X, the solution is anything but consistent because the *identity* of X is still org.lib.animal.x.X. Examples of way this breaks things: * X().__class__.__name__ gives unexpected results. * Automatically generated documentation will document using the real package name. * Moving the *actual* classes around by way of this aliasing would break things like pickled data structure as a result of the change of actual identity, unless one *always* pre-emptively maintains this shadow hierarchy (which is a problem in and of itself). You can reassign the class's module: from org.lib.animal.monkey import Monkey Monkey.__module__ = 'org.lib.animal' (Which, I must admit, is not a bad idea in some cases.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
Bjoern Schliessmann [EMAIL PROTECTED] wrote: Grant Edwards wrote: Trying to find assembly language stuff to look at is futile. Python doesn't get compiled into assembly language. So, how do processors execute Python scripts? :) Is that a rhetorical question? Grant is quite correct; Python scripts (in the canonical CPython) are NOT compiled into assembly language. Scripts are compiled to an intermediate language. Processors execute Python scripts when the interpreter, written in a high-level language and compiled to assembly, interprets the intermediate language created by the Python compiler. -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: sudoku solver in Python ...
Derek Marshall [EMAIL PROTECTED] wrote: This is just for fun, in case someone would be interested and because I haven't had the pleasure of posting anything here in many years ... http://derek.marshall.googlepages.com/pythonsudokusolver Appreciate any feedback anyone who takes the time to have a look would want to give ... In my view, the canonical Python sudoku solver is located here: http://www.ics.uci.edu/~eppstein/PADS/Sudoku.py This is from David Eppstein, a professor of Computer Science at the University of California at Irvine. More than just solving the puzzles, his script actually prints out the individual steps that lead to the solution, one by one, in readable English. I've used it several times just to get a hint at the next step in a solution. It can also create new puzzles. His website contains a large collection of interesting public domain Python scripts for numerical analysis and linear programming problems and puzzles. http://www.ics.uci.edu/~eppstein/ -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
En Thu, 24 Jan 2008 05:16:51 -0200, Peter Schuller [EMAIL PROTECTED] escribió: I do *not* want to simply break out X into org.lib.animal.x, and have org.lib.animal import org.lib.animal.x.X as X. While this naively solves the problem of being able to refer to X as org.lib.animal.X, the solution is anything but consistent because the *identity* of X is still org.lib.animal.x.X. The term identity in Python means something separate from this concept; you seem to mean the name of X. Not necessarily. In part it is the name, in that __name__ will be different. But to the extent that calling code can potentially import them under differents names, it's identity. Because importing the same module under two names results in two distinct modules (two distinct module objects) that have no realation with each other. So for example, if a module has a single global protected by a mutex, there are suddenly two copies of that. In short: identity matters. That's not true. It doesn't matter if you Import a module several times at different places and with different names, it's always the same module object. py from xml.etree import ElementTree py import xml.etree.ElementTree as ET2 py import xml.etree py ET3 = getattr(xml.etree, 'ElementTree') py ElementTree is ET2 True py ET2 is ET3 True Ok, there is one exception: the main script is loaded as __main__, but if you import it using its own file name, you get a duplicate module. You could confuse Python adding a package root to sys.path and doing imports from inside that package and from the outside with different names, but... just don't do that! I realize that technically Python does not have this either. Like I said in the original post, I do realize that I can override __import__ with any arbitrary function, and/or do magic in __init__. But I also did not want to resort to hacks, and would prefer that there be some kind of well-established solution to the problem. I don't really understand what your problem is exactly, but I think you don't require any __import__ magic or arcane hacks. Perhaps the __path__ package attribute may be useful to you. You can add arbitrary directories to this list, which are searched for submodules of the package. This way you can (partially) decouple the file structure from the logical package structure. But I don't think it's a good thing... in Java, you would have the class org.lib.animal.Monkey in wherever/org/lib/animal/Monkey.java and org.lib.animal.Tiger in wherever/org/lib/animal/Tiger.java In other words, introducing a separate file does not introduce a new package. This works well as long as you are fine with having everything related to a class in the same file. The problem is that with Python, everything is not a classes, and a file translates to a module, not a class. So you cannot have your source in different files without introducing as many packages as you introduce files. Isn't org.lib.animal a package, reflected as a directory on disk? That's the same both for Java and Python. Monkey.py and Tiger.py would be modules inside that directory, just like Monkey.java and Tiger.java. Aren't the same thing? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping whitespace
On Jan 24, 8:21 am, ryan k [EMAIL PROTECTED] wrote: On Jan 23, 6:30 pm, John Machin [EMAIL PROTECTED] wrote: On Jan 24, 9:50 am, ryan k [EMAIL PROTECTED] wrote: Steven D'Aprano, you are a prick. And your reasons for coming to that stridently expressed conclusion after reading a posting that was *not* addressed to you are .? Because his tone is extremely condescending and quite frankly annoying. From this post to others, his terse remarks scar this community and fade its atmosphere of friendliness. And your response was any better because...? -- http://mail.python.org/mailman/listinfo/python-list
ENMAC Mobile Phones, iPods EQ100 www.enmac.com.hk
www.enmac.com.hk GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens, Digital Quran. Enjoy these products with Islamic Features (Complete Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily Supplications, Universal Qibla Direction, Prayer Timing and much more) visit our website for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Some questions about decode/encode
On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: My second question is: is there any one who has tested very long mbcs decode? I tried to decode a long(20+MB) xml yesterday, which turns out to be very strange and cause SAX fail to parse the decoded string. That's because SAX wants bytes, not a decoded string. Don't decode it yourself. However, I use another text editor to convert the file to utf-8 and SAX will parse the content successfully. Because now you feed SAX with bytes instead of a unicode string. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
The Way to Paradise
We are all in quest of true happiness. In this world, the idea of true/perfect happiness is not feasible because this world is inevitably doomed to total annihilation. True happiness is found only in dwelling upon Paradise, and enjoying its blessings. However, none would enter Paradise except the purified (those who are void of sins, void of an atom of grudge or malignance). Since Paradise is created only for the purified/pious, those who have evil looks (looking lustfully at strange women, and vice versa), who envy others, treat their fellowmen badly, hate mankind, or backbite cannot enter Paradise. To conclude, none can enter Paradise unless totally purified (sin-free). Those who indulge in illegal talk (backbiting, using indecent language, etc.), or have sinful hearts are denied entry to Paradise. Allah (The sublime) said: And those who kept their duty to Lord (AL- Muttaquin) will be driven/led to Paradise in groups, and when they reach there, its gates will be opened (before their arrival for their reception) and its keepers will say: Salamun Alaikum (peace be upon you)! How blessed you are (being sin-free and having done well), enter here (Paradise) to abide therein eternally. Surat Az-Zumar/The Groups: 73. In another Surah, Allah says: Those whose lives the angels take while they are in a pious state (pure from all evil, and worshipping none but only Allah) will be addressed as such: Salamun Alaikum (peace be upon you) enter Paradise due to that which you used to do (during your mortal life/in the world). Surat An-Nahl/The Bees: 32. The above-mentioned verses set the condition that, in order to enter Paradise, we have to be sin-free and void of an atom of guilt! One may argue that since we are all sinners, it seems that none can enter Paradise! Well, it is true that only the pious can enter Paradise, but, Allah (The Glorified), with His vast mercy, established eleven means to help us be purified: 4 in this world, 3 in the grave, and another 4 on the Day of Resurrection. These eleven means of purification aim at enabling us to cross/walk on the straight path rather than to slip and fall. This path is stretched over Hell fire and it is finer than a hair and sharper than the edge of a razor/sword! Knowing the nature of the straight path, one may question how people would tread on that path! Well, some will cross/walk on it as fast as the blink of an eye, others will be as fast as the light, others will be as fast as the wind, others will crawl, and others will cling to the path, then the angels will lead and/or encourage them onwards (lest they should fall into Hell fire), while others will be snatched by the hooks (attached to the path) to ensure/hasten their fall into Fire. 4 Means/Standpoints of Purification in this World 1. Repentance: Repentance is not limited to asking for forgiveness or invoking Allah's mercy, rather, it is one of the greatest religious rituals to win Allah's love/satisfaction and a means to get closer to Him. Allah (The Sublime) says: Allah loves those who turn unto Him in repentance and loves those who purify themselves (by taking a bath and cleaning and washing thoroughly their private parts/bodies (in preparation for their prayers). Surat AL-Baqarah/The Cow: 222. Repentance removes sins, as Allah (The Sublime) says: And verily, I'm indeed forgiving to him who repents, believes in My Oneness, and associates none in worshipping with Me, did righteous good deeds, and then remained faithful to such belief and good deeds. Surat Ta-Ha: 82. Repentance changes evil deeds into good ones. Allah (The Glorified and The Exalted) said: Except those who repented, believed in monotheism, and did righteous deeds; for those, Allah will change their sins into good deeds, and Allah is Oft-Forgiving, Most Merciful . Surat AL-Furqan/The Criterion: 70. 2. Asking for Forgiveness: We (Moslems) should always ask Allah to forgive our sins (whether remembered or not). Allah's Messenger (PBUH), though being the most pious, endowed with the most knowledge of his Lord, and having had both his past and future guilt pardoned/forgiven (by Allah), he used to ask for Allah's forgiveness as many as a hundred times a day (an action that won't take more than a minute of your time). In this respect, the prophet (PBUH) says: I swear by Allah, I do ask for Allah's forgiveness more than 70 times a day. This Hadith is quoted by AL- Bokhari. Also, Bin Omar (the son of Omar)-may Allah be content with them all- said: we used to count for the messenger of Allah (in one session and before leaving his place) as many as 100 times saying: O Lord! Forgive me my sins and accept my repentance, you are the One Who accepts repentance, the Most Merciful. This Hadith is quoted by Abu Dawoud and AL-Turmuzi. 3. Good Deeds Remove Bad deeds: Change bad deeds with good ones because Abu Dhar Ibn Jundub and Abu abdulrahman Bin Muaz Bin Jabal (may Allah be content with them all) narrated that
The Way to Paradise
We are all in quest of true happiness. In this world, the idea of true/perfect happiness is not feasible because this world is inevitably doomed to total annihilation. True happiness is found only in dwelling upon Paradise, and enjoying its blessings. However, none would enter Paradise except the purified (those who are void of sins, void of an atom of grudge or malignance). Since Paradise is created only for the purified/pious, those who have evil looks (looking lustfully at strange women, and vice versa), who envy others, treat their fellowmen badly, hate mankind, or backbite cannot enter Paradise. To conclude, none can enter Paradise unless totally purified (sin-free). Those who indulge in illegal talk (backbiting, using indecent language, etc.), or have sinful hearts are denied entry to Paradise. Allah (The sublime) said: And those who kept their duty to Lord (AL- Muttaquin) will be driven/led to Paradise in groups, and when they reach there, its gates will be opened (before their arrival for their reception) and its keepers will say: Salamun Alaikum (peace be upon you)! How blessed you are (being sin-free and having done well), enter here (Paradise) to abide therein eternally. Surat Az-Zumar/The Groups: 73. In another Surah, Allah says: Those whose lives the angels take while they are in a pious state (pure from all evil, and worshipping none but only Allah) will be addressed as such: Salamun Alaikum (peace be upon you) enter Paradise due to that which you used to do (during your mortal life/in the world). Surat An-Nahl/The Bees: 32. The above-mentioned verses set the condition that, in order to enter Paradise, we have to be sin-free and void of an atom of guilt! One may argue that since we are all sinners, it seems that none can enter Paradise! Well, it is true that only the pious can enter Paradise, but, Allah (The Glorified), with His vast mercy, established eleven means to help us be purified: 4 in this world, 3 in the grave, and another 4 on the Day of Resurrection. These eleven means of purification aim at enabling us to cross/walk on the straight path rather than to slip and fall. This path is stretched over Hell fire and it is finer than a hair and sharper than the edge of a razor/sword! Knowing the nature of the straight path, one may question how people would tread on that path! Well, some will cross/walk on it as fast as the blink of an eye, others will be as fast as the light, others will be as fast as the wind, others will crawl, and others will cling to the path, then the angels will lead and/or encourage them onwards (lest they should fall into Hell fire), while others will be snatched by the hooks (attached to the path) to ensure/hasten their fall into Fire. 4 Means/Standpoints of Purification in this World 1. Repentance: Repentance is not limited to asking for forgiveness or invoking Allah's mercy, rather, it is one of the greatest religious rituals to win Allah's love/satisfaction and a means to get closer to Him. Allah (The Sublime) says: Allah loves those who turn unto Him in repentance and loves those who purify themselves (by taking a bath and cleaning and washing thoroughly their private parts/bodies (in preparation for their prayers). Surat AL-Baqarah/The Cow: 222. Repentance removes sins, as Allah (The Sublime) says: And verily, I'm indeed forgiving to him who repents, believes in My Oneness, and associates none in worshipping with Me, did righteous good deeds, and then remained faithful to such belief and good deeds. Surat Ta-Ha: 82. Repentance changes evil deeds into good ones. Allah (The Glorified and The Exalted) said: Except those who repented, believed in monotheism, and did righteous deeds; for those, Allah will change their sins into good deeds, and Allah is Oft-Forgiving, Most Merciful . Surat AL-Furqan/The Criterion: 70. 2. Asking for Forgiveness: We (Moslems) should always ask Allah to forgive our sins (whether remembered or not). Allah's Messenger (PBUH), though being the most pious, endowed with the most knowledge of his Lord, and having had both his past and future guilt pardoned/forgiven (by Allah), he used to ask for Allah's forgiveness as many as a hundred times a day (an action that won't take more than a minute of your time). In this respect, the prophet (PBUH) says: I swear by Allah, I do ask for Allah's forgiveness more than 70 times a day. This Hadith is quoted by AL- Bokhari. Also, Bin Omar (the son of Omar)-may Allah be content with them all- said: we used to count for the messenger of Allah (in one session and before leaving his place) as many as 100 times saying: O Lord! Forgive me my sins and accept my repentance, you are the One Who accepts repentance, the Most Merciful. This Hadith is quoted by Abu Dawoud and AL-Turmuzi. 3. Good Deeds Remove Bad deeds: Change bad deeds with good ones because Abu Dhar Ibn Jundub and Abu abdulrahman Bin Muaz Bin Jabal (may Allah be content with them all) narrated that
Re: A GUI framework for running simulations
Martin Manns [EMAIL PROTECTED] wrote: If you want to keep things simple, pygame could be an alternative for visualizing simulations and setting parameters even though it does not provide all these fancy widgets around. I'd second that. pygame will give you a window you can draw on which you can plot the result of your simulation. You can draw a few buttons (like play and stop) and detect clicks in them very easily. If you want loads of parameters then you'll either need to reach for a GUI toolkit or roll your own menuing system for pygame (which isn't that hard). -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Increment Variable Name
Grant Edwards schrieb: On 2008-01-23, Diez B. Roggisch [EMAIL PROTECTED] wrote: David Brochu schrieb: This is probably really trivial but I'm stumped :-( Does anyone know how to increment a variable name? For example: I know the length of a list and I want to pass each element of a list to a unique variable, thus I want to increment variable names. If the list length = 4, i want to have the following variables: var1, var2, var3, var4. Use a dictionary value_dict = {} for i, value in values: value_dict[var%i % i] = value That assumes that the OPs list is actually a list of tumples: Tumples? :) I forgot the enumerate... Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Lxml on mac
On Jan 23, 5:08 pm, Stefan Behnel [EMAIL PROTECTED] wrote: But do anybody know if there is an easy way to use schema validation in python(on a mac) ? You mean: easier than the above? Likely not many... Well thanks for the reply's. I found GenerateDS make by Dave Kuhlman. I will try to give that a go. -- http://mail.python.org/mailman/listinfo/python-list
Re: Some questions about decode/encode
On Jan 24, 2:49 pm, glacier [EMAIL PROTECTED] wrote: I use chinese charactors as an example here. s1='你好吗' repr(s1) '\\xc4\\xe3\\xba\\xc3\\xc2\\xf0' b1=s1.decode('GBK') My first question is : what strategy does 'decode' use to tell the way to seperate the words. I mean since s1 is an multi-bytes-char string, how did it determine to seperate the string every 2bytes or 1byte? The usual strategy for encodings like GBK is: 1. If the current byte is less than 0x80, then it's a 1-byte character. 2. Current byte 0x81 to 0xFE inclusive: current byte and the next byte make up a two-byte character. 3. Current byte 0x80: undefined (or used e.g. in cp936 for the 1-byte euro character) 4: Current byte 0xFF: undefined Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: pairs from a list
:) I knew it was too simple to be true and appropriately slows down when corrected, dang. :) Matt. Internet [EMAIL PROTECTED] To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: pairs from a list 23/01/2008 18:32 Matthew_WARREN wrote: I'm just fiddling with this, am no great expert, but I added def pairs5(x): o=[] for n in zip(x[::2],x[1:2]): The second argument should be x[1::2]. o.append(n) return o I dont know if that breaks any constraints placed on the problem, but I It breaks the constraints unless the above is not cut-n-paste ;) Also note that your pairs5() offers no advantage over def pairs6(x): return zip(x[::2], x[1::2]) Peter -- http://mail.python.org/mailman/listinfo/python-list This message and any attachments (the message) is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. - Ce message et toutes les pieces jointes (ci-apres le message) sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython
[Tim Golden] wxPython is trying to interpret your byte stream as a Unicode text stream encoded as cp1252. But it's not, so it gives up in a heap. One solution is to pass the repr of file_content. Another solution is for you to prefilter the text, replacing non-printables by their hex value or by some marker. Not much in it, really. code import random file_content = .join ( chr (random.randint (0, 255)) for i in range (1000) ) munged_text = .join ( c if 32 = ord (c) = 126 else hex (ord (c)) for c in file_content ) print repr (file_content) print munged_text /code TJG [joe jacob] If I open an exe file in notepad, I can see some junk characters. I'm trying to develop a program like an editor which can encrypt a file opened by it. I need to open files like exe or jpeg etc in the editor and after encryption the encrypted data should be displayed in the editor. I developed the editor but when I tried to open an windows exe file in it I am getting the above mentioned error as the characters contained in it are non unicode. Hi, Joe. I've copied this back to the list (and I encourage you to do the same when replying) since the more people see the issue, the more chances you've got of a useful answer! To try to address what you're saying here: notepad.exe makes some choice or other when confronted by the byte stream in a file which you open. I don't know what that choice is, or how it tries to cope with encoded unicode text, but whatever it does by the choice of its developers. The some junk characters are one of several possible representations of the not-ordinary-characters which your file contains. If you're writing your own editor or file display, you have to make similar choices, which includes understanding what possibilities are offered by the toolset you're employing -- in this case, wxPython. slight guesswork - I haven't checked the source The wxPython wx.TextCtrl expects to be fed with Unicode text. If you pass it a string instead, it tries to decode it according to the system's default encoding, here cp1252. If it can't, it doesn't display junk characters: it just gives an error. /slight guesswork If you want junk characters, then you'll either have to explicitly pass in the characters you want displayed or do the kind of thing I suggested above to indicate their hex value, or find another control (or an option of the wx.TextCtrl) which will attempt to do the work for you when displaying raw bytes. I'm afraid I'm not a wxPython expert so maybe someone else has suggestions. But the most important thing is that you understand what's happening here and why you can't just say I want it to do what Notepad does. TJG -- http://mail.python.org/mailman/listinfo/python-list
Navigating through python packages
Hello, I work with Zope and Plone, hence I deal with lots of eggs and python packages and modules. I'm always opening source files inside packages, closing them, opening again, searching through them... The main issue here is the level of directory nesting.. you need to write a lot (in emacs) or click too much (in Eclispe) to open python source file. Take the following dir structure for a particular package in my Plone buildout eggs/plone.app.portlets.portlets.1.0.5/plone/app/portlets/portlets/news ... this is insane! How do you guys deal with this issue so as to make life easier in this aspect? Thanks, Marcelo. -- http://mail.python.org/mailman/listinfo/python-list
Designing website
Hi All, I am planning to design a website using windows, apache, mysql, python. But I came to know that python cgi is very slow. I came across mod_python also but no good documentation are available for learning mod_python. Suggest me a good solution for this as I don't know other languages like PHP; I prefer python. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython
On Jan 24, 4:20 pm, Tim Golden [EMAIL PROTECTED] wrote: [Tim Golden] wxPython is trying to interpret your byte stream as a Unicode text stream encoded as cp1252. But it's not, so it gives up in a heap. One solution is to pass the repr of file_content. Another solution is for you to prefilter the text, replacing non-printables by their hex value or by some marker. Not much in it, really. code import random file_content = .join ( chr (random.randint (0, 255)) for i in range (1000) ) munged_text = .join ( c if 32 = ord (c) = 126 else hex (ord (c)) for c in file_content ) print repr (file_content) print munged_text /code TJG [joe jacob] If I open an exe file in notepad, I can see some junk characters. I'm trying to develop a program like an editor which can encrypt a file opened by it. I need to open files like exe or jpeg etc in the editor and after encryption the encrypted data should be displayed in the editor. I developed the editor but when I tried to open an windows exe file in it I am getting the above mentioned error as the characters contained in it are non unicode. Hi, Joe. I've copied this back to the list (and I encourage you to do the same when replying) since the more people see the issue, the more chances you've got of a useful answer! To try to address what you're saying here: notepad.exe makes some choice or other when confronted by the byte stream in a file which you open. I don't know what that choice is, or how it tries to cope with encoded unicode text, but whatever it does by the choice of its developers. The some junk characters are one of several possible representations of the not-ordinary-characters which your file contains. If you're writing your own editor or file display, you have to make similar choices, which includes understanding what possibilities are offered by the toolset you're employing -- in this case, wxPython. slight guesswork - I haven't checked the source The wxPython wx.TextCtrl expects to be fed with Unicode text. If you pass it a string instead, it tries to decode it according to the system's default encoding, here cp1252. If it can't, it doesn't display junk characters: it just gives an error. /slight guesswork If you want junk characters, then you'll either have to explicitly pass in the characters you want displayed or do the kind of thing I suggested above to indicate their hex value, or find another control (or an option of the wx.TextCtrl) which will attempt to do the work for you when displaying raw bytes. I'm afraid I'm not a wxPython expert so maybe someone else has suggestions. But the most important thing is that you understand what's happening here and why you can't just say I want it to do what Notepad does. TJG Thanks for the information. I'll try to manage it some how. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython
[... snip stuff from TJG ...] joe jacob wrote: Thanks for the information. I'll try to manage it some how. If you haven't already, try posting to a wxPython or wxWidgets mailing list; maybe someone's already done this kind of thing? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing website
I am planning to design a website using windows, apache, mysql, python. You don't mention what sort of website...low-volume or high-volume, basic text or graphic-intensive, simple design or complex web-application logic. Each of these factors into one's choice. But I came to know that python cgi is very slow. I came across mod_python also but no good documentation are available for learning mod_python. Suggest me a good solution for this as I don't know other languages like PHP; I prefer python. If you're coming from CGI development and planning a small app, I'll give a plug for the WebStack[1] framework which basically reduces just about every option out there (CGI, mod_python, built-in BaseHTTPServer, and several othes) to a common API. However, I'd also recommend looking into one of the more powerful frameworks that abstracts away the server interface a bit more. I'm personally a Django[2] guy, but for some folks CherryPy[3], Pylons[4], TurboGears[5] or Zope[6] fills the bill. They do the grunt work of interfacing with your web-server (whether through mod_python, FastCGI or WSGI, or possibly other options such as a Twisted[7] internal server) as well as make a lot of other web-development aspects easier through separation of concerns. In most, business logic is kept separate from presentation logic which are both kept separate from the data layer. This allows developers to focus on a particular aspect at a time. There are also deployment issues. If you have your own server, it's not a big deal. However, if you're looking for cheap low-end shared hosting, the resources made available on such a machine are usually a bit constrained for these more powerful schemes. Sadly, this does make PHP look inviting for deployment on low-end hosting services despite its warty language. HTH, -tkc [1] http://www.boddie.org.uk/python/WebStack.html [2] http://www.djangoproject.com [3] http://www.cherrypy.org [4] http://pylonshq.com [5] http://turbogears.org [6] http://zope.org [7] http://twistedmatrix.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Increment Variable Name
On Jan 23, 11:45 pm, David Brochu [EMAIL PROTECTED] wrote: This is probably really trivial but I'm stumped :-( Does anyone know how to increment a variable name? For example: I know the length of a list and I want to pass each element of a list to a unique variable, thus I want to increment variable names. If the list length = 4, i want to have the following variables: var1, var2, var3, var4. Thanks Do you want to do this?: locals() {'__builtins__': module '__builtin__' (built-in), '__name__': '__main__', 'pywin': module 'pywin' from 'C:\Python25\Lib\site- packages\pythonwin\pywin\__init__.pyc', '__doc__': None} locals()['var'+str(1)] = spam locals() {'__builtins__': module '__builtin__' (built-in), '__name__': '__main__', 'var1': 'spam', 'pywin': module 'pywin' from 'C: \Python25\Lib\site-packages\pythonwin\pywin\__init__.pyc', '__doc__': None} var1 'spam' -- http://mail.python.org/mailman/listinfo/python-list
Re: Terminology: script versus program
Ben Finney wrote: George Sakkis [EMAIL PROTECTED] writes: On Jan 23, 8:14 pm, [EMAIL PROTECTED] wrote: The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101 ... 18. What is your favorite programming language? (15 choices, Python not included) 19. What is your favorite scripting language? o Python o Perl (5 more choices) Python is much more than a scripting language (whatever this means, other than a semi-derogatory term used by clueless PHBs). Sorry, I'll pass. I agree entirely. The term script has the strong connotation of a limited-purpose program designed to solve a problem expressed almost entirely as a simple series of steps. Languages that are often used to write such scripts are usually referred to as scripting languages, which becomes a denigration because such a language need not have support for much else. I strongly disagree with your interpretation. Scritping languages provide high-level facilites for process control. Historically, they were purely interpretive but now they tend to compile to some sort of byte code. Examples include the various shells, Rexx, and various languages whose names start with P. Languages which only express a series of steps are generally called batch languages. I've never heard anyone refer to a .BAT file as a script. In scripting languages, speed of execution is often less important than speed of implementation. When speed of execution is important, it is easier to invoke an external module than to patch or rewrite the interpreter. In Python, PERL and BASH, these modules can be dynamically linked libraries as well as stand-alone executables. Finally, the provided process control facilities are often generalized into quite powerful support for programming in the large, especially both object-oriented and functional programming. This leads to supprot for a much broader set of practices and solutions than any mere programming language can easily provide. The only drawback I've ever found to this is that it's easy to accidentally use huge amounts of memory, for instance by 'slurping' files into memory in a single command. This term seems quite prevalent among the Python core developers, unfortunately. The 'distutils' module even has the term 'script' used in its interface, to refer to the programs that are to be distributed. Apparently the core developers agree with my interpretation, not yours. -- http://mail.python.org/mailman/listinfo/python-list
Re: Increment Variable Name
On Jan 24, 12:02 pm, janislaw [EMAIL PROTECTED] wrote: On Jan 23, 11:45 pm, David Brochu [EMAIL PROTECTED] wrote: This is probably really trivial but I'm stumped :-( Does anyone know how to increment a variable name? For example: I know the length of a list and I want to pass each element of a list to a unique variable, thus I want to increment variable names. If the list length = 4, i want to have the following variables: var1, var2, var3, var4. Thanks Do you want to do this?: locals()['var'+str(1)] = spam As I recently learnt in this newsgroup, that's not guaranteed to work. From http://docs.python.org/lib/built-in-funcs.html Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Test driven development
Hi Sorry if this is a bit off topic but as unit testing is such a cornerstone of python development I thought a few of you may be able to share your knowledge/experiences. I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? Thanks Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: sudoku solver in Python ...
Shawn Milochik wrote: On Jan 23, 2008, at 10:02 PM, Derek Marshall wrote: This is just for fun, in case someone would be interested and because I haven't had the pleasure of posting anything here in many years ... http://derek.marshall.googlepages.com/pythonsudokusolver Appreciate any feedback anyone who takes the time to have a look would want to give ... Yours with-too-much-time-to-kill-on-the-train'ly, Derek -- http://mail.python.org/mailman/listinfo/python-list For those interested in this topic, here's another (much shorter) one: http://norvig.com/sudoku.html I'm not making any judgements here, though. If anyone takes the time to actually review them, I'd be interested in hearing any educated comparisons. Shawn So would I. Below is the winner of my hacking for an as fast as possible 110% pure python (no imports at all!) comprehensive sudoku solver under 50 LOCs, back in 2006. Performance is comparable to the solver you advertize - numbers are slightly better, but platform differences could easily absorb that - eg (not counting module initialization and not using psyco) it takes 9.3 ms average on the AI escargot problem linked to in Norwig's page, 5.6 ms/problem on some standard top1465 list of hard problems, and 3.4 ms/problem on the first 1000 on some other top5 list of relatively hard problems. This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about 50%. Dropping performance requirements by half allows reducing LOC count in proportion. OTOH, the code although short is nearly unreadable, sorry; should probably feature/comment it on some web page, like the two already proposed in the thread. Will do if/for reviewer. Interface is calling sudoku99(problem) with 'problem' a standard 81 character string with '0' or '.' placeholder for unknowns. Returns same with values filled in. Beware that although in practice it solved all well-formed human-solvable problems I could find, it is not guaranteed to deal properly (or even terminate?) for underdetermined problems or determined problems that would require exploring choicepoints with more than 2 possibilities (if such exist). Cheers, Boris w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81] for n in range(729)] q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s)) q2w = map(set,zip(*9*[q2w])) w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in enumerate(w2q)] empty = set(range(729)).copy def sudoku99(problem) : givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0'k) ws=search(givens,[9]*len(q2w),empty()) return ''.join(str(w%9+1) for w in sorted(ws)) def search(w0s,q2nw,free) : while 1 : while w0s: w0 = w0s.pop() for q in w2q[w0] : q2nw[q]=100 wz = w2q2w[w0]free free-=wz for w in wz : for q in w2q[w] : n = q2nw[q] = q2nw[q]-1 if n2 : ww,=q2w[q]free w0s.add(ww) if len(free)==81 : return free thres = int((len(free)+52.85)/27.5) ix,vmax = -1,0 try : while 1 : ix=q2nw.index(2,ix+1) for w0 in (q2w[ix]free)-w0s : v = len(w2q2w[w0]free) if v vmax : ixmax = ix if v =thres : break vmax = v w0s.add(w0) else : continue break except : pass w0,w1 = q2w[ixmax]free try : w0s.clear() w0s.add(w0) return search(w0s,q2nw[:],free.copy()) except ValueError : w0s.clear() w0s.add(w1) -- http://mail.python.org/mailman/listinfo/python-list
Re: When is min(a, b) != min(b, a)?
On 2008-01-21, Steven D'Aprano [EMAIL PROTECTED] wrote: On Sun, 20 Jan 2008 21:15:02 -0600, Albert Hopkins wrote: According to the IEEE-754 standard the usual trichotomy of x is less than y, x is equal to y, or x is greater than y has to be extended to include x and y are unordered. Comparisons with NaNs are unordered, and so expressions like x nan should signal an exception. That doesn't follow. The problem is not that x nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
On 1/24/08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi Sorry if this is a bit off topic but as unit testing is such a cornerstone of python development I thought a few of you may be able to share your knowledge/experiences. Test driven development, simplistically, means to write the tests before you write the code. I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. It should work with any unit of development, although it can be hard to usefully test high-level functionality that depends on currently unimplemented underware. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? The system I've adopted is to use inline doctests for the simplest, tutorial-like examples, with outline unit tests composd to verify implementation details and to probe bounderies. Typically, I write a doctest, then the routine, and finally the unit tests. Top-down should work fine with test-driven, although your highest level tests will fail until your low-level tests pass. All the failing tests might be kind of depressing, though. Personally, I haven't really given top-down a fair shake, so I don't know which approach reveals my stupid design mistakes faster. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/package hierarchy and its separation from file structure
Not necessarily. In part it is the name, in that __name__ will be different. But to the extent that calling code can potentially import them under differents names, it's identity. Because importing the same module under two names results in two distinct modules (two distinct module objects) that have no realation with each other. So for example, if a module has a single global protected by a mutex, there are suddenly two copies of that. In short: identity matters. That's not true. It doesn't matter if you Import a module several times at different places and with different names, it's always the same module object. Sorry, this is all my stupidity. I was being daft. When I said importing under different names, I meant exactly that. As in, applying hacks to import a module under a different name by doing it relative to a different root directory. This is however not what anyone is suggesting in this discussion. I got my wires crossed. I fully understand that import x.y.z or import x.y.z as B, and so one do not affect the identity of the module. Ok, there is one exception: the main script is loaded as __main__, but if you import it using its own file name, you get a duplicate module. You could confuse Python adding a package root to sys.path and doing imports from inside that package and from the outside with different names, but... just don't do that! Right :) I don't really understand what your problem is exactly, but I think you don't require any __import__ magic or arcane hacks. Perhaps the __path__ package attribute may be useful to you. You can add arbitrary directories to this list, which are searched for submodules of the package. This way you can (partially) decouple the file structure from the logical package structure. But I don't think it's a good thing... That sounds useful if I want to essentially put the contents of a directory somewhere else, without using a symlink. In this case my problem is more related to the file == module and directory == module semantics, since I want to break contents in a single module out into several files. Isn't org.lib.animal a package, reflected as a directory on disk? That's the same both for Java and Python. Monkey.py and Tiger.py would be modules inside that directory, just like Monkey.java and Tiger.java. Aren't the same thing? No, because in Java Monkey.java is a class. So we have class Monkey in package org.lib.animal. In Python we would have class Monkey in module org.lib.animal.monkey, which is redundant and does not reflect the intended hierarchy. I have to either live with this, or put Monkey in .../animal/__init__.py. Neither option is what I would want, ideally. Java does still suffer from the same problem since it forces class == file (well, public class == file). However it is less of a problem since you tend to want to keep a single class in a single file, while I have a lot more incentive to split up a module into different files (because you may have a lot of code hiding behind the public interface of a module). So essentially, Java and Python have the same problem, but certain aspects of Java happens to mitigate the effects of it. Languages like Ruby do not have the problem at all, because the relationship between files and modules is non-existent. -- / Peter Schuller PGP userID: 0xE9758B7D or 'Peter Schuller [EMAIL PROTECTED]' Key retrieval: Send an E-Mail to [EMAIL PROTECTED] E-Mail: [EMAIL PROTECTED] Web: http://www.scode.org -- http://mail.python.org/mailman/listinfo/python-list
Re: csv to xls using python 2.1.3
Unfortunately we have to stick with python 2.1.3 for this project. -- http://mail.python.org/mailman/listinfo/python-list
Re: csv to xls using python 2.1.3
On Jan 23, 5:15 pm, Larry Bates [EMAIL PROTECTED] wrote: FYI - Excel can read .CSV files directly and convert them to .XLS. -Larry Thanks Larry The customer wants 2 buttons - one for csv, one for xls. Kind regards Liz -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython
On Jan 24, 5:37 am, Tim Golden [EMAIL PROTECTED] wrote: [... snip stuff from TJG ...] joe jacob wrote: Thanks for the information. I'll try to manage it some how. If you haven't already, try posting to a wxPython or wxWidgets mailing list; maybe someone's already done this kind of thing? TJG I'm not able to think of anything offhand that's in wxPython, but I seem to recall someone trying to display a language even if the language wasn't installed on the PC. The OP might find the internationalization techniques useful for this application. Here's some wiki entries on that topic: http://wiki.wxpython.org/RecipesI18n http://wiki.wxpython.org/Internationalization The newest version of wxPython comes with Editra, which is a fairly advanced text editor written with wxPython. It won't open exes or pictures, but most files that are in plain text it opens with no problem. Editra has its own site: http://editra.org/ The mailing list for wxPython can be found here: http://wxpython.org/maillist.php Mike -- http://mail.python.org/mailman/listinfo/python-list
Which reportlab version for python 2.1.3?
Hiya Probably me being thick but I can't find which version of reportlab I should use for python 2.1.3. Many thanks Liz -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
On 2008-01-24, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. It is not bottom-up imho. The main difference imho is in abstract, far-away goals versus running code for a small concrete sub-set of functionality in the short-term. How you provide that running code for a small concrete sub-set of functionality in the short-term is not defined by the approach. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if 1. Define a small step of extended functionality that you can finish by the end of the week. 2. Write tests that should run after implementing the functionality. 3. Write code that make the tests work. 4. goto 1. anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? No, with TTD there is only one goal, namely increasing the percentage of passed tests to 100%. (which you then break again by doing steps 1 and 2, and fix again in step 3) TTD is about DESIGNing for WHAT YOU NEED TODAY, not for what you might need tomorrow. You may want to do a small top-down design (and next week another slightly larger one, and another slightly larger one in 2 weeks, etc), but you should NOT DESIGN FOR MORE FUNCTIONALITY THAN WHAT YOU NEED for all tests to pass. Sincerely, Albert PS The above is purely from a TTD perspective. I personally do not really think you can SOLVE ALL PROBLEMS in the most efficient way using TTD. On the other hand, the concrete, short-term approach does produce running code fast for the implemented sub-set of functionality, which may be nice in a project. -- http://mail.python.org/mailman/listinfo/python-list
Re: When is min(a, b) != min(b, a)?
Antoon Pardon wrote: That doesn't follow. The problem is not that x nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. Please report the problem. cmp(), min() and max() don't treat NaNs right. I don't think that x nan == False is the correct answer, too. But I've to check the IEEE 754 specs. IMHO nan and nan should raise an exception. Christian -- http://mail.python.org/mailman/listinfo/python-list
piping into a python script
Hi, (Gnu/Linux - Python 2.4/5) Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? 2. import fileinput for line in fileinput.input(): print (line) But this opens each file and I don't want that. I have seen a lot of search results that don't quite answer this angle of the question, so I'm trying on the list. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? I've been a big fan of TDD for a few years. I don't always use it. When working with legacy code, sometimes the pain of getting things into a test harness exceeds the effort I'm able or willing to put into it right now. The other times I don't use it is when I'm just doing some simple little thing (which inevitably grows into something bigger than originally anticipated). In all cases, I often find that code I ended up writing is less well documented, less well tested, and more buggy. You've hit the nail on the head with the top-down, bottom-up issue. TDD (at least in my mind) encourages bottom-up design, because it forces you to have working code on day one. This is not always good. So, the key (as you pointed out) to mixing TDD with top-down, is to use mock objects a lot. But, this is a good thing; it forces you to write classes which can be tested in isolation. This no only makes for better tested code, but often leads to cleaner design. Now, to drag this thread back to something apropos to Python, the good news is that Python makes it easy to work with mock objects. Often, all you need to do is import myTestingFoo as Foo and it all just works. Since functions and classes are first-class objects, it's easy to pass them around. Since Python uses duck typing, you don't have to make sure your test class inherets from anything in particular. It all just works. -- http://mail.python.org/mailman/listinfo/python-list
Re: When is min(a, b) != min(b, a)?
On Jan 24, 2:28 pm, Christian Heimes [EMAIL PROTECTED] wrote: Antoon Pardon wrote: That doesn't follow. The problem is not that x nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. Please report the problem. cmp(), min() and max() don't treat NaNs right. I don't think that x nan == False is the correct answer, too. But I've to check the IEEE 754 specs. IMHO nan and nan should raise an exception. Christian To a floating point interested layman such as I, treating not-a-number comparisons with floats should give the same result as comparing a fileobject (also not-a-number), with a float. Or does nan have /need a more domain specific interpretation? - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
Tim Roberts wrote: Bjoern Schliessmann [EMAIL PROTECTED] So, how do processors execute Python scripts? :) Is that a rhetorical question? A little bit. Grant is quite correct; Python scripts (in the canonical CPython) are NOT compiled into assembly language. Scripts are compiled to an intermediate language. Processors execute Python scripts when the interpreter, written in a high-level language and compiled to assembly, interprets the intermediate language created by the Python compiler. So in the end, the program defined in the Python script _is_ compiled to the CPU's language. But never mind, it depends on how you define compile in the end. Regards, Björn -- BOFH excuse #225: It's those computer people in X {city of world}. They keep stuffing things up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
On Jan 24, 7:37 am, [EMAIL PROTECTED] wrote: Hi Sorry if this is a bit off topic but as unit testing is such a cornerstone of python development I thought a few of you may be able to share your knowledge/experiences. I like the concept of TDD but find it difficult to put into practice most of the time. I think this primarily because I tend to like top- down development and functional/object decomposition and TDD feels more like a bottom-up approach. So my question is when approaching a project that you want to employ test driven development on how and where do you start? And also if anyone uses top-down design with TDD I would be interested in how you do it (does it involve lots of mock objects/ is the first test you write the last one to pass)? Thanks Andy I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the bottom-up approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) Roy: While mocking is good to have tests well organized (instead of having a huge pile of tests at the highest level), over- mocking (mocking everything, early) leads to, I think, a design that is too rigid. What if a new spec reveals that the current design of a large subset of your classes has to be re-done? All your mocking and the test below them, they all have to be brought up to the highest level of tests so you can re-organize your code. Since doing this is a lot of work, and usually messing with tests is a lot more dangerous than messing with the code itself, you would tend to stay with your old design, even if it's not the optimal design for the task you need to do. Virgil -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? Usually Linux tools that can get the data from command line or files treat a single - as file name special with the meaning of: read from stdin. So the interface if `fui.py` would be: 1. ./fui.py *.a 2. ls *.a | ./fui.py - 3. ls *.a | ./fui.py *.b - Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
On Jan 24, 3:17 pm, Donn Ingle [EMAIL PROTECTED] wrote: Hi, (Gnu/Linux - Python 2.4/5) Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? 2. import fileinput for line in fileinput.input(): print (line) But this opens each file and I don't want that. I have seen a lot of search results that don't quite answer this angle of the question, so I'm trying on the list. \d Try the fileinput module. What you describe above is pretty close to the unix 'standard' but not quite. if we substitute the lp command instead of ./fui, the command normally takes a list of files to act on as its arguments, and anything piped in goes to its stdin where it is processed if it has an argument of - fileinput works that way but you may have problems with your: ls *.jpg | ./fui.py *.png Which might better be expressed as: ./fui.py `ls *.jpg` *.png which would work for ls and a python program using the fileinput module. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: get the size of a dynamically changing file fast ?
Gabriel Genellina wrote: En Wed, 23 Jan 2008 16:16:58 -0200, Stef Mientki [EMAIL PROTECTED] escribió: Yes, that's a small disadavantage of using a high-level language, where there's no flush available, and you assume it'll done automatically ;-) Uhm, there is a flush method for Python's files. From http:// I was talking about a high-level language, in which the sending program was written, (Delphi, not about Python ;-) In Delphi, flush(filevar) does work. flush is only valid for textfiles, not for binary files (at least in D7) anyway thanks, cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
RE: Stripping whitespace
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of John Machin Sent: Wednesday, January 23, 2008 5:48 PM To: python-list@python.org Subject: Re: Stripping whitespace On Jan 24, 7:57 am, Reedick, Andrew [EMAIL PROTECTED] wrote: Why is it that so many Python people are regex adverse? Use the dashed line as a regex. Convert the dashes to dots. Wrap the dots in parentheses. Convert the whitespace chars to '\s'. Presto! Simpler, cleaner code. pattern = re.sub(r'-', r'.', line) pattern = re.sub(r'\s', r'\\s', pattern) pattern = re.sub(r'([.]+)', r'(\1)', pattern) Consider this: pattern = ' '.join('(.{%d})' % len(x) for x in line.split()) Good. But the main drawback to using split+join is that it works if there is only one whitespace char acting as a column separator (split+join will compress multiple whitespace characters down to one char.) Normally, it's safe to assume a one character separator between columns, however since the input is supposed to be tab delimited (but wasn't) and tabs tend to get randomly converted to spaces depending on which butterfly is flapping its wings at any given instant, keeping the original whitespace column separators is probably a good idea. * The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622 -- http://mail.python.org/mailman/listinfo/python-list
Connecting to Sql Server from Python
Hi, I have an sql server from which I'd like to read and write to. The connection string is as follows - Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated Security=True;Pooling=False Other properties as they appear in Visual Studio 2005 include - Data Provider: .NET Framework Data Provider for SQL Server State: Open Type: Microsoft SQL Server So my question is, how might I connect to my Test Catalog and update data within its tables via perl, Thanks, Barry. -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
On Jan 24, 3:25 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Thu, 24 Jan 2008 17:17:25 +0200, Donn Ingle wrote: Given these two examples: 1. ./fui.py *.py 2. ls *.py | ./fui.py How can I capture a list of the arguments? I need to get all the strings (file or dir names) passed via the normal command line and any that may come from a pipe. There is a third case: 3. ls *.jpg | ./fui.py *.png Where I would be gathering strings from two places. I am trying to write a command-line friendly tool that can be used in traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally. I have tried: 1. pipedIn = sys.stdin.readlines() Works fine for example 2, but example 1 goes into a 'wait for input' mode and that's no good. Is there a way to tell when no input is coming from a pipe at all? Usually Linux tools that can get the data from command line or files treat a single - as file name special with the meaning of: read from stdin. So the interface if `fui.py` would be: 1. ./fui.py *.a 2. ls *.a | ./fui.py - 3. ls *.a | ./fui.py *.b - Ciao, Marc 'BlackJack' Rintsch If X.a X.b Y.a Y.b are all files whose contents are to be processed then To process all files: ./fui.py *.a *.b Or: ./fui.py `ls *.a *.b` To process one file from a pipe unix usually does: cat X.a | ./fui.py - To get the filenames from stdin would usually need a command line switch telling fui.py to read a file *list* from stdin. For verilog simulators for example you have the -f switch that says insert further command line arguments from the file name in the next argument, so you could do: ls *.a | ./fui.py -f - *.b For equivalent functionality to my first example. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: A global or module-level variable?
On Jan 23, 2:27 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Wed, 23 Jan 2008 11:58:05 -0200, Bret [EMAIL PROTECTED] escribió: On Jan 22, 1:00 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: If you have to do it that way, use: Is there a better way? A more Pythonic way? It's simple, clear and works fine, why make it more complicated? Unless you have additional requirements, like a multithreaded program. -- Gabriel Genellina Ultimately, it will be multithreaded -- and I had intended to wrap the access to the global member in a lock to ensure only one thread could get a value at any point. It might also become multiprocess (ugh!) and so might need to live in its own SocketServer some day. But for now, I agree. Simple is good. I just wanted to be sure I wasn't oversimplifying, you know? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Try the fileinput module. I did give the fileinput module a go, but I can't find much info on it and the help is ... well, it's python help ;) in goes to its stdin where it is processed if it has an argument of - fileinput works that way Okay, I did think of the dash, but did not know how to handle it. Is it a bash thing or will that dash get passed into the args? (I am using getopt to parse the options and args) which would work for ls and a python program using the fileinput module. Any examples of fileinput (that do not open each file) would be great! (I'll go searching now anyway) Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Paddy wrote: ls *.a | ./fui.py -f - *.b To be sure I grok this: I am seeing the single dash as a placeholder for where all the piped filenames will go, so *.b happens after *.a has been expanded and they all get fed to -f, right? I'm also guessing you mean that I should detect the single dash and then go look for stdin at that point. How do I detect a lack of stdin? Thanks, \d -- http://mail.python.org/mailman/listinfo/python-list
Re: finding memory leak in edgewall trac 0.11
On Jan 20, 2:59 pm, Christian Heimes [EMAIL PROTECTED] wrote: rupert.thurner wrote: i forgot to mention that i cannot see any explicit sys._getframe(), or __del__ in the genshi code, while the ones intrac-core seemed to be there in 0.10.4. Does the code keep a reference to a traceback object or an attribute of a traceback object? Christian if there is no other possibility but doing it with sys.exc_traceback, sys.last_traceback, sys.exc_info, the answer is no for genshi. -- http://mail.python.org/mailman/listinfo/python-list
Re: Some questions about decode/encode
On Jan 24, 1:44 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 23 Jan 2008 19:49:01 -0800, glacier wrote: My second question is: is there any one who has tested very long mbcs decode? I tried to decode a long(20+MB) xml yesterday, which turns out to be very strange and cause SAX fail to parse the decoded string. That's because SAX wants bytes, not a decoded string. Don't decode it yourself. encode() converts a unicode string to a regular string. decode() converts a regular string to a unicode string. So I think what Marc is saying is that SAX needs a regular string(i.e. bytes) not a decoded string(i.e. a unicode string). -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Sql Server from Python
On Jan 24, 9:44 am, [EMAIL PROTECTED] wrote: Hi, I have an sql server from which I'd like to read and write to. The connection string is as follows - Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated Security=True;Pooling=False Other properties as they appear in Visual Studio 2005 include - Data Provider: .NET Framework Data Provider for SQL Server State: Open Type: Microsoft SQL Server So my question is, how might I connect to my Test Catalog and update data within its tables via perl, Thanks, Barry. If you want to do this in Perl, then why are you asking on a Python list? In Python, there are many ways to accomplish this task. Take a look at SQLAlchemy, SQLObject, pymssql or the adodb package. http://pymssql.sourceforge.net/ www.sqlalchemy.org http://www.sqlobject.org/ http://phplens.com/lens/adodb/adodb-py-docs.htm Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Sql Server from Python
On 24 Jan, 17:16, Mike Driscoll [EMAIL PROTECTED] wrote: On Jan 24, 9:44 am, [EMAIL PROTECTED] wrote: Hi, I have an sql server from which I'd like to read and write to. The connection string is as follows - Data Source=localhost\SQLExpress;Initial Catalog=Test;Integrated Security=True;Pooling=False Other properties as they appear in Visual Studio 2005 include - Data Provider: .NET Framework Data Provider for SQL Server State: Open Type: Microsoft SQL Server So my question is, how might I connect to my Test Catalog and update data within its tables via perl, Thanks, Barry. If you want to do this in Perl, then why are you asking on a Python list? In Python, there are many ways to accomplish this task. Take a look at SQLAlchemy, SQLObject, pymssql or the adodb package. http://pymssql.sourceforge.net/www.sqlalchemy.orghttp://www.sqlobject.org/http://phplens.com/lens/adodb/adodb-py-docs.htm Mike- Dölj citerad text - - Visa citerad text - Woops, I ment Python... -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
On Jan 24, 4:02 pm, Donn Ingle [EMAIL PROTECTED] wrote: Try the fileinput module. I did give the fileinput module a go, but I can't find much info on it and the help is ... well, it's python help ;) Try http://effbot.org/librarybook/fileinput.htm in goes to its stdin where it is processed if it has an argument of - fileinput works that way Okay, I did think of the dash, but did not know how to handle it. Is it a bash thing or will that dash get passed into the args? (I am using getopt to parse the options and args) - gets passed in and fileinput handles it. which would work for ls and a python program using the fileinput module. Any examples of fileinput (that do not open each file) would be great! (I'll go searching now anyway) fileinput is set to process each file a line at a time unfortunately. Thanks, Your welcome :-) - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Beginner Pyserial Question
Hi Guys, I have a project where I'd like to save GPS data that is streamed to a Sony Vaio over bluetooth. I can monitor the data stream over Hyper Terminal, but I'd like to use python to capture it as well. I've installed Python 2.5, pyserial 2.2 and the appropriate pywin program (pywin32-210.win32-py2.5.exe). My problem comes when I try to open a serial port. After importing serial, I issue the following statement: GPS = serial.Serial(0) Traceback (most recent call last): File pyshell#3, line 1, in module GPS = serial.Serial(0) File C:\Python25\lib\site-packages\serial\serialutil.py, line 156, in __init__ self.open() File C:\Python25\lib\site-packages\serial\serialwin32.py, line 55, in open raise SerialException(could not open port: %s % msg) SerialException: could not open port: (2, 'CreateFile', 'The system cannot find the file specified.') I'm not sure where the source of the problem is. I was wondering if someone could recognize what might be be. the Vaio is running XP SP2. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Paddy wrote: fileinput is set to process each file a line at a time unfortunately. Wow. So there seems to be no solution to my OP. I'm amazed, I would have thought a simple list of strings, one from stdin and one from the args, would be easy to get. I *really* don't want to open each file, that would be insane. Perhaps I shall have to forgo the stdin stuff then, after all. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
wget -i - it doesn't do anything, just waits for your input. Your applications probably should behave the same. Okay, that works for me. Paddy wrote: ls *.a | ./fui.py -f - *.b It doesn't seem to me that -f parameter is necessary for your application. Yes and no, I have another option that needs to take a variable number of args. It should treat all the arguments as the filenames, shouldn't it? And when one of the filenames is -, just try to read stdin. I have tested getopt and it strips the lone '-' out. I can get it from sys.argv, but then I am really doing more parsing than I want to. It's a tricky job this. I think I will look in sys.argv, if I find a single dash the I will replace that element in the list with whatever comes from stdin. Then I'll pass all of it to getopt. Thanks for the help. \d -- When you allow legends to rule your life, your world is based on fiction -- Segio Aragones (Groo the Wanderer Number 99) Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: When is min(a, b) != min(b, a)?
Christian Heimes [EMAIL PROTECTED] writes: Antoon Pardon wrote: That doesn't follow. The problem is not that x nan returns False because that is correct since x isn't smaller than nan. The problem is cmp(x, nan) returning 1, because that indicates that x is greater than nan and that isn't true. Please report the problem. cmp(), min() and max() don't treat NaNs right. I don't think that x nan == False is the correct answer, too. But I've to check the IEEE 754 specs. IMHO nan and nan should raise an exception. I disagree with your last sentence. We are dealing with quiet NaNs which should not raise exceptions. x nan is well defined in IEEE, it is false. IMHO cmp() should raise an exception if one or more arguments is a NaN. Its current definition is to return an integer which may be negative, zero, or positive for less than, equal, or greater than. There is no spec for unordered, and the integer returned cannot be NaN. I'd be happy if min() and max() behaved as if their comparison operations were minNum and maxNum from IEEE. In other words they never return NaN unless all their arguments are NaN. int(nan) should raise an exception. I note that in Python 2.5.1 int(inf) already does. -- Pete Forman-./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent [EMAIL PROTECTED]-./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Pyserial Question
On 2008-01-24, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi Guys, I have a project where I'd like to save GPS data that is streamed to a Sony Vaio over bluetooth. I can monitor the data stream over Hyper Terminal, but I'd like to use python to capture it as well. I've installed Python 2.5, pyserial 2.2 and the appropriate pywin program (pywin32-210.win32-py2.5.exe). My problem comes when I try to open a serial port. After importing serial, I issue the following statement: GPS = serial.Serial(0) Traceback (most recent call last): File pyshell#3, line 1, in module GPS = serial.Serial(0) File C:\Python25\lib\site-packages\serial\serialutil.py, line 156, in __init__ self.open() File C:\Python25\lib\site-packages\serial\serialwin32.py, line 55, in open raise SerialException(could not open port: %s % msg) SerialException: could not open port: (2, 'CreateFile', 'The system cannot find the file specified.') I'm not sure where the source of the problem is. I was wondering if someone could recognize what might be be. It's Windows... it's not expected to work. ;) My guess is that for whatever reason the 'first' serial port (which is what you're asking for by specifying a 0 when instantiating the Serial class) doesn't actually exist. Serial device names under Windows are broken. Just because you have only one serial port, it doesn't mean that serial port is the first serial port. Try using the actual name of the com port (e.g. 'COM3' or 'COM5') instead of 0. Oh, if you end up having to use a com port higher than COM9, that's broken in Windows as well, and you've got to sprinkle a bunch of backslashes into the device name (I don't remember the exact syntax). -- Grant Edwards grante Yow! ... this must be what at it's like to be a COLLEGE visi.comGRADUATE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Pyserial Question
My guess is that for whatever reason the 'first' serial port (which is what you're asking for by specifying a 0 when instantiating the Serial class) doesn't actually exist. Serial device names under Windows are broken. I realize this. I tried connecting to different port numbers, but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. Try using the actual name of the com port (e.g. 'COM3' or 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. Oh, if you end up having to use a com port higher than COM9, that's broken in Windows as well, and you've got to sprinkle a bunch of backslashes into the device name (I don't remember the exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
On Jan 24, 10:14 am, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: Tim Roberts wrote: Grant is quite correct; Python scripts (in the canonical CPython) are NOT compiled into assembly language. Scripts are compiled to an intermediate language. Processors execute Python scripts when the interpreter, written in a high-level language and compiled to assembly, interprets the intermediate language created by the Python compiler. So in the end, the program defined in the Python script _is_ compiled to the CPU's language. I would say it's compiled to an intermediate language (bytecode), and then that intermediate language is interpreted. But never mind, it depends on how you define compile in the end. If you define compile as interpret, yeah. Calr Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
On Jan 24, 2008 9:14 AM, Bjoern Schliessmann [EMAIL PROTECTED] wrote: Tim Roberts wrote: Bjoern Schliessmann [EMAIL PROTECTED] So, how do processors execute Python scripts? :) Is that a rhetorical question? A little bit. Grant is quite correct; Python scripts (in the canonical CPython) are NOT compiled into assembly language. Scripts are compiled to an intermediate language. Processors execute Python scripts when the interpreter, written in a high-level language and compiled to assembly, interprets the intermediate language created by the Python compiler. So in the end, the program defined in the Python script _is_ compiled to the CPU's language. But never mind, it depends on how you define compile in the end. This is true if and only if you would agree that Powerpoint presentations, Word documents, and PNG images are likewise compiled to machine code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Pyserial Question
COM = 0 #for COM1 BAUD = 115200 class serial_port(): def __init__(self): self.start_time = None self.end_time = None self.asleep_duration = None self.device = serial.Serial() self.device.timeout = 1 self.device.baudrate = BAUD self.device.port = COM a_serial_port = serial_port() a_serial_port.device.open() - Original Message From: [EMAIL PROTECTED] [EMAIL PROTECTED] To: python-list@python.org Sent: Thursday, January 24, 2008 10:13:39 AM Subject: Re: Beginner Pyserial Question My guess is that for whatever reason the 'first' serial port (which is what you're asking for by specifying a 0 when instantiating the Serial class) doesn't actually exist. Serial device names under Windows are broken. I realize this. I tried connecting to different port numbers, but I have not tried the serial.Serial(COM1). I wasn't sure if that worked, but I know a quick way to find out. Try using the actual name of the com port (e.g. 'COM3' or 'COM5') instead of 0. The com port used in Hyper Terminal is COM40. I have tried connecting to 39/40/41 to no avail. Oh, if you end up having to use a com port higher than COM9, that's broken in Windows as well, and you've got to sprinkle a bunch of backslashes into the device name (I don't remember the exact syntax). That might become an issue when I try to read COM40 for the GPS bluetooth transmission. This issue does not relate to why I cannot open smaller com ports, though. -- http://mail.python.org/mailman/listinfo/python-list Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: translating Python to Assembler
Hallöchen! Carl Banks writes: On Jan 24, 10:14 am, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: [...] But never mind, it depends on how you define compile in the end. If you define compile as interpret, yeah. Well, it is just-in-time-compiled command by command. :o) Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Duplicating a variable
I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] x = y x[2] = 5 y [1,2,5] It seems that simply assigning x to y allows further modification of y via x. (I'm new to python and I'm sure this is obvious to experienced users). So my question, how do I go about duplicating a variable which I can then manipulate independently? Thanks, -Hans -- http://mail.python.org/mailman/listinfo/python-list
Re: Duplicating a variable
On Jan 24, 9:36 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] x = y x[2] = 5 y [1,2,5] It seems that simply assigning x to y allows further modification of y via x. (I'm new to python and I'm sure this is obvious to experienced users). So my question, how do I go about duplicating a variable which I can then manipulate independently? Thanks, -Hans Ah, found the copy module... Much better. Thanks, -Hans -- http://mail.python.org/mailman/listinfo/python-list
Re: Duplicating a variable
Have a look at the copy module if you have a somewhat complex object graph to duplicate. Remember, you're essentially just creating another reference to a singular list object with simple assignment (a = b). a = [1,2,3,4, ['5a', '5b', '5c', ['6a', '6b','6c']], 7,8] b = a a [1, 2, 3, 4, ['5a', '5b', '5c', ['6a', '6b', '6c']], 7, 8] a[4][1] = None a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] b [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] import copy d = copy.deepcopy(a) d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] a [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] a[4][1] = Something a [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] b [1, 2, 3, 4, ['5a', 'Something', '5c', ['6a', '6b', '6c']], 7, 8] d [1, 2, 3, 4, ['5a', None, '5c', ['6a', '6b', '6c']], 7, 8] Thanks, Jeff On 1/24/08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] x = y x[2] = 5 y [1,2,5] It seems that simply assigning x to y allows further modification of y via x. (I'm new to python and I'm sure this is obvious to experienced users). So my question, how do I go about duplicating a variable which I can then manipulate independently? Thanks, -Hans -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Pyserial Question
I've solved the problem- Thanks for steering me in the right direction. The problem is that your traditional COM1 does not exist on this computer (Thanks Grant). A trip to the Device manager listed all the COM ports on the computer. After successfully connecting to COM7 (port = serial.Serial(6)), I realized the reason I couldn't connect to COM40 was because it was tied up with hyper terminal. after closing everything, I was able to issue a readline and collect data. Thanks for the help! jimmy -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing website
joe jacob a écrit : Hi All, I am planning to design a website using windows, apache, mysql, python. But I came to know that python cgi is very slow. The problem here is not with Python, but with how cgi works - that is, by launching a new process for each request. Trying to write Java cgi would be even worse FWIW !-) I came across mod_python also but no good documentation are available for learning mod_python. Err... mod_python is actually well documented IMHO - but suppose you already have some good knowledge of web programming and Apache. Suggest me a good solution for this as I don't know other languages like PHP; I prefer python. If you're new to web programming and look for a good doc and a strong community, I'd suggest Django. If you're feeling a bit more lucky, you might have a look at Pylons. -- http://mail.python.org/mailman/listinfo/python-list
Re: Duplicating a variable
[EMAIL PROTECTED] a écrit : I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. using the deepcopy function of the copy module. I was surprised when simple assignment didn't work. For example, let y = [1,2,3] x = y x[2] = 5 y [1,2,5] Python only uses object references. It never copy anything unless explicitely asked for. -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Donn Ingle wrote: Paddy wrote: fileinput is set to process each file a line at a time unfortunately. Wow. So there seems to be no solution to my OP. I'm amazed, I would have thought a simple list of strings, one from stdin and one from the args, would be easy to get. I *really* don't want to open each file, that would be insane. Perhaps I shall have to forgo the stdin stuff then, after all. Hi! I'm not sure if I completely get what you want, but what's about this: #!/usr/bin/python import sys filelist = [] with_stdin=0 if len(sys.argv) 1: for file in sys.argv[1:]: if file == -: with_stdin=1 continue filelist.append(file) else: with_stdin=1 if with_stdin: for file in sys.stdin: filelist.append(file) for file in filelist: print Processing file: %s % file It's a bit clumsy, but seems to do what I guess you want. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Duplicating a variable
Hans: I have run into a bit of a subtle problem. How do I go about duplicating a variable (particularly a list of lists) in python. I was surprised when simple assignment didn't work. Python is quite high-level language, but now and then it too accepts some compromises to increase its speed/size performance. Probably after Python someone will invent a language that may be slower than Python because it's higher level than Python, and avoids that problem you talk about (and other things). (And with a strategy of smart data sharing and copy-on-write the interpreter can avoid part of that overhead). how do I go about duplicating a variable which I can then manipulate independently? If your variable contains a list, then you can copy it like this: l1 = [1, 2, 3] l2 = l1[:] l2[1] = 4 As you can see now they are two distinct lists: l1 [1, 2, 3] l2 [1, 4, 3] If you want to copy any kind of object you can use the copy function (instead of a simpler copy method that's absent): d1 = {1:2, 3:4} from copy import copy d2 = copy(d1) d1[1] = 5 d1 {1: 5, 3: 4} d2 {1: 2, 3: 4} But as you can see copy works only one level deep: d3 = {1:[1], 3:4} d3 {1: [1], 3: 4} d4 = copy(d3) d3[1][0] = 2 d3 {1: [2], 3: 4} d4 {1: [2], 3: 4} To copy all levels you need deepcopy: from copy import deepcopy d5 = deepcopy(d3) d3[1][0] = 5 d3 {1: [5], 3: 4} d4 {1: [5], 3: 4} d5 {1: [2], 3: 4} Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: [wxPython-users] Issue with docking wx.listctrl window
tarun wrote: Hello All, I'm trying to create a Frame with AuiManager. The code is attached. *Problem:* - I want 2 windows to be docked in the frame. One is a text control and other is a list control. - The text control gets docked, but on trying to dock the list control, all the tabs dis-appear. The tabs appear only when the list control window is kept floating. In the attached code the list control window is kept floating. This can be docked To see the issue with docking, comment line 33 and un-comment line 35 in the attached file and then try to execute, the issue would be clearly visible. On un-docking the window1, the tabs again appear.. *Please let me the solution to this ASAP* The main problem is that you are putting the listctrl on a panel, but you are telling AUI to manage the listctrl, not the panel. If I understand correctly then your other problems stem from that as well. Try passing self.log to AddPane, instead of self.log.list. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! -- http://mail.python.org/mailman/listinfo/python-list
RE: piping into a python script
-Original Message- From: [EMAIL PROTECTED] [mailto:python- [EMAIL PROTECTED] On Behalf Of Donn Sent: Thursday, January 24, 2008 12:03 PM To: Michał Bentkowski Cc: python-list@python.org Subject: Re: piping into a python script I have tested getopt and it strips the lone '-' out. I can get it from Try 'foo.py -- -'. The '--' normally tells the parser to stop parsing args. Ex: date -foo.txt; rm -foo.txt; rm -- -foo.txt I think this will tell you if stdin is being piped in or not: import sys import os print os.isatty(sys.stdin.fileno()) D:\type a.txt | python a.py False D:\python a.py True Also if you're lazy, look at the StringIO class: if options.filelist is None and len(args) 1: # read from stdin f = sys.stdin elif options.filelist is not None and len(args) 1: # read filenames from file f = open(options.filelist, 'r') elif options.filelist is None and len(args) 0: # filenames on command line f = StringIO.StringIO('\n'.join(args)) else: ## Thanks for playing. parser.print_help() exit(1) if f: for filename in f: -- Segio Aragones (Groo the Wanderer Number 99) Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought each other? -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonic backtrace with gdb
Hynek Hanke [EMAIL PROTECTED] writes on Wed, 23 Jan 2008 14:30:22 +0100: ... I've also tried to use the backtrace script here http://mashebali.com/?Python_GDB_macros:The_Macros:Backtrace But I get a different error: (gdb) pbt Invalid type combination in ordering comparison. I'm using GDB version 6.6.90. I expect that your GDB version is too new and has introduced some safety checks (which now break). It will probably help when you add explicite type casts to long around the comparisons in the definition of pbt. Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone explain this unexpected raw_input behavior?
On Jan 24, 2008 8:08 AM, Gabriel Genellina [EMAIL PROTECTED] wrote: En Thu, 24 Jan 2008 01:00:53 -0200, Mike Kent [EMAIL PROTECTED] escribió: Gabriel, thank you for clarifying the source of this behavior. Still, I'm surprised it would be hard-coded into Python. Consider an interactive program, that asks the user several questions, and displays paragraphs of information based on those questions. The paragraphs are output using print, and the questions are asked via raw_input. You want to do some simple debugging of the program by printing some debugging statements via 'print sys.stderr', and you don't want the debug output mixed in with the normal output on the screen, so you try to route the debugging output to a file by adding '2filename' to the end of the command line. Unfortunately, you will no longer see any of the questions being printed via raw_input. The rest of the output will be fine, but the questions disappear. Your program just stops, without asking anything... you have to guess what should be there. You have one console, two streams to output data (stdout and stderr), and three data sources (program output, user prompt, and debugging messages). Someone has to give. I'm now convinced that the current behavior is rather reasonable... If it weren't for the documentation... If the prompt argument is present, it is written to *standard output* without a trailing newline. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
Virgil Dupras schreef: I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the bottom-up approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) I don't regularly use TDD yet, and one of the reasons is that in many cases I'm unsure exactly how to use it in practice. I read Test-driven development - A practical guide (and I should re-read), but I feel it doesn't help my much in everyday situations. Somehow the examples in the book don't match very well with how I code (and I admit that perhaps the problem is more with me than with the book). One of the problems I have is something like what Andy describes: I need a function spam(), so I write tests for it. Then I start implementing the function and see that I need to write functions ham() and eggs(). Should I write unit tests for ham() and eggs(), or do I rely on the tests for spam()? If I don't write them, doesn't that make it more difficult to find out why the tests for spam() fail? Speaking about over-engineering, when I do TDD along the lines of the book I mentioned, I always feel that I'm over-engineering the tests. It all feels very unnatural though I'm convinced it shouldn't be like that. Can someone suggest other books to read about the subject, ideally something more focused on Python or C++ rather than Java? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Which reportlab version for python 2.1.3?
On Jan 24, 8:17 am, LizzyLiz [EMAIL PROTECTED] wrote: Hiya Probably me being thick but I can't find which version of reportlab I should use for python 2.1.3. Many thanks Liz Since ReportLab's website lists dlls for Python 2.1 - 2.5, I think you can just use the latest version. Just download it, unzip it somewhere convenient and then navigate to that location using the command line. Then type the following (as long as Python is in your system path): python setup.py install or if Python isn't on your path: path\to\python\python.exe setup.py install HTH Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: creating .pyo with make
Diez B. Roggisch wrote: Yann Leboulanger schrieb: Yann Leboulanger wrote: Hi, I use autoconf / automake to manage my python project, and I'l like make / make install to create / install .pyo files instead of .py files. Is there something I should add to my Makefile.am files to do that? Or should I do all that myself with py_compile module? Are there some examples somewhere with autotools? Thanks for your help Hehe replying to myself. It seems I just have to replace project_DATA = $(srcdir)/*.py by project_PYTHON = $(srcdir)/*.py Then when I do make install, it installs .py, .pyc and .pyo. Would it be possible to install only .pyo? Is it a good idea? There might be the occasional code that relies on doc-strings to work - seldomly, but possible. Which are obmitted by .pyo, but not of pyc. Apart from that, having only pyc-files (or pyo for that matter) sucks. Just today I had to delve into a ZOPE-application, setting breakpoints and getting things done. It would have been impossible or at least much more inconvenient to debug if I hadn't had the sources available (and put at a place where they actually get invoked from the interpreter, not lying around unrelated) Diez Source are available i ntarballs, but when I do make install I don't care to install .py files. .pyo are enough to run the application. -- Yann -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems getting Python scripts to run on server
On Jan 23, 11:30 pm, 7stud [EMAIL PROTECTED] wrote: I just wanted to point out that the Directory tag below would go in the httpd.conf file(a config file for apache), which you apparently do not have access to. I was suggesting that you check with your host to make sure they have the right AllowOverride line. 3) What you can put in .htaccess files is determined by the AllowOverride directive. e.g. Directory /Library/Apache2/cgi-bin AllowOverride FileInfo Options None Order allow,deny Allow from all /Directory Note: you must have AllowOverride Options in effect to permit the use of the Options directive in .htaccess files. So, in the above example the line starting with AllowOverride would need to have Options instead of FileInfo(or maybe in addition to?). More info fromhttp://httpd.apache.org/docs/2.0/howto/htaccess.html: --- Finally, you may wish to use a .htaccess file to permit the execution of CGI programs in a particular directory. This may be implemented with the following configuration: Options +ExecCGI AddHandler cgi-script cgi pl Alternately, if you wish to have all files in the given directory be considered to be CGI programs, this may be done with the following configuration: Options +ExecCGI SetHandler cgi-script Note that AllowOverride Options and AllowOverride FileInfo must both be in effect for these directives to have any effect. Please see the CGI tutorial for a more complete discussion of CGI programming and configuration. - According to that passage, you should have the extension 'py' not '.py' in the AddHandler part. I don't know if that makes a difference. Go to that web page and click the link to the CGI tutorial, and maybe you can find some clues on how to configure your directories with .htacesss files. -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
On Jan 24, 1:30 pm, Roel Schroeven [EMAIL PROTECTED] wrote: Virgil Dupras schreef: I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the bottom-up approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) I don't regularly use TDD yet, and one of the reasons is that in many cases I'm unsure exactly how to use it in practice. I read Test-driven development - A practical guide (and I should re-read), but I feel it doesn't help my much in everyday situations. Somehow the examples in the book don't match very well with how I code (and I admit that perhaps the problem is more with me than with the book). One of the problems I have is something like what Andy describes: I need a function spam(), so I write tests for it. Then I start implementing the function and see that I need to write functions ham() and eggs(). Should I write unit tests for ham() and eggs(), or do I rely on the tests for spam()? If I don't write them, doesn't that make it more difficult to find out why the tests for spam() fail? Speaking about over-engineering, when I do TDD along the lines of the book I mentioned, I always feel that I'm over-engineering the tests. It all feels very unnatural though I'm convinced it shouldn't be like that. Can someone suggest other books to read about the subject, ideally something more focused on Python or C++ rather than Java? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven I also have a book about TDD and it never was of much help either. All techniques come from the initial workflow: Red - Green - Refactor. The problem you describe is a tricky problem. The way I feel it should be solved is: - Write spam() (and its tests, of course). - Then, at some point, in the re-factor phase, you split extract the function ham() from spam(). Alright, do it and keep the tests as is (all on spam()). - Then at some other point, you extract eggs(). same thing. - After a while (I don't know, 3 or 4 milestones), when it becomes clear that ham() and eggs() are there to stay, start moving your tests away from spam() by just mocking ham() and eggs() and just make sure that spam() call them with the right arguments. The tests you had on spam() that were relevant to ham() and eggs() are just performed directly on them now. What I've been saying in my other message is: Don't do that too early, because if it turns out that ham() and eggs() is not the optimal way to do it, but foo() bar() and baz() is, it is *much* easier to do a safe re-factoring with high level tests. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Journal Survey
On Jan 23, 7:42 pm, George Sakkis [EMAIL PROTECTED] wrote: On Jan 23, 8:14 pm, [EMAIL PROTECTED] wrote: The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101 ... 18. What is your favorite programming language? (15 choices, Python not included) 19. What is your favorite scripting language? o Python o Perl (5 more choices) Python is much more than a scripting language (whatever this means, other than a semi-derogatory term used by clueless PHBs). Sorry, I'll pass. George Someone please correct me if I am wrong, but I think of a Python script as a flat source file with no (or few) functions or classes, whereas a full-blown program has functions and classes. Both have their place. I agree it is unfortunate that the Linux World poll classified Python as a scripting language. I suspect they did that because Python is not (typically) compiled and does not have static typing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Journal Survey
On 24 Jan, 04:42, George Sakkis [EMAIL PROTECTED] wrote: On Jan 23, 8:14 pm, [EMAIL PROTECTED] wrote: The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101 18. What is your favorite programming language? 19. What is your favorite scripting language? 20. What is your favourite colour? ;-) Python is much more than a scripting language (whatever this means, other than a semi-derogatory term used by clueless PHBs). Sorry, I'll pass. Well, LJ isn't my chosen reading material any more, but a write-in vote sends the appropriate message in this case. I anticipate the usual C/C++ is the favourite programming language on Linux routine when the results get published but, as I wrote, LJ passed the point of no subscription some time ago. Paul -- http://mail.python.org/mailman/listinfo/python-list
Sorting Large File (Code/Performance)
Hello all, I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. I'd greatly appreciate if someone can post sample code that can help me do this. Also, any ideas on approximately how long is the sort process going to take (XP, Dual Core 2.0GHz w/2GB RAM). Cheers, Ira -- http://mail.python.org/mailman/listinfo/python-list
Re: piping into a python script
Thanks for the tips, I'll decode and try 'em all out. Ah yes, Groo. Ever wonder who would win if Groo and Forrest Gump fought each other? Heh ;) I reckon they'd both die laughing. Be fun to watch -- if anyone else survived! \d -- A computer without Windows is like chocolate cake without mustard. -- Anonymous Coward /. Fonty Python and other dev news at: http://otherwiseingle.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Email module, how to add header to the top of an email?
I have been using the Email module and Message class for awhile, however I have been unable to find a way to add a header to the top of the email similar to what is done with Received: headers... the add_header method only appends to the bottom. Is there someway this can be done? Thanks David -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Large File (Code/Performance)
[EMAIL PROTECTED] writes: I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. I'd greatly appreciate if someone can post sample code that can help me do this. Use the unix sort command: sort inputfile -o outputfile I think there is a cygwin port. Also, any ideas on approximately how long is the sort process going to take (XP, Dual Core 2.0GHz w/2GB RAM). Eh, unix sort would probably take a while, somewhere between 15 minutes and an hour. If you only have to do it once it's not worth writing special purpose code. If you have to do it a lot, get some more ram for that box, suck the file into memory and do a radix sort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Test driven development
Virgil Dupras schreef: On Jan 24, 1:30 pm, Roel Schroeven [EMAIL PROTECTED] wrote: Virgil Dupras schreef: I know what you mean by top-down vs. bottom-up and I used to have the same dilemma, but now I would tend to agree with Albert. Your issue with top-down or bottom-up is not relevant in TDD. The only thing that is relevant is to reach your current milestone as soon as possible, without caring about what you're going to do in the milestone after that. Not so long ago, I took the bottom-up approach to TDD, which was a mistake because it leads to over-engineering (the end result is not so bad since it's over-engineering that has good test coverage :) ) I don't regularly use TDD yet, and one of the reasons is that in many cases I'm unsure exactly how to use it in practice. I read Test-driven development - A practical guide (and I should re-read), but I feel it doesn't help my much in everyday situations. Somehow the examples in the book don't match very well with how I code (and I admit that perhaps the problem is more with me than with the book). One of the problems I have is something like what Andy describes: I need a function spam(), so I write tests for it. Then I start implementing the function and see that I need to write functions ham() and eggs(). Should I write unit tests for ham() and eggs(), or do I rely on the tests for spam()? If I don't write them, doesn't that make it more difficult to find out why the tests for spam() fail? Speaking about over-engineering, when I do TDD along the lines of the book I mentioned, I always feel that I'm over-engineering the tests. It all feels very unnatural though I'm convinced it shouldn't be like that. Can someone suggest other books to read about the subject, ideally something more focused on Python or C++ rather than Java? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven I also have a book about TDD and it never was of much help either. All techniques come from the initial workflow: Red - Green - Refactor. The problem you describe is a tricky problem. The way I feel it should be solved is: - Write spam() (and its tests, of course). - Then, at some point, in the re-factor phase, you split extract the function ham() from spam(). Alright, do it and keep the tests as is (all on spam()). - Then at some other point, you extract eggs(). same thing. - After a while (I don't know, 3 or 4 milestones), when it becomes clear that ham() and eggs() are there to stay, start moving your tests away from spam() by just mocking ham() and eggs() and just make sure that spam() call them with the right arguments. The tests you had on spam() that were relevant to ham() and eggs() are just performed directly on them now. What I've been saying in my other message is: Don't do that too early, because if it turns out that ham() and eggs() is not the optimal way to do it, but foo() bar() and baz() is, it is *much* easier to do a safe re-factoring with high level tests. That sounds reasonable. I'm getting the impression that reading that book led me to a too strict approach. I guess I just need to try somewhat harder to use TDD in my daily coding. Apart from books, are there other resources that can help beginners with TDD? Mailing lists, forums, newsgroups possibly? -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux Journal Survey
want to vote for Python. http://www.linuxjournal.com/node/1006101 18. What is your favorite programming language? (15 choices, Python not included) I'm not sure why some folks have their knickers in a knot...I took the survey and there was an Other box, so I just wrote in Python for my favorite programming language. I mean, Basic, Lisp, and Prolog make it in there...I use Python for programming a heckuva lot more than I use any of the others. 19. What is your favorite scripting language? o Python and answered Python for this question too. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Duplicating a variable
On Jan 24, 9:55 am, [EMAIL PROTECTED] wrote: If your variable contains a list, then you can copy it like this: l1 = [1, 2, 3] l2 = l1[:] l2[1] = 4 As you can see now they are two distinct lists: l1 [1, 2, 3] l2 [1, 4, 3] If you want to copy any kind of object you can use the copy function (instead of a simpler copy method that's absent): d1 = {1:2, 3:4} from copy import copy d2 = copy(d1) d1[1] = 5 d1 {1: 5, 3: 4} d2 {1: 2, 3: 4} But as you can see copy works only one level deep: d3 = {1:[1], 3:4} d3 {1: [1], 3: 4} d4 = copy(d3) d3[1][0] = 2 d3 {1: [2], 3: 4} d4 {1: [2], 3: 4} To copy all levels you need deepcopy: from copy import deepcopy d5 = deepcopy(d3) d3[1][0] = 5 d3 {1: [5], 3: 4} d4 {1: [5], 3: 4} d5 {1: [2], 3: 4} Bye, bearophile Works great, it is exactly what I needed thanks! -Hans -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Large File (Code/Performance)
[EMAIL PROTECTED] wrote: Hello all, I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. Given those numbers, the average number of characters per line is less than 2. Please check. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Smart Debugger (Python)
Hi All, Please find the smart debugger for python. it is an enchanced version of python pdb with data rendering feature. http://develsdb.googlecode.com/svn/trunk/python/ http://develsdb.googlecode.com/svn/wiki/SmartDebuggerPython.wiki hope you find this useful. Regards, Karthik -- http://mail.python.org/mailman/listinfo/python-list
Re: sudoku solver in Python ...
On Wed, 23 Jan 2008 19:02:01 -0800 (PST), Derek Marshall wrote: This is just for fun, in case someone would be interested and because I haven't had the pleasure of posting anything here in many years ... http://derek.marshall.googlepages.com/pythonsudokusolver Appreciate any feedback anyone who takes the time to have a look would want to give ... Yours with-too-much-time-to-kill-on-the-train'ly, Derek Neither fast nor user friendly, but very concise: options = set([str(i) for i in range(1, 10)]) def solve(puzzle): i = puzzle.find('0') if i 0: print puzzle return exclude = set( puzzle[j] if i//9 == j//9 or i%9 == j%9 or i//27 == j//27 and (i%9)//3 == (j%9)//3 else '0' for j in range(81) ) for option in options - exclude: solve(puzzle[:i] + option + puzzle[i+1:]) solve('20037516963921845757196438215249687334875291679683124590010050087600400089001') solve('05430007000162903156002504010034089002080610073860997100070006240') solve('2060895009005003806090009000100370009000810060009000105084007001009140207') solve('0001500704800202097030002900500040068000108104060028050014000') solve('0008970901006010090030257410600800207005090763000') solve('50001090073025600750080080003004007100821069006070004') solve('07004006300200904050800703009008060070080500702010400700690020030') solve('570090180030040862405000609559030020091030075') solve('07004006300200904050800703009008060070080500702010400700690020030') solve('1840800090345000409652008007653010002510700020792') solve('06003045900028008000730900509008060070800503600090042000938020010') solve('0014078601509000802301300056095070005043091807300') solve('7050200030035040076308200062093800904100100070302') solve('0010074002009660030057008900930510069002700600582007005200800') solve('0073002003000180062073450584906700420006009004300') I can't take credit for it, though. It's an adaptation of a one-liner in Groovy, that comes with the ducumentation: def r(a){def i=a.indexOf(48);if(i0)print a else(('1'..'9')-(0..80).collect{j- g={(int)it(i)==(int)it(j)};g{it/9}|g{it%9}|g{it/27}g{it%9/3}?a[j]:'0'}).each{ r(a[0..i]+it+a[i+1..-1])}} Although this one-liner is buggy, the underlying idea is good, so I pilfered ;-) OT: If you're interested in a slightly more readable (and working) version: def r(a){ def i = a.indexOf(48) if( i 0 ){ println a; return } ( ('1'..'9') - ( 0 .. 80).collect{ j- i.intdiv(9) == j.intdiv(9) || i%9 == j%9 || i.intdiv(27) == j.intdiv(27) (i%9).intdiv(3) == (j%9).intdiv(3) ? a[j] : '0' } ).each{ r(a[0..i] + it + (i==80 ? : a[i+1..-1])) } } Thomas -- http://mail.python.org/mailman/listinfo/python-list
a newbie regex question
Given a regular expression pattern, for example, \([A-Z].+[a-z]\), print out all strings that match the pattern in a file Anyone tell me a way to do it? I know it's easy, but i'm completely new to python thanks alot -- http://mail.python.org/mailman/listinfo/python-list
Ignore exceptions
Hy. Is there any way to make interrupter ignore exceptions. I'm working on bigger project and i used to put try catch blocks after writing and testing code what's boring and it's easy to make mistake. I remember of something like that in C++ but I cant find anythin like that for python. SMALLp -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignore exceptions
On Jan 24, 2:13 pm, SMALLp [EMAIL PROTECTED] wrote: Hy. Is there any way to make interrupter ignore exceptions. I'm working on bigger project and i used to put try catch blocks after writing and testing code what's boring and it's easy to make mistake. I remember of something like that in C++ but I cant find anythin like that for python. SMALLp See the try statement: http://docs.python.org/ref/try.html http://www.network-theory.co.uk/docs/pytut/HandlingExceptions.html http://docs.python.org/api/exceptionHandling.html Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignore exceptions
On 2008-01-24, SMALLp [EMAIL PROTECTED] wrote: Hy. Hi. Is there any way to make interrupter ignore exceptions. Nope. Either handle the exceptions or write code that doesn't generate exceptions. I'm working on bigger project and i used to put try catch blocks after writing and testing code You're getting unhandled exceptions after you've tested your code? I guess you need to do better testing. what's boring and it's easy to make mistake. I remember of something like that in C++ but I cant find anythin like that for python. I should hope not. The Python language wouldn't _work_ if the VM ignored exceptions. Exceptions are used for all sorts of things besides errors (terminating a loop, exiting a program, etc.). If exceptions were ignored all sorts of things would stop working. -- Grant Edwards grante Yow! I'll show you MY at telex number if you show me visi.comYOURS ... -- http://mail.python.org/mailman/listinfo/python-list
object vs class oriented -- xotcl
I've been away from Python for at least a year, and in the interim have spent a little time looking at the XOTcl object framework for Tcl. One of the interesting features of XOTcl is the ability for an object to change class dynamically. The XOtcl documentation makes the claim that this makes it object oriented, while most other languages are class oriented. Here's a snippet from the wiki, from a post to the mailing list by Gustaf Neumann: (http://wiki.tcl.tk/1297) Class-oriented means: look at the class and you know exactly how all of the instances look alike. The class is the first and primary language construct; the class is well the place where you specify the instance variables (there are no instance variables except those specified in the class). The only kind of individualism left in the objects is to let them differ by their state (the values of their instance variables). Changing classes (class migration) is conceptually quite hard for this setup. Object-oriented (in this distinction) means that the primary elements are objects, which keep all instance variables. classes my be used to specify the behavior of objects, they are container for methods and they control the life-cycle of objects. Objects are like the facts, and classes are like rules, that determine the behavior of the objects. Since the connection between objects and classes is rather loose, it is sufficient to define their relation through an association. Therefore it is quite easy to change the relation between objects and classes (and between classes and classes) dynamically. Objects have arbitrary individualism, they may have variables never used in any class, they may have private procs etc. I'm not sure that describes the method well. Basically, you can instantiate an object A of class Foo, and later change A to be an object of class Bar. Does Python support this type of flexibility? As I stated above, I've been away from Python for awhile now, and am a bit rusty, but it seems that slots or new style objects might provide this type of behavior. The ability to have an object change class is certainly (to me) a novel idea. Can I do it in Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Large File (Code/Performance)
On Jan 25, 6:18 am, [EMAIL PROTECTED] wrote: Hello all, I have an Unicode text file with 1.6 billon lines (~2GB) that I'd like to sort based on first two characters. If you mean 1.6 American billion i.e. 1.6 * 1000 ** 3 lines, and 2 * 1024 ** 3 bytes of data, that's 1.34 bytes per line. If you mean other definitions of billion and/or GB, the result is even fewer bytes per line. What is a Unicode text file? How is it encoded: utf8, utf16, utf16le, utf16be, ??? If you don't know, do this: print repr(open('the_file', 'rb').read(100)) and show us the results. What does based on [the] first two characters mean? Do you mean raw order based on the ordinal of each character i.e. no fancy language- specific collating sequence? Do the first two characters always belong to the ASCII subset? You'd like to sort a large file? Why? Sorting a file is just a means to an end, and often another means is more appropriate. What are you going to do with it after it's sorted? I'd greatly appreciate if someone can post sample code that can help me do this. I'm sure you would. However it would benefit you even more if instead of sitting on the beach next to the big arrow pointing to the drop zone, you were to read the manual and work out how to do it yourself. Here's a start: http://docs.python.org/lib/typesseq-mutable.html Also, any ideas on approximately how long is the sort process going to take (XP, Dual Core 2.0GHz w/2GB RAM). If you really have a 2GB file and only 2GB of RAM, I suggest that you don't hold your breath. Instead of writing Python code, you are probably better off doing an external sort. You might consider looking for a Windows port of a Unicode-capable Unix sort utility. Google GnuWin32 and see if their sort does what you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone explain this unexpected raw_input behavior?
If it weren't for the documentation... If the prompt argument is present, it is written to *standard output* without a trailing newline. -- mvh Björn I have reported this issue to the python-dev mailing list, and Guido agrees that this is a bug in Python. It turns out that the key is that my site does not have GNU readline installed, so Python falls back to its own implementation of readline. Using GNU readline, raw_input will write its prompt to stdout. Python's own implementation of readline sends the output to stderr. As Bjorn states, the documentation for raw_input says it writes its prompt to stdout. A bug issue has been opened in the Python Trac system for this. -- http://mail.python.org/mailman/listinfo/python-list
Re: object vs class oriented -- xotcl
On Jan 24, 12:35 pm, William Pursell [EMAIL PROTECTED] wrote: I'm not sure that describes the method well. Basically, you can instantiate an object A of class Foo, and later change A to be an object of class Bar. Does Python support this type of flexibility? As I stated above, I've been away from Python for awhile now, and am a bit rusty, but it seems that slots or new style objects might provide this type of behavior. The ability to have an object change class is certainly (to me) a novel idea. Can I do it in Python? Short answer: yes, easily. Long answer: observe. class Foo(object): ... def foo(self): print Foo.foo ... class Bar(object): ... def foo(self): print Bar.foo ... a = Foo() a.__class__ = Bar a.foo() Bar.foo -- http://mail.python.org/mailman/listinfo/python-list