how to arrange classes in .py files?
Hi all, I work with Java. Recently I read some about python, and it is really impressive. So i decide to learn it in my spare time by a small application. But i got a question about the python classes. Didn't find any help with Google. In java, usually a .java file contains One Class. I read some python codes, I found one py file can have many classes and functions. Is there any convention how to manage python classes into .py files? Now I just deal with my little application exactly in Java style: package: gui, service, dao, entity, util (from the package name, you can see the MVC pattern) gui: wxPython classes service: business logic, transaction mgmt etc. dao: Data access classes entity: "pojo"s util: some handy utility classes later VO classes/package may be involved as well. In above packages, each .py file contains one python class. And ClassName = Filename not sure about the right code structure of python oop. Can anyone give some hint on it? would be great with reason. Thanks in advance. regards, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying a list element from a function
> * to do the same modification on the list "a" within a function > * not to hardcode in this function the position of the string in each >>> a = [ [4, "toto"], [5, "cou"] ] >>> def assign(element,pos,newValue): ... element[pos]=newValue ... >>> assign(a[0],1,'xxx') >>> print a [[4, 'xxx'], [5, 'cou']] >>> does it fit the requirement? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to arrange classes in .py files?
On Mar 27, 3:01 pm, "David L. Jones" wrote: > On Mar 26, 8:51 pm, Kent wrote: > > > ... Is > > there any convention how to manage python classes into .py files? > > > ... > > In above packages, each .py file contains one python class. And > > ClassName = Filename > > > ... > > Can anyone give some hint on it? would be great with reason. > > Overall, I don't think there is a single convention that anyone can > point to and everyone will at least acknowledge as convention. > > If you have multiple single-class files, then you will have > unnecessary redundancy referencing the classes from outside: > > # Module structure: mymodule/ > # __init.py__ > # someclass.py > import mymodule > c = mymodule.someclass.someclass() > > You can get around this with a Java-like statement: > > # Same module structure > from mymodule.someclass import someclass # or from ... import * > c = someclass() > > but you lose namespacing which can make code more difficult to read. I > think that this Java-style approach of pulling everything into the > current namespace is quite silly, since Python's module structure was > specifically designed in large part not to work like this. (Commence > flaming.) > > I tend to think in terms of coupling and cohesion. Within an > application, any classes, functions, data, etc. that are tightly > coupled are candidates to live in the same file. If you have a set of > classes that all inherit from a common set of base classes, then you > should probably consider putting the base and inherited classes > together in a file. That puts them in the same namespace, which makes > sense. > > Cohesion is the flip side: if a class is large, even if it is somewhat > coupled to other classes, it should probably go in its own file. In > general, use coupling as a guide to put more things into a single > file, and cohesion as a guide to break out parts into multiple files. > > D thanks you guys' explaination. I did some refactory on my codes. Now it look's like: myapp/ # this is a package, it is the root package - gui/ # this is package, contains all gui related modules - mainFrame.py - dao.py # all daos are in this module - service.py # all service classes, responsible for handling DB connections, Txn mgmt, and Business logic Task (calling daos) - entity.py # like 'pojo's, in java, - util.py # utils - myapp.py # start main script with this structure, import statements were *significantly* reduced. :) -- http://mail.python.org/mailman/listinfo/python-list
question about wxpython CtrlList event binder: wx.EVT_LIST_ITEM_RIGHT_CLICK
Hi there, I wrote a desktop application with wxPython2.8. And got a problem. Hope here someone can give some hint. Thanks in advance. There was a ListCtrl (lc) in my GUI, and it was a bit long, so that there would be some blank space below ("empty area") in case there were only a few items. I bind a function on the event wx.EVT_LIST_ITEM_RIGHT_CLICK, when user rightclick on the lc item, my function was triggered, and open a popup menu. Depends on the item user clicked, the menu items can be different. I checked the event.getData(), to decide which menu item will show to user. That is, if user right click on the "empty area", the event.getData() will be 0. I wrote the appl. under Linux, and tested, it worked as what I expected. However, today someone reported a bug, said, under Windows XP, right clicking on the items of lc, it works fine, but if on the "empty area" of the lc, nothing happened, no popup menu. I tested under WINXP, the function was not triggered at all when I right-clicked on the "empty area". I tried to bind wx.EVT_RIGHT_DOWN(UP) to the lc, but the function cannot be triggered under Linux. any suggestion? Thanks regards, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: question about wxpython CtrlList event binder: wx.EVT_LIST_ITEM_RIGHT_CLICK
Hi Mike, thx for the wxpython maillist link, I will give it a shot. But I would like to paste the code snippet here as well, hope it can tell sufficient information. (I added some comments in the class. ) Thank you. class TagListCtrl(wx.ListCtrl): ''' Tag list ListCtrl widget ''' def __init__(self,parent,id): # this 'images' is not important, just icons images = (myGui.ICON_TAG_CUSTOM, myGui.ICON_TAG_ALL,myGui.ICON_TAG_SEARCH, myGui.ICON_TAG_TRASH, myGui.ICON_TAG_FAV) # so the listctrl is in REPORT MODE wx.ListCtrl.__init__(self,parent,id,style=wx.LC_REPORT| wx.LC_HRULES| wx.LC_SINGLE_SEL) #here are some property value init.. self.SetName(myGui.TAG_LIST_NAME) self.parent = parent self.mainFrm = self.GetTopLevelParent() # main Frame il = wx.ImageList(24,24) for image in images: il.Add(wx.Bitmap(image,wx.BITMAP_TYPE_PNG)) self.InsertColumn(0,'Tags') self.AssignImageList(il,wx.IMAGE_LIST_SMALL) #popup menu self.popmenu = None # bind the events self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelect) #selected, e.g. left click self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onTagMgmt,self) # right click, HERE COMES THE PROBLEM #this function load the item data into the List self.loadTags() #this is the function def onTagMgmt(self,event): tagId = event.GetData() # following codes are omitted. just some business logic stuff. checking the tagId, making decision of showing popup menu items... Kent On Apr 21, 11:24 pm, Mike Driscoll wrote: > On Apr 21, 3:35 pm, Kent wrote: > > > Hi there, > > > I wrote a desktop application with wxPython2.8. And got a problem. > > Hope here someone can give some hint. Thanks in advance. > > I recommend joining the wxPython mailing list and posting there. The > guys there are great and can probably help you out. > Seehttp://wxpython.org/maillist.php > > > > > > > There was a ListCtrl (lc) in my GUI, and it was a bit long, so that > > there would be some blank space below ("empty area") in case there > > were only a few items. > > > I bind a function on the event wx.EVT_LIST_ITEM_RIGHT_CLICK, when user > > rightclick on the lc item, my function was triggered, and open a popup > > menu. > > > Depends on the item user clicked, the menu items can be different. I > > checked the event.getData(), to decide which menu item will show to > > user. That is, if user right click on the "empty area", the > > event.getData() will be 0. I wrote the appl. under Linux, and tested, > > it worked as what I expected. > > > However, today someone reported a bug, said, under Windows XP, right > > clicking on the items of lc, it works fine, but if on the "empty area" > > of the lc, nothing happened, no popup menu. I tested under WINXP, the > > function was not triggered at all when I right-clicked on the "empty > > area". > > > I tried to bind wx.EVT_RIGHT_DOWN(UP) to the lc, but the function > > cannot be triggered under Linux. any suggestion? > > > Thanks > > > regards, > > > Kent > > If you join the wxPython list, they'll probably ask for a small > runnable sample. Here's some instructions for how to do > that:http://wiki.wxpython.org/MakingSampleApps > > It would be good to know what mode you are using for your ListCtrl. > List view, report, icon or what? The demo doesn't have any white space > at the end, so I can't test this easily. Are you using a sizer to hold > the widget? > > - Mike -- http://mail.python.org/mailman/listinfo/python-list
WINXP vs. LINUX in threading.Thread
hello all, i want to add a "new update notification" feature to my wxPython appl. The codes below do the job. The logic is simple enough, I don't think it needs to be explained. since sometimes, under windows, proxy setting was a script. and was set in IE. In this case, connecting to the HTML will take relative long time. I therefore run the following codes in a new Thread (subclass of threading.Thread), so that user don't have to wait during the version checking period. Under Linux, it worked smoothly. But under Windows XP, it didn't. If there was new updates, the notification dialog can show, but no text, icon, on it. Then, the whole application didn't response any longer. :( I have to force stop the application process. where is the problem? Thanks. code to get the version from a HTML: def getLatestVersion(versionUrl): #proxy is only for testing #proxy_support = urllib2.ProxyHandler ({"http":"10.48.187.80:8080"}) #opener = urllib2.build_opener(proxy_support) #urllib2.install_opener(opener) #proxy is only for testing result = '' try: f = urllib2.urlopen(versionUrl) s = f.read() f.close() result = s.split("#xxx#")[1] except: pass return result Thread class: class UpdateChecker(Thread): def __init__(self): Thread.__init__(self) def run(self): lv = util.getLatestVersion(config.VERSION_URL) if lv>config.VERSION: showUpdateDialog(lv) codes to start the thread: updatechk = UpdateChecker() updatechk.start() -- http://mail.python.org/mailman/listinfo/python-list
Re: WINXP vs. LINUX in threading.Thread
Thanx you guys. Now my program is working. I used the Thread subclass. and at the end of the run method, i call wx.CallAfter(mainFrame.somefunction, para) to show the dialog or change some text. I tested in winxp&linux. both worked. Kent On Apr 23, 6:16 am, Carl Banks wrote: > On Apr 22, 5:34 pm, Lie Ryan wrote: > > > > > Diez B. Roggisch wrote: > > > Kent schrieb: > > >> hello all, > > > >> i want to add a "new update notification" feature to my wxPython appl. > > >> The codes below do the job. The logic is simple enough, I don't think > > >> it needs to be explained. > > > >> since sometimes, under windows, proxy setting was a script. and was > > >> set in IE. In this case, connecting to the HTML will take relative > > >> long time. I therefore run the following codes in a new Thread > > >> (subclass of threading.Thread), so that user don't have to wait during > > >> the version checking period. > > > >> Under Linux, it worked smoothly. But under Windows XP, it didn't. If > > >> there was new updates, the notification dialog can show, but no text, > > >> icon, on it. Then, the whole application didn't response any > > >> longer. :( I have to force stop the application process. > > > >> where is the problem? > > > > GUI-toolkits and threads usually are not a good idea (Qt4 being an > > > exception to that rule, at least they claim that). Google wxPython + > > > threading for answers how to solve this - essentially, you need to > > > create a timer or event-based solution that allows your > > > background-thread to inject a status message to the main eventloop. > > > > Diez > > > You should use the GUI toolkit's own event loop for threading. An event > > loop is some sort of cooperative multithreading mechanism, > > The function in question, gethostbyname, isn't cooperating, though. > It blocks for a substantial amount of time from an event handler, > freezing the application. > > > if you used > > the threading mechanism from the threading library, there will be two > > conflicting threading mechanism, resulting in many hard-to-predict > > situation if you're not careful. The wxYield mechanism is much easier > > option than multithreading. > > The problem is, during most of the delay wxYield can't be called > becaust the function gethostbyname is blocking. > > I think Diez is correct. To avoid the freeze, one should spawn a > thread, and when it completes it should notify the GUI thread by > pushing an event or scheduling an idle call. Functions that do that > are usually thread-safe. (A permanent worker thread might be better > but it would involve a lot more synchronization.) > > Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators and propagation of exceptions
On Apr 8, 3:47 pm, r wrote: > I'm already making something like this (that is, if I understand you > correctly). In the example below (an "almost" real code this time, I > made too many mistakes before) all the Expressions (including the > Error one) implement an 'eval' method that gets called by one of the > loops. So I don't have to do anything to detect the error, just have > to catch it and reraise it at each stage so that it propagates to the > next level (what I have to do anyway as the next level generates > errors as well). > > class Expression(object): > def eval(self): > pass > > class Error(Expression): > def __init__(self, exception): > self.exception = exception > > def eval(self): > raise self.exception Perhaps, instead of raising exceptions at each level, you could return an Error object that implements the eval() (or whatever appropriate protocol) to return an appropriate new Error object. In this case, you could have class Error(Expression); def eval(self): return unicode(self.exception) Error would itself be created by Expression.parseToken(), instead of raising an exception. The idea is that at each level of parsing, instead of raising an exception you return an object which, when interpreted at the next outer level, will again return an appropriate error object for that level. You might be able to have a single Error object which implements the required methods at each level to just return self. I don't know if this really works when you start nesting but perhaps it is worth a try. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: optparse eats $
Try this on your *nix command line: echo ">$100" On a *nix command line, the '$1' part of ">$100" will be seen as 'give me the value of the shell variable "1"', and since it has no value, will result in an empty string. So it's not optparse, or Python, because the literal string you intend to pass as a command line argument to your Python script never has a chance of getting there. Try escaping the '$' with a backslash on the command line. -- http://mail.python.org/mailman/listinfo/python-list
Re: skipping one unittest assertion?
I agree that each test should test only one 'thing', but it's also true that testing one 'thing' sometimes/often involves multiple assertions. But in the OP's case, it does sound like the assertion he wants to skip should be broken out into its own test. -- http://mail.python.org/mailman/listinfo/python-list
Re: portable multiprocessing code
You could also install Python 2.7 on that RedHat machine. It can be done without interfering with the 2.5 that RedHat depends on. -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining a full path name from file
If a filename does not contain a path component, os.path.abspath will prepend the current directory path onto it. -- http://mail.python.org/mailman/listinfo/python-list
free python course materials for high school students available
Hi, I've taught a python course with some positive results to high school students with zero experience in programming. Now I am making these course materials (slides in English and lecture videos in Cantonese) freely available as a contribution back to the community (http://www.istudycenter.org/summercourses/programming-for-kids/python-materials). Hope you find them useful :-) -- https://mail.python.org/mailman/listinfo/python-list
training materials and learning environment for teaching kids python available
Hi all, This is a set of training materials I used to successfully teach Python to kids as little as 10 years old. It was a success because the kids didn't just finish the course, they independently completed most of the coding challenges by applying the knowledge they had learned. The first four lessons (Lesson 1, Lesson 2, Lesson 3, Lesson 4) and a lite version of the learning environment are freely available at: https://www.istudycenter.org/yes-kids-can-learn-python Let me know if you like it. Thanks! -- https://mail.python.org/mailman/listinfo/python-list
can't add variables to instances of built-in classes
Hi, I can add new variables to user-defined classes like: >>> class Test: ... pass ... >>> a=Test() >>> a.x=100 but it doesn't work if the instances belong to a built-in class such as str or list: >>> a='abc' >>> a.x=100 Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'x' What makes this difference? Thanks in advance! -- https://mail.python.org/mailman/listinfo/python-list
Re: can't add variables to instances of built-in classes
Hi Peter, Thanks a lot for your excellent explanation! -- https://mail.python.org/mailman/listinfo/python-list
Why not allow empty code blocks?
Hi I'm aware that we can use 'pass' as an empty code block. But why doesn't python allow a code block to be empty and thus eliminate the need for this null statement? thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Re: Why not allow empty code blocks?
On Saturday, July 23, 2016 at 9:49:51 AM UTC+8, Steven D'Aprano wrote: > Because it cannot tell the difference between an empty code block and > failing to indent the code block: > > for x in sequence: > print('loop') Thanks for the excellent answer! -- https://mail.python.org/mailman/listinfo/python-list
Interactively online Python learning environment freely available
Hi, I've made an online python learning environment available at https://p4kweb.appspot.com Please take a look and let me know what you think :-) -- https://mail.python.org/mailman/listinfo/python-list
My Python programming book for kids is free for 48 hours
Hi, If you're interested, please get it for free at: https://www.amazon.com/Yes-Kids-can-learn-Python-ebook/dp/B084CY2L43/ref=sr_1_3 This is a set of training materials I used to successfully teach Python to kids as little as 10 years old. The online learning environment are freely available at https://p4kweb.appspot.com and the first four chapters are available at https://www.istudycenter.org/yes-kids-can-learn-python. Lesson 1: Call a function & use variables Lesson 2: Expressions and text strings Lesson 3: Perform various calculations based values input by the user Lesson 4: Use the tank to draw shapes with its bombs Lesson 5: Show an input box and use "if" in Python Lesson 6: Prompt for multiple values and display information in a message box Lesson 7: increase the value of a variable and call a function that gives back information Lesson 8: Use "if" without "else" Lesson 9: Use "if" to guard against an operation that might fail Lesson 10: 2D coordinate system for positioning objects Lesson 11: Respond to mouse clicks and kick start a continuous process Lesson 12: Use random numbers Lesson 13: Use 'and' or embedded 'if's Lesson 14: Respond to key presses Lesson 15: Respond to key presses (2) Lesson 16: Boolean values and stop a continuous process Lesson 17: stop a continuous process (2) Lesson 18: Steer a continuous process -- https://mail.python.org/mailman/listinfo/python-list
Re: unittest setup
paul kölle wrote: > hi all, > > I noticed that setUp() and tearDown() is run before and after *earch* > test* method in my TestCase subclasses. I'd like to run them *once* for > each TestCase subclass. How do I do that. One way to do this is to make a TestSuite subclass that includes your startup and shutdown code. For example I have some tests that rely on a webserver being started. I have a TestSuite that starts the server, runs the tests and stops the server. This way the server is only started once per test module. Here is the TestSuite class: class CbServerTestSuite(unittest.TestSuite): ''' A test suite that starts an instance of CbServer for the suite ''' def __init__(self, testCaseClass): unittest.TestSuite.__init__(self) self.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(testCaseClass)) def __call__(self, result): CbServer.start() unittest.TestSuite.__call__(self, result) CbServer.stop() I use it like this: class MyTest(unittest.TestCase): def testWhatever(self): pass def suite(): return CbServerTestSuite(MyTest) if __name__=='__main__': unittest.TextTestRunner().run(suite()) This runs under Jython (Python 2.1); in more recent Python I think you can override TestSuite.run() instead of __call__(). Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Not defined
Rob wrote: > When trying the basic tutorial for cgkit I always seem to get a not defined > error as follows. > > Pythonwin GUI > > >>>>from cgkit import * >>>>Sphere() > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'Sphere' is not defined Which version of cgkit are you using? Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Will python never intend to support private, protected andpublic?
Mike Meyer wrote: > Paul Rubin <http://[EMAIL PROTECTED]> writes: > >>>>That's not what privilege separation means. It means that the >>>>privileged objects stay secure even when the unprivileged part of the >>>>program is completely controlled by an attacker. >>> >>>In which case, what's "private" got to do with this? The examples I've >>>seen of it don't give you privilege seperation any more than python does. >> >>If you have a java class instance with a private member that's (say) a >>network socket to a special port, access to the port is controlled >>entirely by that class. > > > Are you sure? My understanding was that Java's introspection mechanism > could be used to access private variables. Yes, in a Java application with the default security manager it is trivial to access a private variable of another class using introspection. For example: /* HasPrivate.java */ public class HasPrivate { private int myPrivate = 42; } /* HackPrivate.java */ import java.lang.reflect.Field; public class HackPrivate { public static void main(String[] argv) throws Exception { HasPrivate hp = new HasPrivate(); Field notSoPrivate = hp.getClass().getDeclaredField("myPrivate"); notSoPrivate.setAccessible(true); System.out.println("myPrivate = " + notSoPrivate.getInt(hp)); } } Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Nicer way of strip and replace?
Markus Rosenstihl wrote: > Hi, > I wonder if i can make this nicer: > > euro=euro + float(string.replace(string.strip(rechnung[element][10], > '"'), ',' , '.')) You can use the str methods instead of functions from the string module: euro=euro + float(rechnung[element][10].strip('"').replace(',' , '.')) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: are there internal functions for these ?
black wrote: > hi all~ > > i wrote some functions for copying and moving files caz' i didnt find > concret functions within the doc. but i think these operations are > simple and important so there may be some internal ones i didnt know. > anyone could figure me out ? See the os, os.path and shutil modules for many file operations including copy and move. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python adodb
[EMAIL PROTECTED] wrote: > In trying to use the adodb module, I have had good success. However I > need to access a database with a username and password at this time. I have used a connection string like this to connect to MS SQL Server from adodb: connStrSQLServer = r"Provider=SQLOLEDB.1; User ID=user; Password=passwd;Initial Catalog=Northwind;Data Source=(local)" HTH Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a Python mentor
LenS wrote: > Hello > > Was wandering if there is any place where some one could go to get > mentoring on python coding. I have started coding in python but I am > the only one in the shop using it. So there is no one around to look > over my code give suggestions on improvement, in style, logic, easier > ways of doing things etc. I second gene's recommendation of the python-tutor mailing list - we do all of the above as well as cheerfully answer all questions, give suggestions on how to do things, etc. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem splitting a string
Alex Martelli wrote: > Using sum on lists is DEFINITELY slow -- avoid it like the plague. > > If you have a list of lists LOL, DON'T use sum(LOL, []), but rather > > [x for x in y for y in LOL] Should be >>> lol = [[1,2],[3,4]] >>> [x for y in lol for x in y] [1, 2, 3, 4] The outer loop comes first. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem splitting a string
Steven D'Aprano wrote: > On Sat, 15 Oct 2005 10:51:41 +0200, Alex Martelli wrote: >>[ x for x in y.split('_') for y in z.split(' ') ] > > py> mystr = 'this_NP is_VL funny_JJ' > py> [x for x in y.split('_') for y in mystr.split(' ')] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'y' is not defined The order of the 'for' clauses is backwards: >>> [x for y in mystr.split(' ') for x in y.split('_')] ['this', 'NP', 'is', 'VL', 'funny', 'JJ'] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Outdated documentation
Laszlo Zsolt Nagy wrote: > Is this the good place to post? Follow the "About this document" link at the bottom of any page of Python docs for information about submitting change requests. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: ordered keywords?
Ron Adam wrote: > drawshapes( triangle=3, square=4, color=red, > polygon(triangle, color), > polygon(square, color) ) > > This comes close to the same pattern used in SVG and other formats where > you have definitions before expressions. Why is this better than the obvious triangle=3 square=4 color=red drawshapes(polygon(triangle, color), polygon(square, color) ) or even drawshapes(polygon(3, red), polygon(4, red) ) which is concise and readable IMO...? Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest of file-reading function
Helge Stenstroem wrote: > Say I have a function > > def f(filename): > result = openFileAndProcessContents(filename) > return result > > Can that function be unit tested without having a real file as input? If you can refactor openFileAndProcessContents() so it looks like this: def openFileAndProcessContents(filename): data = open(filename).read() processContents(data) then you can write your tests against processContents() and just pass it a string with the test data. I usually have a set of test files as part of my project that I can pass to functions like this. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie]Is there a module for print object in a readable format?
Micah Elliott wrote: > On Oct 20, Steven D'Aprano wrote: > >>That's not what I get. What are you using? >> >>py> pprint.pprint([1,2,3,4,[0,1,2], 5], width=1, indent=4) >>Traceback (most recent call last): >> File "", line 1, in ? >>TypeError: pprint() got an unexpected keyword argument 'width' > > > I find it useful to have all relevant python versions (as listed on > http://www.python.org/download/) installed on my primary test > machines. If you want to know when a feature was introduced, the docs are often helpful: pprint( object[, stream[, indent[, width[, depth]]]]) Changed in version 2.4: The parameters indent, width and depth were added. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: parser question
Micah Elliott wrote: > You might be able to tackle this easily enough with REs if your > structures don't nest arbitrarily. It's hard to tell if this deserves > a formal grammar based on the example. If it does, you could try PLY > <http://www.dabeaz.com/ply/> (which I've had a pleasant experience > with in the past) or any of the other parsers listed on the PLY site's > "Other Python Parsing Tools". A more complete list is here: http://www.nedbatchelder.com/text/python-parsers.html I have found pyparsing easy to work with. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python variables are bound to types when used?
[EMAIL PROTECTED] wrote: > So I want to define a method that takes a "boolean" in a module, eg. > > def getDBName(l2): > ... > > Now, in Python variables are bound to types when used, right? > > Eg. > x = 10 # makes it an INT > whereas > x = "hello" # makes it a string You don't have it quite right. In each case, the name 'x' is bound to a value. The type is a property of the value, not of the name. > > I take it, the parameters to a function (in the above example "l2") are > bound in the definition, rather than as invoked. No, the parameter values are bound to the parameter names at the time of call. Again, it is the value that is typed, not the name. > > So, if I use "l2" thus: > > if (l2): # only then does it make it a boolean? No, this doesn't change the type of the value bound to l2, it just evaluates the value as True or False according to the rules here: http://docs.python.org/ref/Booleans.html#Booleans > > and if I did, > > if (l2 = "hello"): # would it become string? No; assuming you mean to compare l2 == "hello", this will call a special method of the object bound to l2, passing "hello" as a parameter. The result will be evaluated as True or False. The actual method called on l2 may be __cmp__ or __eq__. http://docs.python.org/ref/customization.html Kent > > and what if I never used it in the definition body? > > Elucidate please. > -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
[EMAIL PROTECTED] wrote: > how ? > i have tried to use unix timestamps, and i have also tried with > DateTime objects > do i need to use a scale that isn't linear (default in most) ? > how do i putt this off ? Here is some code that works for me. It plots multiple datasets against time. The input data looks like this: 2005-04-04 16:00:00 141.154.195.129 - W3SVC1 SP6018ASP2 208.254.37.191 443 GET /rkadqsr/newskills/newskills.cfm selectedTab=1 200 0 53440 599 1594 HTTP/1.1 adqsr.skillport.com Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1) CookiesEnabled=1;+ASPSESSIONIDACTSSRAT=MCNLNLGADPOFGFKAHJHLDDKG;+CFID=785030;+CFTOKEN=27203160 https://adqsr.skillport.com/rkadqsr/login/login.cfm 2005-04-04 16:00:00 208.254.38.216 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST /_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 274 4547 HTTP/1.0 adqsr.skillport.com aiccisapi - - 2005-04-04 16:00:00 208.254.38.240 - W3SVC1 SP6018ASP2 208.254.37.191 443 POST /_rkadqsrBackend_od_cgi/aiccisapi.dll - 200 0 372 3019 250 HTTP/1.0 adqsr.skillport.com aiccisapi - - import datetime, time import Gnuplot dataPath = 'ex05040416.log' datasets = {} startTime = None f = open(dataPath) for line in f: try: dat, tim, c_ip, cs_username, s_sitename, s_computername, s_ip, s_port, \ cs_method, cs_uri_stem, cs_uri_query, sc_status, sc_win32_status, sc_bytes, \ cs_bytes, time_taken, cs_version, cs_host, cs_User_Agent, cs_Cookie, cs_Referer = line.split() except ValueError: print "Can't parse", line continue tim = time.mktime(time.strptime(dat+' '+tim, "%Y-%m-%d %H:%M:%S")) delay = int(time_taken) if startTime is None: startTime = tim tim -= startTime #print tim, delay datasets.setdefault(sc_status, []).append([tim, delay]) g = Gnuplot.Gnuplot(debug=1) plotter = g.plot for key, values in datasets.items(): plotter(values) plotter = g.replot raw_input('Please press return to continue...\n') -- http://mail.python.org/mailman/listinfo/python-list
Re: sort problem
Michele Petrazzo wrote: > Lasse Vågsæther Karlsen wrote: > >> How about: >> >> list.sort(key=lambda x: x[3]) Better to use key=operator.itemgetter(3) > Yes, on my linux-test-box it work, but I my developer pc I don't have > the 2.4 yet. I think that this is a good reason for update :) or learn about decorate-sort-undecorate: lst = [ ...whatever ] lst = [ x[3], i, x for i, x in enumerate(lst) ] lst.sort() lst = [ x for _, _, x in lst ] Kent > > Thanks, > Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on re.IGNORECASE
[EMAIL PROTECTED] wrote: > Hi, > > I'm having some problems with basic RE in python. I was wondering > whether > somebody could provide a hint on what's going wrong with the following > script. Comments are included. > > TIA. > -myself > > >>python2.3 > > Python 2.3.4 (#1, Nov 18 2004, 13:39:30) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-39)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import re >>>>pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$') >>>>pattern.search("GGHTTP/1.1 200 OK\r\n", re.IGNORECASE) > > <_sre.SRE_Match object at 0xb75c6ed0> > >>>>pattern.search("GHTTP/1.1 200 OK\r\n", re.IGNORECASE) > > # this makes no sense to me. Why is the previous line matched Because the second argument to pattern.search() is the position where the search starts, not a flag. re.IGNORECASE == 2 so your search is skipping the first two chars. Try giving the flags as a second argument to re.compile(): >>> import re >>> re.IGNORECASE 2 >>> pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$', re.IGNORECASE) >>> pattern.search("GGHTTP/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x00965980> >>> pattern.search("GHTTP/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x009659D0> >>> pattern.search("Ghttp/1.1 200 OK\r\n") <_sre.SRE_Match object at 0x009651B0> Kent > # and this not? > >>>>pattern.search("GHTTP/1.1 200 OK\r\n") > > <_sre.SRE_Match object at 0xb758d020> > -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Beginning Python (Practical Python 2.0)
Magnus Lie Hetland wrote: > I guess it has actually been out for a while -- I just haven't > received my copies yet... Anyways: My book, "Beginning Python: From > Novice to Professional" (Apress, 2005) is now out. Apress is offering a $10 rebate if you purchase the book before October 30. See for example http://www.bookpool.com/sm/159059519X Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Binding a variable?
Paul Dale wrote: > > Hi everyone, > > Is it possible to bind a list member or variable to a variable such that No, Python variables don't work that way. > > temp = 5 The name 'temp' is now bound to the integer 5. Think of temp as a pointer to an integer object with value 5. > > list = [ temp ] the name 'list' is bound to a list whose only member is a reference to the integer 5 > > temp == 6 Ok now temp is bound to a new integer, but the list hasn't changed - it's member is still a reference to 5 > > list > > would show > > list = [ 6 ] You have to put a mutable object into the list - something whose state you can change. For example this works, because temp and lst[0] are references to the same mutable (changeable) list: >>> temp = [6] >>> lst = [temp] >>> lst [[6]] >>> temp[0] = 5 >>> lst [[5]] Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: need some advice on x y plot
[EMAIL PROTECTED] wrote: > i am running a query on a database and making a list of time, value > pairs > kinda like this > plot_points = ([time, value], [time, value], [time, value]) > gnuplot complains that it needs a float for one of the values. > i can plot just the value, and it shows up ( no x value found) > > how should i proceed? Convert one of the values to a float? What are your time and value numbers? Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect os.system output
jas wrote: > I would like to redirect the output from os.system to a variable, but > am having trouble. I tried using os.popen(..).read() ...but that > doesn't give me exactly what i want. Here is an example using subprocess: http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en&; Kent > > ..this is windows by the way. > > For example: > tmp = os.popen("hostname").read() > > ...works as expected. > > however, > > tmp = os.popen("cmd").read() > ...i would like to have access to the cmd process...i.e. enter commands > like a normal command line. os.system() allows this, but i dont want > output to the screen..i wanna store it to a variable. then send > content of variable elsewhere, receive more input and submit it. > almost emulate the windows command prompt. > > any ideas? > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Casey Hawthorne wrote: > I have heard, but have not been able to verify that if a program is > about > 10,000 lines in C++ > it is about > 5,000 lines in Java > and it is about > 3,000 lines in Python (Ruby to?) My experience is that Java:Python is roughly 2:1, the highest I have seen (on small bits of code) is 3:1. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: coloring a complex number
Arthur wrote: > Spending the morning avoiding responsibilities, and seeing what it would > take to color some complex numbers. > > class color_complex(complex): > def __init__(self,*args,**kws): > complex.__init__(*args) > self.color=kws.get('color', 'BLUE') In general when you subclass an immutable type you have to override __new__ rather than __init__. There is some explanation and example here: http://www.python.org/2.2.3/descrintro.html#__new__ Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Bryan wrote: > i would not say sion's ratio of 5:1 is dubious. for what it's worth, > i've written i pretty complex program in jython over the last year. > jython compiles to java source code and the number of generated java > lines to the jython lines is 4:1. Ugh. The code generated by jythonc is *nothing like* the code you would write by hand to do the same thing. This is a meaningless comparison. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Module Importing Question
James Stroud wrote: > Hello All, > > I have two modules that I use interchangably depending on the circumstances. > These modules are imported by yet another module. I want the "importation" of > these two alternatives to be mutually exclusive and dependent on the state of > the "outermost module" > > A diagram: > > mainApp ==imports==> aModule ==imports==> [oneMod | orTheOtherMod] > > I want the importing of oneMod or orTheOtherMod to depend on the state of the > mainApp. aModule is frozen, as are oneMod and orTheOtherMod. How might I > accomplish this? I don't know what you mean by frozen, so maybe this is no good, but I would avoid having aModule look back at the state of mainApp. Instead use another module to communicate state. This could be a simple as # in mainApp import helper if something: import oneMod as theMod else: import orTheOtherMod as theMod helper.theMod = theMod import aModule # in aModule import helper.theMod as theMod theMod.someFunction() Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about inheritance...
KraftDiner wrote: > This is what I've got so far: > class Rect(Shape): > def __init__(self): > super(self.__class__, self).__init__() Should be super(Rect, self).__init__() > def render(self): > super(self.__class__, self).render() ditto In this example it doesn't make any difference but with a deeper inheritance hierachy it does. See http://www.python.org/2.2.3/descrintro.html#cooperation Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky Areas in Python
Steven D'Aprano wrote: > Alex Martelli wrote: > Those two are easy. However, and this is where I show my hard-won > ignorance, and admit that I don't see the problem with the property > examples: > >> class Base(object) >> def getFoo(self): ... >> def setFoo(self): ... >> foo = property(getFoo, setFoo) >> >> class Derived(Base): >> def getFoo(self): > > > Unless the answer is "Why are you using setters and getters anyway? This > isn't Java you know." > > Oh wait! Yes I do... the setter doesn't actually take an argument to set > the property too. Is that it, or have a missed a cunningly hidden deeper > problem? Derived.getFoo() will not override the use of Base.getFoo() to access the attribute foo. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: High Order Messages in Python
[EMAIL PROTECTED] wrote: > counting that out(regardless whether it is (dis)advantage or not), what > else a block can do but not a named function ? My limited understanding is that the advantage is - simpler syntax - high level of integration into the standard library (*many* methods that take closure arguments). Blocks are used not just for iteration but for the kinds of things shown in the examples to PEP 343 http://www.python.org/peps/pep-0343.html For example to open a file and read from it uses two closures, one to wrap a block with the file open/close, one to iterate lines (from the pickaxe book): File.open("testfile") do |file| file.each_line { |line| puts line } end Kent > > Alex Martelli wrote: > >>[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >> >> >>>could someone enlighten me what is the advantage of block over named >>>function ? >>> >>>One thing that I can see a difference may be lexical scope ? >> >>"Yes, but" -- according to the latest Ruby book, the "mixed lexical >>scope" of blocks is a highly controversial notion in the Ruby community; >>so I wouldn't necessarily count it as an _advantage_ of Ruby blocks... >> >> >>Alex > > -- http://mail.python.org/mailman/listinfo/python-list
Re: output from external commands
darren kirby wrote: > quoth the James Colannino: >>So, for example, in Perl I could do something like: >> >>@files = `ls`; >> >>So I guess I'm looking for something similiar to the backticks in Perl. >>Forgive me if I've asked something that's a bit basic for this list. >>Any help would be greatly appreciated :) Thanks very much in advance. > > > If all you want is filenames this will work: > >>>>import glob >>>>files = ["%s" % f for f in glob.glob("*")] or import os files = os.listdir('.') Python has built-in support for many file manipulations, see the os, os.path and shutil modules. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect os.system output
jas wrote: > Any other ideas? or examples of using subprocess to do what I was > asking? Actually I thought I was giving an example of what you were asking: - on windows - send a series of commands to a command process - capture the result to a variable The example I referenced sends a series of HELP commands to cmd.exe, captures the output of the commands and saves it to a file. What did I miss? Kent > > > Kent Johnson wrote: > >>jas wrote: >> >>>I would like to redirect the output from os.system to a variable, but >>>am having trouble. I tried using os.popen(..).read() ...but that >>>doesn't give me exactly what i want. >> >>Here is an example using subprocess: >>http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en&; >> >>Kent >> >> >>>..this is windows by the way. >>> >>>For example: >>>tmp = os.popen("hostname").read() >>> >>>...works as expected. >>> >>>however, >>> >>>tmp = os.popen("cmd").read() >>>...i would like to have access to the cmd process...i.e. enter commands >>>like a normal command line. os.system() allows this, but i dont want >>>output to the screen..i wanna store it to a variable. then send >>>content of variable elsewhere, receive more input and submit it. >>>almost emulate the windows command prompt. >>> >>>any ideas? >>> > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect os.system output
jas wrote: > Ok, I tried this... > > C:\>python > Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import subprocess as sp >>>>p = sp.Popen("cmd", stdout=sp.PIPE) >>>> >>>>result = p.communicate("ipconfig") > > 'result' is not recognized as an internal or external command, > operable program or batch file. > > > > basically I was opening to send the "ipconfig" command to cmd.exe and > store the result in the "result" variable. But you can see there was > an error with result. This works for me: import subprocess as sp p = sp.Popen("ipconfig", stdout=sp.PIPE) result = p.communicate()[0] print result Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Tree Discovery (script, tool, __?)
Istvan Albert wrote: > All I can add to this is: > > - don't use SAX unless your document is huge > - don't use DOM unless someone is putting a gun to your head +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Scanning a file
[EMAIL PROTECTED] wrote: > I want to scan a file byte for byte for occurences of the the four byte > pattern 0x0100. data = sys.stdin.read() print data.count('\x00\x00\x01\x00') Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: OEM character set issue
Dennis Lee Bieber wrote: > On Fri, 28 Oct 2005 15:55:56 +0200, "Ladvánszky Károly" <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > >>On my hungarian Win2k, some of the accented characters of the file names >>appear incorrectly when Python is driven from the command line. However, >>they > > > The "MS-DOS" command window tends to use a different character > encoding than full "Windows" widgets. You can chaneg the encoding used by the command window with the chcp command. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: extracting numbers from a file, excluding fixed words
dawenliu wrote: > Hi, I have a file with this content: > xxx xx x xxx > 1 > 0 > 0 > 0 > 1 > 1 > 0 > (many more 1's and 0's to follow) > y yy yyy yy y yyy > > The x's and y's are FIXED and known words which I will ignore, such as > "This is the start of the file" and "This is the end of the file". The > digits 1 and 0 have UNKNOWN length. I want to extract the digits and > store them in a file. Any suggestions will be appreciated. > Off the top of my head (not tested): inf = open('input.txt') out = open('output.txt', 'w') skips = [ 'xxx xx x xxx', 'y yy yyy yy y yyy', ] for line in inf: for skip in skips: if skip in line: continue out.write(line) inf.close() out.close() Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Function returns none
[EMAIL PROTECTED] wrote: > I'm trying to write a website updating script, but when I run the > script, my function to search the DOM tree returns None instead of what > it should. When you call findelement() recursively you have to return the value from the recursive call to the next caller up. See example below. Kent > > I have this program: > > import sys > from xml.dom.minidom import parse > > > # search the tree for an element with a particular class > > def findelement(current, classtofind, topnode = None): > if topnode == None: topnode = current > > > > # if it's an xml element... > if current.nodeType == 1: > print current.nodeName, ':', current.getAttribute('class') > if current.getAttribute('class') == classtofind: > print 'Returning node:', current > return current > elif current.hasChildNodes(): > findelement(current.firstChild, classtofind, topnode) Should be return findelement(current.firstChild, classtofind, topnode) and similarly wherever you call findelement(). > elif current.nextSibling: > findelement(current.nextSibling, classtofind, topnode) > > elif (current.parentNode != topnode) \ > > and (current.parentNode.nextSibling != None): > > findelement(current.parentNode.nextSibling, classtofind, > topnode) > else: > > print 'Returning None...' > > return None > > # others (text, comment, etc) > > else: > > if current.nextSibling: > > findelement(current.nextSibling, classtofind, topnode) > > elif (current.parentNode != topnode) \ > > and (current.parentNode.nextSibling != None): > > findelement(current.parentNode.nextSibling, classtofind, > topnode) > else: > > print 'Returning None...' > > return None > > > > # parse the document > > blog = parse('/home/noah/dev/blog/template.html') > > > > # find a post > > postexample = findelement(blog.documentElement, 'post') > > > > print 'Got node: ', postexample > > - > > My output is this: > > - > html : > head : > title : > body : > h1 : > ul : > li : > h2 : > ol : > li : post > Returning node: > Got node:None > - > > The function finds the right element fine, and says it will return Element: li at -0x48599c74>, but the program gets None instead. What's > happening here? Any suggestions? > -- http://mail.python.org/mailman/listinfo/python-list
Re: frozenset/subclassing/keyword args
Mark E. Fenner wrote: > Speaking of which, in the docs at the bottom of the description of the > builtin set/frozenset, there is a link to a page describing differences > between the builtin sets and the sets module sets. This link is broken > locally and on the python.org docs. > Locally, it reads: > file:///usr/share/doc/python-docs-2.4.2/html/lib/module-comparison-to-builtin-set.html > > While it should read: > file:///usr/share/doc/python-docs-2.4.2/html/lib/comparison-to-builtin-set.html A little further down the page it says "See About this document... for information on suggesting changes." If you click the link there it will tell you how to submit a doc bug which is the best way to get this fixed. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Flat file, Python accessible database?
Karlo Lozovina wrote: > I've been Googling around for _small_, flat file (no server processes), > SQL-like database which can be easily access from Python. Speed and > perforamnce are of no issue, most important is that all data is contained > within single file and no server binary has to run in order to use the > dbase. Oh, and I'm using Python under Cygwin. Depending on what you mean by "SQL-like" you might like KirbyBase http://www.netpromi.com/kirbybase.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Object-Relational Mapping API for Python
Aquarius wrote: > I explored Java's Hibernate a bit and I was intrigued by how you can > map entity objects to database tables, preserving all the relations and > constraits. I am interested if there is something like this for Python > - I noticed some APIs in the "Cheeseshop", but most of them were alpha, > better, or seemed to be forsaken a long time ago. Can you recommend me > anything? > SQLObject, PyDO, Durus and Django's database API. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning multiple languages (question for general discussion)
John Salerno wrote: > I thought it might be interesting to get some opinions on when you know > when you're "done" learning a language. I've been learning C# for a few > months (albeit not intensively) and I feel I have a good grasp of the > language in general. Never? When you move on? You can become proficient in a couple of months but that is different from "expert" which is different from "knows everything there is to know". I have been using Python for several years and I still learn from the old hands in this news group. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this in Python?
Lad wrote: > Can you please explain in more details (1) choice? If you are using CGI you might be interested in the VoidSpace logintools which seems to handle much of this process. See http://www.voidspace.org.uk/python/logintools.html#no-login-no-access Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Class' Child Methods
Steve Holden wrote: > Andrea Gavana wrote: >> The class "Custom" has a lot of methods (functions), but the user >> won't call >> directly this class, he/she will call the MainClass class to construct >> the >> GUI app. However, all the methods that the user can call refer to the >> "Custom" class, not the MainClass class. That is, the methods that the >> user >> call should propagate to the "Custom" class. However, I know I can do: >> >> # Inside MainClass >> def SomeMethod(self, param): >> self.customwidget.SomeMethod(param) >> > It seems that what you need is a generic delegation. > > This pattern (in Python, anyway) makes use of the fact that if the > interpreter can't find a method or other attribute for an object it will > call the object's __getattr__() method. Another alternative is to delegate specific method by creating new attributes in MainClass. In MainClass.__init__() you can write self.SomeMethod = self.customwidget.SomeMethod to automatically delegate SomeMethod. You can do this from a list of method names: for method in [ 'SomeMethod', 'SomeOtherMethod' ]: setattr(self, method, getattr(self.customwidget, method)) This gives you more control over which methods are delegated - if there are some Custom methods that you do *not* want to expose in MainClass this might be a better approach. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: re sub help
[EMAIL PROTECTED] wrote: > hi > > i have a string : > a = > "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" > > inside the string, there are "\n". I don't want to substitute the '\n' > in between > the [startdelim] and [enddelim] to ''. I only want to get rid of the > '\n' everywhere else. Here is a solution using re.sub and a class that maintains state. It works when the input text contains multiple startdelim/enddelim pairs. import re a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n" * 2 class subber(object): def __init__(self): self.delimiterSeen = False def __call__(self, m): text = m.group() if text == 'startdelim': self.delimiterSeen = True return text if text == 'enddelim': self.delimiterSeen = False return text if self.delimiterSeen: return text return '' delimRe = re.compile('\n|startdelim|enddelim') newText = delimRe.sub(subber(), a) print repr(newText) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying source at runtime - jython case
Jan Gregor wrote: > Hello folks > > I want to apply changes in my source code without stopping jython > and JVM. Preferable are modifications directly to instances of > classes. My application is a desktop app using swing library. Can you be more specific? Python and Jython allow classes to be modified at runtime without changing the source code or compiling new code. For example you can add and remove methods and attributes from a class and change the base classes of a class. You can also modify individual instances of a class to change their attributes and behaviour independently of other instances of the class. What are you trying to do? For example see http://groups.google.com/group/comp.lang.python/browse_frm/thread/8f7d87975eab0ca4/18215f7ce8f5d609?rnum=15#18215f7ce8f5d609 http://groups.google.com/group/comp.lang.python/browse_frm/thread/a0b19b37ac48deaa/e599041de4b8feb0?rnum=22#e599041de4b8feb0 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: modifying source at runtime - jython case
Jan Gregor wrote: > my typical scenario is that my swing application is running, and i see > some error or chance for improvement - modify sources of app, stop and run > application again. > so task is to reload class defitions (from source files) and modify also > existing instances (their methods). Ok, I think my first reply completely missed the mark. IIUC what you want is hard. This recipe might help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Pylab and pyserial plot in real time
[EMAIL PROTECTED] wrote: > Hiya, > > I've got a PIC microcontroller reading me humidity data via rs232, this > is in ASCII format. I can view this data easily using hyperterminal or > pyserial and convert it to its value (relative humidty with ord(input)) > > But what im trying to do is plot the data in real time, ideally with > pylab - as it looks simple to use and simple is the way i want to go! > > My code is below, it doesnt show a graph, I was wondering whether > someone could suggest whats wrong? You have to call pylab.show() for the graph to be drawn. I don't know if it will work incrementally if you call show() in the loop. Kent > > thank you in advance > > David > > > > import serial > from pylab import * > > ser = serial.Serial(0) > t = arange(0.0, 1.0+0.01, 0.01) > > xlabel('time') > ylabel('RH %') > title(' RH sensor data sampled at 1 sec intervals ') > #grid(true) > > x = 0 > > while 1: > s = ser.read() > b = ord(s) > h = [] > h.append(b) > x = x + 1 > plot(t,h) > > ser.close > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: need help extracting data from a text file
[EMAIL PROTECTED] wrote: > Hey there, > i have a text file with a bunch of values scattered throughout it. > i am needing to pull out a value that is in parenthesis right after a > certain word, > like the first time the word 'foo' is found, retrieve the values in the > next set of parenthesis (bar) and it would return 'bar' > > i think i can use re to do this, but is there some easier way? It's pretty easy with an re: >>> import re >>> fooRe = re.compile(r'foo.*?\((.*?)\)') >>> fooRe.search('foo(bar)').group(1) 'bar' >>> fooRe.search('This is a foo bar baz blah blah (bar)').group(1) 'bar' Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression question -- exclude substring
[EMAIL PROTECTED] wrote: > Hi, > > I'm having trouble extracting substrings using regular expression. Here > is my problem: > > Want to find the substring that is immediately before a given > substring. For example: from > "00 noise1 01 noise2 00 target 01 target_mark", > want to get > "00 target 01" > which is before > "target_mark". > My regular expression > "(00.*?01) target_mark" > will extract > "00 noise1 01 noise2 00 target 01". If there is a character that can't appear in the bit between the numbers then use everything-but-that instead of . - for example if spaces can only appear as you show them, use "(00 [^ ]* 01) target_mark" or "(00 \S* 01) target_mark" Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression question -- exclude substring
James Stroud wrote: > On Monday 07 November 2005 16:18, [EMAIL PROTECTED] wrote: > >>Ya, for some reason your non-greedy "?" doesn't seem to be taking. >>This works: >> >>re.sub('(.*)(00.*?01) target_mark', r'\2', your_string) > > > The non-greedy is actually acting as expected. This is because non-greedy > operators are "forward looking", not "backward looking". So the non-greedy > finds the start of the first start-of-the-match it comes accross and then > finds the first occurrence of '01' that makes the complete match, otherwise > the greedy operator would match .* as much as it could, gobbling up all '01's > before the last because these match '.*'. For example: > > py> rgx = re.compile(r"(00.*01) target_mark") > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') > ['00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01'] > py> rgx = re.compile(r"(00.*?01) target_mark") > py> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') > ['00 noise1 01 noise2 00 target 01', '00 dowhat 01'] ??? not in my Python: >>> rgx = re.compile(r"(00.*01) target_mark") >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01'] >>> rgx = re.compile(r"(00.*?01) target_mark") >>> rgx.findall('00 noise1 01 noise2 00 target 01 target_mark 00 dowhat 01') ['00 noise1 01 noise2 00 target 01'] Since target_mark only occurs once in the string the greedy and non-greedy match is the same in this case. Kent -- http://mail.python.org/mailman/listinfo/python-list
Confusion about __call__ and attribute lookup
I am learning about metaclasses and there is something that confuses me. I understand that if I define a __call__ method for a class, then instances of the class become callable using function syntax: >>> class Foo(object): ... def __call__(self): ... print 'Called Foo' ... >>> f=Foo() >>> f() Called Foo To create a class instance, you call the class. This made me think that the class' class must define __call__, and indeed it does, and calling it as an unbound method also creates a class instance: >>> dir(type) [..., '__call__', ...] >>> f=type.__call__(Foo) >>> f <__main__.Foo object at 0x00A35EB0> But why doesn't Foo.__call__ shadow type.__call__? Normally an instance attribute takes precedence over a class attribute. Is it something special about how function call syntax is handled internally, or do all special methods work this way, or is there something else going on? PS Is there any place in the standard Python docs where the details of attribute lookup are spelled out? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion about __call__ and attribute lookup
Leif K-Brooks wrote: > New-style classes look up special methods on the class, not on the instance: For my future reference, is this documented somewhere in the standard docs? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Confusion about __call__ and attribute lookup
John J. Lee wrote: > Kent Johnson <[EMAIL PROTECTED]> writes: > >>Leif K-Brooks wrote: >> >>>New-style classes look up special methods on the class, not on the instance: >> >>For my future reference, is this documented somewhere in the standard docs? > > Maybe somewhere in here :-( > > http://www.python.org/doc/newstyle.html I have never found it there. I think something like the writeup Serge referenced should be in the language reference. I just sent the suggestion to [EMAIL PROTECTED] Thanks to both of you, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Book
David Rasmussen wrote: > What is the best book for Python newbies (seasoned programmer in other > languages)? I like Learning Python. Python in a Nutshell is good if you want something brief. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: generate HTML
Jim wrote: > Perhaps you are trying to do this: > 'text to go here: %s' % ('text',) > ? For that you need a double-quoted string: > "text to go here: %s" % ('text',) Uh, no, not in Python: >>> 'text to go here: %s' % ('text',) 'text to go here: text' >>> "text to go here: %s" % ('text',) 'text to go here: text' Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Need advice on subclassing code
Rusty Shackleford wrote: > Hi -- > > We have some code that returns an object of a different class, depending > on some parameters. For example: > > if param x is 1 and y is 1, we make an object of class C_1_1. > if param x is 1 and y is 2, we make an object of class C_1_2. > > C_1_1 and C_1_2 share a common C ancestor, and in practice may be > identical, but theoretically, could have the same function name with two > different implementations underneath. > > We have a file where all the C_X_Y classes are defined. > Is this the best solution? Is there some way of doing a default vs. > non-default deal, without having to manually hardcode all the different > possible subclasses? How are you instantiating the correct class? You should be able to provide a default behaviour. For example if the classes are all defined in module C you could have a factory like this: import C def makeC(x, y): subtype = 'C_%d_%d' % (x, y) cls = getattr(C, subtype, C.C) return cls(x, y) Then in module C just define the subtypes you need to specialize; all other values of x and y will get the base class C.C. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for files on Windows with Python
Shane wrote: > I've been giving Google a good workout with no luck. I would like to > be able to search a Windows filesystem for filenames, returning a > list off absolute paths to the found files, something like:> > def findFiles(filename, pathToSearch): > ... > ... > return foundFileNames > > Is the os module where I should start? I always use Jason Orendorff's path module for this kind of stuff. It's way easier to use than os.whatever: import path files = path.path(pathToSearch).walkfiles(filename) will give a list of path.path objects in pathToSearch whose names match filename (which is a glob so wildcards are recognized). path.path is a subclass of str so the results can be used wherever you want the full path. http://www.jorendorff.com/articles/python/path/index.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for files on Windows with Python
Peter Hansen wrote: > Kent Johnson wrote: >> import path >> files = path.path(pathToSearch).walkfiles(filename) > > A minor enhancement (IMHO) (though I certainly agree with Kent's > recommendation here): since there is nothing else of interest in the > "path" module, it seems to be a fairly common idiom to do "from path > import path" and skip the doubled "path.path" bit. Certainly it's your choice. I find most programs using path only reference path.path once, to create a starting path; other paths are created from that using files() or / etc. In this case it is less typing to say import path basePath = path.path(...) instead of from path import path basePath = path(...) from path import path only wins on number of chars if you reference path *three* times. YMMV :-) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Web-based client code execution
Stephen Kellett wrote: > In message <[EMAIL PROTECTED]>, Steve > <[EMAIL PROTECTED]> writes > >> AJAX works because browsers can execute javascript. I don't know of a >> browser that can execute python. Basically your stuck with java or >> javascript because everything else really isn't cross platform. > > > ActiveState do a version of Python that can run in a script tag like > JavaScript and VBScript. This requires Windows Scripting Host. They also > do a similar thing for Perl, not sure about TCL. See http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to create a button in either pygame or livewires?
Nathan Pinno wrote: > Hey all, > > Is there a way to create a button in either pygame or livewires, that is > able to be clicked and when clicked sends a command to restart the program? Maybe something here: http://www.pygame.org/wiki/gui Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Web-based client code execution
Paul Watson wrote: > Kent Johnson wrote: >> Stephen Kellett wrote: >>> ActiveState do a version of Python that can run in a script tag like >>> JavaScript and VBScript. This requires Windows Scripting Host. They >>> also do a similar thing for Perl, not sure about TCL. >> >> See >> http://groups.google.com/group/comp.lang.python/msg/2d34acee66b40830 > > Please correct my misunderstanding if I am wrong, but I thought that > this runs server-side only and requires Microsoft IIS as the httpd > server. Is that correct? I haven't tried it but the referenced article seems to be about including Python in a web page to be run in-browser by IE. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Web-based client code execution
Paul Watson wrote: > My desire to have the code distributed through a web page is just to > ensure that the user is running the correct version and has not hacked > it in any way. I suppose I can checksum the local client application > and compare it with what is on the server. Then, make a way to > update... ARGH! I have used Java Web Start to distribute Jython applications from a web page. There are a few glitches getting it set up but then it works well. Solves 'ensure that the user is running the correct version' nicely. Not sure if it protects against hacking. My Jython and Web Start recipe is here: http://personalpages.tds.net/~kent37/Python/JythonWebStart.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Persist a class (not an instance)
Is there a way to persist a class definition (not a class instance, the actual class) so it can be restored later? A naive approach using pickle doesn't work: >>> import pickle >>> class Foo(object): ... def show(self): ... print "I'm a Foo" ... >>> p = pickle.dumps(Foo) >>> p 'c__main__\nFoo\np0\n.' Hmm, doesn't look too promising. In a new interpreter: >>> import pickle >>> p='c__main__\nFoo\np0\n.' >>> Foo = pickle.loads(p) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "C:\Python24\lib\pickle.py", line 872, in load dispatch[key](self) File "C:\Python24\lib\pickle.py", line 1104, in load_global klass = self.find_class(module, name) File "C:\Python24\lib\pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'Foo' The idea is to persist classes that are created and modified at runtime. Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Python book for a non-programmer
Simon Brunning wrote: > I have a non-programming friend who wants to learn Python. It's been > so long since I've been in her shoes that I don't feel qualified to > judge the books aimed at people in her situation. Python Programming for the absolute beginner http://premierpressbooks.com/ptr_detail.cfm?group=Programming&isbn=1%2D59200%2D073%2D8 Python Programming: An Introduction to Computer Science http://www.fbeedle.com/99-6.html And the Introductory Books page in the wiki lists many: http://wiki.python.org/moin/IntroductoryBooks Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Persist a class (not an instance)
Sybren Stuvel wrote: > Kent Johnson enlightened us with: > >>Is there a way to persist a class definition (not a class instance, >>the actual class) so it can be restored later? > > > From the docs: > > "Similarly, classes are pickled by named reference, so the same > restrictions in the unpickling environment apply. Note that none of > the class's code or data is pickled [...]" OK that confirms that pickle won't work. Is there another approach that will? Kent -- http://mail.python.org/mailman/listinfo/python-list
No apos in htmlentitydefs
I see that htmlentitydefs.name2codepoint does not include 'apos' as one of the recognized names. Is this intentional or a bug? In fact ' is not a recognized entity in HTML 4.01; see this list: http://www.w3.org/TR/html4/sgml/entities.html#misc But it is recognized in XHTML 1.0: http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters and AFAIK it is commonly supported by browsers which IMO argues that it should be included. Any thoughts? Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for good beginner's tutorial
Roy Smith wrote: > My wife wants to learn Python. Can anybody suggest a good tutorial > for her to read? She's a PhD molecular biologist who is a pretty > advanced Unix user. She mucks about with Perl scripts doing things > like text processing and even some simple CGI scripts, but has no > formal programming training. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: How to list currently defined classes, methods etc
Deep wrote: > I have been looking a bit and am stuck at this point. > > Given a string, how do i find what is the string bound to. > Let me give an example. > > def deep(): > print "Hello" > > now inspect.ismethod(deep) returns true. (As it should). > But if I am trying to make a list of all bound methods), i use > dir(), which is a list of strings. I get the string "deep" from this > list. Look it up in the globals() dict: >>> def deep(): ... print 'Hello' ... >>> globals()['deep'] > How do I obtain the reference to the method it is bound to. > The same problem can be extended to attributes and classes. Use getattr() to inspect classes and instances: >>> class deeper: ... def deepest(self): ... print 'goodbye' ... >>> getattr(deeper, 'deepest') >>> d=deeper() >>> getattr(d, 'deepest') > Kent -- http://mail.python.org/mailman/listinfo/python-list
CDDB.py binaries for Python 2.4
Howdy, I'm using Python 2.4 on W2K I would love to use the tools at http://cddb-py.sourceforge.net/ the newest Win binaries are for Python 2.0 The dll won't load, I assume this is due to version mismatch. I'm not set up with a C compiler. Does anyone know of a source of current binaries for this package? Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect character encoding
Martin P. Hellwig wrote: > I read or heard (can't remember the origin) that MS IE has a quite good > implementation of guessing the language en character encoding of web > pages when there not or falsely specified. Yes, I think that's right. In my experience MS Word does a very good job of guessing the encoding of text files. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there an equivalent to Java Webstart in Python?
Nic Bar wrote: > The problem with Jython is that I can only live inside the aplet > virtual machine, Only if you are writing an applet. > I need a full features application with access to the local computer > resources. You can do this with Jython and JWS. Write your app in Jython, deploy with JWS, be happy, go home early ;) I have some notes about it here: http://personalpages.tds.net/~kent37/Python/JythonWebStart.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there an equivalent to Java Webstart in Python?
Renato wrote: > What use is Java WebStart, exactly? It's a way to deploy a Java app from a web site. Assuming the user has Java installed, the app can be launched just by clicking a link on a web page. The jar files are cached locally so they are only downloaded once, the user can make desktop and Start menu shortcuts for the app, and you can update users automatically by deploying new jars to the web server. It's pretty nice and largely trouble-free. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there an equivalent to Java Webstart in Python?
Ravi Teja wrote: > Hi Kent, > Too complicated example :-). Jythonc works just fine to create a > regular jar file that you can reference in your jnlp file. If it works for you, good. I have never been able to compile a real app with jythonc and I gave up on it long ago. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
Steve Holden wrote: > BartlebyScrivener wrote: >> Now you are on a page with promising-looking links that all start with >> "BeginnersGuide," but the first three are not warm welcomes, they are >> housekeeping matters about where you can take courses or how to >> download Python for people who don't know whether they want to or not >> yet, or there's one that says "examples" which will take you to the >> ActiveState Cookbook site so you can get really confused. > I think the Python community as a whole should take this on board as > fair criticism. It would be really nice if a total beginner did actually > see a usable path through the web to their first working Python program. OK I'll bite. That Beginners Guide page has bugged me for a long time. It's a wiki page but it is marked as immutable so I can't change it. Here are some immediate suggestions: - get rid of the 1-7 list at the top it is very confusing and does not present information in a useful form or order. All of these links except the help link appear in the body text in more useful form. - Change the sentence "Read BeginnersGuide/Overview to learn the key points." to "Read BeginnersGuide/Overview to learn what makes Python special." Or maybe get rid of it completely - I'm not sure evangelism belongs on this page. - Add a sentence at the end of the paragraph that starts, "Once you've read a tutorial" that says, "Many other resources are listed in BeginnersGuide/Help." On the BeginnersGuide/NonProgrammers page, I agree, Guido's tutorial probably shouldn't be listed first even with the disclaimer. It goes way to fast for a beginner. Alan Gauld's tutorial is very popular on the tutor list, so is A Byte of Python (which is not listed on the NonProgrammers page). I would list them first. Or maybe take a vote on the tutor list for favorite beginner's tutorial. That should help a little, maybe we won't confuse the newbies before they even get to an interpreter prompt. Kent PS I am aware of the usual SF bug report procedure for docs, does it apply to these pages? I don't know, they don't have the usual "About this document" link at the bottom. I'm happy to submit a patch if that will help. Otherwise I'm not sure what "the Python community as a whole [taking] this on board" should look like. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutability of function arguments?
Mike Meyer wrote: > "ex_ottoyuhr" <[EMAIL PROTECTED]> writes: > >>I'm trying to create a function that can take arguments, say, foo and >>bar, and modify the original copies of foo and bar as well as its local >>versions -- the equivalent of C++ funct(&foo, &bar). > > > C++'s '&' causes an argument to be passed by reference. Python does > that with all arguments. Any changes you make to the argument in the > function will be seen in the caller unless you explicitly make a copy > to pass. I would say, from the point of view of a C++ programmer, Python passes references by value. In other words if you think of variables as pointers (references) to values, and function call as passing the reference by value, the behaviour of Python makes sense. Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding of file names
utabintarbo wrote: > Here is my situation: > > I am trying to programatically access files created on an IBM AIX > system, stored on a Sun OS 5.8 fileserver, through a samba-mapped drive > on a Win32 system. Not confused? OK, let's move on... ;-) > > When I ask for an os.listdir() of a relevant directory, I get filenames > with embedded escaped characters (ex. > 'F07JS41C.04389525AA.UPR\xa6INR.E\xa6C-P.D11.081305.P2.KPF.model') > which will read as "False" when applying an os.path.isfile() to it. I > wish to apply some operations to these files, but am unable, since > python (on Win32, at least) does not recognize this as a valid > filename. Just to eliminate the obvious, you are calling os.path.join() with the parent name before calling isfile(), yes? Something like for f in os.listdir(someDir): fp = os.path.join(someDir, f) if os.path.isfile(fp): ... Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
A.M. Kuchling wrote: > On Wed, 07 Dec 2005 12:10:18 -0500, > Kent Johnson <[EMAIL PROTECTED]> wrote: > >>OK I'll bite. That Beginners Guide page has bugged me for a long time. >>It's a wiki page but it is marked as immutable so I can't change it. >>Here are some immediate suggestions: > > > Good suggestions; thanks! I've applied most of them. Thanks, this is a big improvement. Here are a few more ideas: - change "Next, you need to get the Python interpreter installed on your computer." to "Next, install the Python interpreter on your computer." (active voice) - move and rewrite the "You'll want to select a [WWW] text editor..." sentence. For a raw beginner, this is not the next step and the page it links to will not be helpful. Tutorials generally start out at the interpreter prompt, not writing programs in an editor. Whatever editor is handy and familiar is probably fine for a first program when the time comes. Here is a suggested rewrite: "When you are ready to write your first program you will need a text editor. To get started you can use any editor you are familiar with such as NotePad or . As you gain experience you may want to use a text editors with features that help you write Python programs. A comprehensive list is here ." I think I would put this before the paragraph beginning "Once you've read a tutorial". - Move the "Need to know how to run Python programs on Windows?" sentence to the last bullet of the list in the next paragraph and rewrite it to "Most tutorials assume you know how to run a program on your computer. If you are using Windows and need help with this, see ." - Change "Next, you're going to want to read a tutorial" to "Next, read a tutorial" With these changes the first links on this page are BG/Overview, BG/Download and BG/NonProgrammers. The second link on BG/NonProgrammers is a reasonable tutorial and the first link is pretty obviously one to skip. So a beginner is guided through the necessary steps with nothing extra or distracting or overwhelming intervening. >>- Change the sentence "Read BeginnersGuide/Overview to learn the key >>> points." to "Read BeginnersGuide/Overview to learn what makes Python >>> special." Or maybe get rid of it completely - I'm not sure evangelism >>> belongs on this page. > > > Yes, it does; fairly often the webmaster alias receives e-mails that > ask "so what is Python?" Direct them to the "What is Python?" link on the front page maybe? ISTM the material in BG/Overview belongs on the pages linked from "What is Python?" Thanks, Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Steven D'Aprano wrote: > On Wed, 07 Dec 2005 23:58:02 -0500, Mike Meyer wrote: >>>1) The stmt "board.Blist[10].DrawQueen(board.Blist[10].b1)" seems >>>awkward. Is there another way (cleaner, more intuitive) to get the >>>same thing done? >> >>Yes. Reaching through objects to do things is usually a bad idea. > > > I don't necessarily disagree, but I don't understand why you say this. Why > it is bad? http://en.wikipedia.org/wiki/Law_of_Demeter Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect the presence of a html file
Phoe6 wrote: > Operating System: Windows > Python version: 2.4 > > I have bookmarks.html and wumpus.c under my c: > > When I tried to check the presence of the bookmarks.html, I fail. > > >>>>os.path.isfile('c:\bookmarks.html') > > False > >>>>os.path.isfile('c:\wumpus.c') > > True The problem is that \ is special in string literals. \b is a backspace character, not the two-character sequence you expect. \w has no special meaning so it *is* the two-character sequence you expect. >>> len('\b') 1 >>> len('\w') 2 The simplest fix is to use raw strings for all your Windows path needs: os.path.isfile(r'c:\bookmarks.html') os.path.isfile(r'c:\wumpus.c') In raw strings the only \ escapes are \' and \", everything else is left alone. >>> len(r'\b') 2 >>> len(r'\w') 2 Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Catching error text like that shown in console?
Peter A. Schott wrote: > I know there's got to be an easy way to do this - I want a way to catch the > error text that would normally be shown in an interactive session and put that > value into a string I can use later. I've tried just using a catch statement > and trying to convert the output to string, but this doesn't always work. I > really don't have programs complex enough to do a lot of specific catching at > this point - I just want to know: > 1. something failed > 2. here's the error output/traceback If you just want to catch exceptions and print a traceback, use the traceback module. This is handy for example if you are processing a number of items and don't want a failure in one to abort the whole loop: import traceback for work in thingsToDo: try: doSomeWork(work) except: traceback.print_exc() If you want more control over the exception info - for example to put it in a string instead of printing it - look at the other functions in the traceback module. Kent -- http://mail.python.org/mailman/listinfo/python-list