Re: [Tutor] Help with objects
On Mon, 21 Nov 2005, Vincent Wan wrote: > Thank you bob. I fixed the errors where I tried to index a dictionary > with name() so so that they say name[] > > >> Beyond the error I'm still not sure I understand how to make and use > >> a tree data structure using objects. > > There is a new error as well > > Traceback (most recent call last): >File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- > currentTree = Tree() >File "/Users/Wally/obj_tree1.py", line 21, in __init__ > nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree > NameError: global name 'nodeList' is not defined Hi Vincent, You may want to look at places in your code where assigning nodeList does appear to work. For example, Node.__init__ appears to do: Tree.nodeList[self.name] = self Check the line that's raising an error: nodeList[0] = Tree.Node(0) as well as the content of the error message: NameError: global name 'nodeList' is not defined Do you understand what the error message is trying to say? You may also want to go through a formal tutorial that talks about data structures like trees. For example, How to Think like a Computer Scientist has a whole chapter on trees: http://www.ibiblio.org/obp/thinkCSpy/chap20.htm Although this concentrates on binary trees, the examples can be adjusted to do an arbitrary tree of any branching width. Rather than have each node have a link to their 'left' and 'right' children, we can do links to the "first child" and "next sibling". The implementation you have should be fine, but I did promise you an alternative implementation of trees. As a quick and dirty example of what this might look like, I'll strip it down so that there's minimal class stuff. ## class Node: def __init__(self, id): self.id = id self.firstChild = None self.nextSibling = None def addChild(node, childId): child = Node(childId) child.nextSibling = node.firstChild node.firstChild = child return child ## (The only reason I'm making a class definition at all is just to treat it as a data structure with labeled attributes. But everything else I write here will be a function, since you probably have a good foundation with them.) Once we have something like this, then if we wanted to represent a node with three children: 1 /|\ / | \ 2 3 4 then we can do something like this: ## >>> node1 = Node(1) >>> addChild(node1, 2) <__main__.Node instance at 0x733a0> >>> addChild(node1, 3) <__main__.Node instance at 0x73620> >>> addChild(node1, 4) <__main__.Node instance at 0x737d8> ## Does this work? Let's inspect what we have so far: ## >>> node1.firstChild <__main__.Node instance at 0x73558> >>> node1.firstChild.id 4 >>> node1.firstChild.nextSibling.id 3 >>> node1.firstChild.nextSibling.nextSibling.id 2 >>> >>> node1.firstChild.nextSibling.nextSibling.nextSibling.id Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'id' ## There they are. And, of course, if we jump off the list, as in the last example, we'll get an error. We should be careful to look before jumping. If it seems awkward to go through the list of children like this, we can abstract away the linked list traversal by writing a helper function, like this: ## def children(node): """Returns the children of a node.""" children = [] child = node.firstChild while child != None: children.append(child) child = child.nextSibling return children ## And now we can more easily see that node1 has three children: ## >>> for child in children(node1): ...print child.id ... 4 3 2 ## The staticmethods and nested classes that you have now seem slightly over-the-top to me, which is why I'm trying to counterbalance that with the simplest generalized tree example I can think of. *grin* I guess I'm trying to say: if you're doing tree stuff, you don't even need to use much sophisticated class stuff --- I think that simple functions should suffice at the moment. Good luck to you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Delete an attribute using Beautiful Soup?
I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be exact. I see Tag.__delitem__(self, key), but I cannot seem to figure out how to use it. Any help? class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, name, attrs=None, parent=Null, previous=Null): "Basic constructor." self.name = name if attrs == None: attrs = [] self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] -- Bob Tanner <[EMAIL PROTECTED]> | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Delete an attribute using Beautiful Soup?
Bob Tanner wrote: > I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be > exact. I believe I answered my own question. Looking for confirmation this is the "right" solution. del(soup.body['bgcolor']) -- Bob Tanner <[EMAIL PROTECTED]> | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamic inheritance?
Hi, Kent Johnson wrote on 20.11.2005: > >Use getattr() to access attributes by name. SiteA is an attribute of >Templates and Page is an attribute of SiteA so you can get use >getattr() twice to get what you want: > >site = getattr(Templates, self.site_name) self.template = >getattr(site, self.template_type) > Unfortunately, this does not seem to work if Templates is a package, not a module. Python complains: AttributeError: 'module' object has no attribute 'SiteA' args = ("'module' object has no attribute 'SiteA'",) even though there is a module SiteA within package Templates. When manually importing SiteA from Templates, everything is good. >From your previous message, I read that modules are treated just like classes >or any other attribute - did I misinterpret your advice? Thanks, Jan -- I was gratified to be able to answer promptly, and I did. I said I didn't know. - Mark Twain ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Inheriting from parent object
Thanks for this. I hadn't really considered that I would have to explicitly store parent/child relationships. Having been browsing for something else, I came across this page about Unifying types and classes: http://www.python.org/2.2.3/descrintro.html >From it, it looks like I could do something like: class Page(object): def __init__(self, parent): self.__header = None self.parent = parent def getheader(self): if not self._header and self.parent: return self.parent.header else: return self.__header def setheader(self, header): self.__header = header header = property(getheader, setheader) Which I think would end up doing exactly what I want. I still don't think I'm clear on the use of self though. Can I only use it in class definitions? I think it might be that myPage = Page(parentPage) is highly deceptive. Shouldn't it really be: new Page(myPage, parentPage) or myPage = new Page(myPage, parentPage) or am I getting really, really confused? Ed On 15/11/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > >>Sorry, I didn't really explain myself clearly. > > Thats OK its easy to get buried in the depths and > forget everyone else is coming at it cold. But > the use of non standard terms confused things > even more! > > >>I want to create a kind of website ... > >>I want to have a root object, which > >>has page objects. The page objects > > will have various properties > >like header, footer, body and an order > > Sounds like a job for classes. Create a > Page class with the various properties. > Initialise objects with their parent > (ie containing) object. > > >>to inherit the attribute from their parent page (ie if it is > >>root.chapter3.page5 then chapter3 is the parent of page5). > > >>I guess the psuedo code would be: > >> > >>def inherit() > >>return this.parent.attribute > >> > > Just put code like this in the init method: > > Class Page: >def __init__(self, parent = None): > self.parent = parent # and handle default too! >def getHeader(self): > return self.parent.header > > etc... > > Then create > > Chapter3 = Page() > Chapter3.header = '''some long string here''' > Chapter3.getHeader() > p2 = Page(Chapter3) > p2.getHeader() # returns Chapter3.header > > etc > > >>(I know Python doesn't really have a 'this' > > But it does have self and you can use > this if you prefer! > > > >>knowing who the function was called by). > > Thats not really needed if you use objects. > Although self does point at the specific > Page whose method is being invoked. > > HTH, > > Alan G > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Application Templates?
I am about to start work on my first significant coding projects in some time (and first ever in python). Does anyone have any standard templates that they use to lay out new projects that they might be willing to share? By templates, I am not asking about complex libraries and OO things that I don't fully understand, but rather a file that sets up a common base for applications like file handling, customary command line handling and such things. Essentially a file that you can start plugging your core logic into and start working from. Thanks, Andy ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with objects
At 09:04 PM 11/21/2005, Vincent Wan wrote: >Thank you bob. I fixed the errors where I tried to index a dictionary >with name() >so so that they say name[] > >>>Beyond the error I'm still not sure I understand how to make and >>>use a tree data structure using objects. > >There is a new error as well > >Traceback (most recent call last): > File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- > currentTree = Tree() > File "/Users/Wally/obj_tree1.py", line 21, in __init__ > nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree >NameError: global name 'nodeList' is not defined > >Code with error bob fixed fixed throughout > ># obj_tree1.py > >import random > ># constants that control the simulation >NUMBER_REPS = 10# run's the simulation >MAX_LINAGES = 10# number of species in each run >BRANCHING_PROBABILITY = 0.5 > >class Tree(object): > numLinages = 0# keeps track of how many nodes there are > nodeList = {}# keeps track of the nodes nodeList is a property of class Tree. > class Node(object): > def __init__(self, name): > self.name = name# an integer > self.alive = True > self.descendents = {}# nodes descending from self > Tree.numLinages += 1# records node creation > Tree.nodeList[self.name] = self# makes node > accesable from tree > def __init__(self): > nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree To refer to a property of the class: Tree.nodeList[0] = Tree.Node(0)# adds a root node 0 to the tree > def AddBranch(self, offspring): > self.descendents[offspring] = Tree.Node(offspring)# > adds a descendent node > def NumLinages( ): > return Tree.numLinages > NumLinages = staticmethod(NumLinages) > >currentTree = Tree() > >for i in range(NUMBER_REPS): > j = 0 > while j <= currentTree.NumLinages(): # checks all node because >their names are sequential integers > if j.alive: > if random.random() >= BRANCHING_PROBABILITY: > currentTree.AddBranch(j, (currentTree.NumLinages() + >1)) # creates a new node > j += 1 > >Thank you for the help > > >Vincent Wan > > >-- >PhD Candidate >Committee on the Conceptual and Historical Studies of Science >University of Chicago > >PO Box 73727 >Fairbanks, AK 99707 > >wan AT walrus DOT us (change CAPS to @ and . ) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] about global definition
>>I have a code here. I understand i can not draw lines without the >>global definition of lastX and lastY. But still confused by its use. >>when should we use global definition? If you don't use classes then you will need to use global variables any time you want to pass information between functions and the functions have a predetermined interface that precludes making the data parameters. Thus in your case the callback click(event) can only take the one parameter, event so you must use global variables. Similarly you need to use globals where you need to maintain state between function calls (even of the same function) Otherwisde you should be able to avoid globals. Using OOP allows you to hide the global functions inside an object which solves both of the above problems. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamic inheritance?
Hi, Jan Eden wrote on 22.11.2005: >Hi, > >Kent Johnson wrote on 20.11.2005: >> >>Use getattr() to access attributes by name. SiteA is an attribute >>of Templates and Page is an attribute of SiteA so you can get use >>getattr() twice to get what you want: >> >>site = getattr(Templates, self.site_name) self.template = >>getattr(site, self.template_type) >> > >Unfortunately, this does not seem to work if Templates is a package, >not a module. Python complains: > >AttributeError: 'module' object has no attribute 'SiteA' > args = ("'module' object has no attribute 'SiteA'",) > >even though there is a module SiteA within package Templates. When >manually importing SiteA from Templates, everything is good. > Found a solution: import Templates #... def GetTemplates(self): __import__('Templates.', globals(), locals(), [self.identifier]) site = getattr(Templates, self.identifier) self.template = getattr(site, self.template_type) works. Thanks, Jan -- He who would give up a little liberty in return for a little security deserves neither liberty nor security. - Benjamin Franklin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python-ldap
I am new to python and fairly new to programming. I have written some ldap scripts in perl and am trying to learn how to do that in python. I found some code on the net using the python-ldap module (the unaltered code is at the bottom of this email) and have adapted it to my needs, the code works fine. I want to learn what some of the things in the code are. The two things I don't understand are ldap.SCOPE_SUBTREE and ldap.RES_SEARCH_ENTRY when I print those out I get integers 2 and 100 respectively, I am not sure if they change but that is what they start out at. I am figuring other modules use similar things (variables?), can someone point me to where I can understand what more about what these are. The help documentation didn't really explain about these. Thanks Pat code: import ldap ## first you must open a connection to the server try: l = ldap.open("127.0.0.1") ## searching doesn't require a bind in LDAP V3. If you're using LDAP v2, set the next line appropriately ## and do a bind as shown in the above example. # you can also set this to ldap.VERSION2 if you're using a v2 directory # you should set the next option to ldap.VERSION2 if you're using a v2 directory l.protocol_version = ldap.VERSION3 except ldap.LDAPError, e: print e # handle error however you like ## The next lines will also need to be changed to support your search requirements and directory baseDN = "ou=Customers, ou=Sales, o=anydomain.com" searchScope = ldap.SCOPE_SUBTREE ## retrieve all attributes - again adjust to your needs - see documentation for more options retrieveAttributes = None searchFilter = "cn=*jack*" try: ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: ## here you don't have to append to a list ## you could do whatever you want with the individual entry ## The appending to list is just for illustration. if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print result_set except ldap.LDAPError, e: print e ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Newbie question
I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work L).. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Problem using easy_install
Hi, I'm trying to get a handle on Python eggs using Easy Install. Because I'm behind an ISA server it seems that first I need to install NTLMAPS - as adviced by Easy Install How-to page. I did just that and I know it's working because I tested it with Firefox. Didn't manage to run ez_setup.py so decided to look elsewhere. Turned of the NTLMAPS server and. I've managed to install setuptools. But for this I had to use the manual installation (not the ez_setup.py bootstrap module). The install went along fine. Now came the problems. Trying to install SQLObject I got: Z:\setuptools-0.6a8>C:\Python24\Scripts\easy_install.exe -f http://pyt rg/package_index.html SQLObject Reading http://pythonpaste.org/package_index.html Searching for SQLObject Reading http://www.python.org/pypi/SQLObject/ No local packages or download links found for SQLObject error: Could not find distribution for Requirement.parse('SQLObject') The funny ([EMAIL PROTECTED]) thing is that after a few tries and variations I get: A windows dialog box saying: "C:\Python24\Scripts\easy_install.exe is not a valid Win32 application." I'm at a lost! I confess that I just follow along instructions, but that's what easy install is supposed to be about right? Txs, Miguel --- Telefone sem assinatura + Internet até 16Mb Apenas 34,90 por mês! Saiba mais em http://acesso.clix.pt grandes ideias fazem clix ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
On Tue, 22 Nov 2005, Douglass, Erik wrote: > I am trying to follow some online first timer tutorials, and I am > writing the practice scripts in notepad (only w32 at work :-().. I save > the script with a .py extension, and when I run it it opens for a brief > moment in a command prompt then closes before I even have a chance to > see what it says. This may seem trivial, but Python also happens to be > my first language so this is all new to me. Using Python 2.4.2 Hi Erik, No problem. What's happening is that Windows is closing down any program that's finished. Usually, that's what you want, except while you're learning how to program. Most of the programs you will be writing will be short, terminate quickly, and close down before you can see your program's results! *grin* If you run your programs through IDLE, you should be able to see them run to completion without closing down. I wrote an introduction to IDLE here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html It's a little outdated, but most of the information there is still relevant. (The menu option for running scripts now lives in the Module menu, I think.) One other way to get around the program-terminating-closes-window problem is to keep your program from terminating. Some people will add a last statement to their program, like the infamous: ## raw_input("Please press enter to continue...") ## which should pause until the user presses the enter key. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
Title: Message Hi Eric, Either - add this line to the end of your scripts - discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson -Original Message-From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Douglass, ErikSent: Wednesday, 23 November 2005 3:03 a.m.To: tutor@python.orgSubject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work L).. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Delete an attribute using Beautiful Soup?
On Tue, 22 Nov 2005, Bob Tanner wrote: > Bob Tanner wrote: > > > I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be > > exact. > > I believe I answered my own question. Looking for confirmation this is the > "right" solution. > > del(soup.body['bgcolor']) Yes, del should do it. del is the deletion statement that lets us do things like remove keys from a dictionary: ## >>> states = {'TX' : 'Texas', ... 'CA' : 'California', ... 'PL' : 'Pluto'} ## If we want to get rid of an intergalactic mistake, we can use del: ## >>> del states['PL'] >>> states {'CA': 'California', 'TX': 'Texas'} ## Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
Hello, Erik, Welcome to the maillist. >From your description, is sounds like you are attempting to run the scripts by double clicking on them from Windows Explorer, or from the Run dialog on the Start menu. Both these methods open a command window in a new process, run the script, then terminate the process as soon as the script ends. Try opening a command window manually, changing to the directory where the script resides, and running the program from there. That way the window will remain after the script has finished, and you can see the results. One way to get to a command prompt window is to use the XP start menu: Start->All Programs->Accessories->Command Prompt HTH BGC == > Date: Tue, 22 Nov 2005 08:03:08 -0600 > From: "Douglass, Erik" <[EMAIL PROTECTED]> > Subject: [Tutor] Newbie question > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="us-ascii" > > I am trying to follow some online first timer tutorials, and I am > writing the practice scripts in notepad (only w32 at work :-().. I > save the script with a .py extension, and when I run it it opens for a > brief moment in a command prompt then closes before I even have a chance > to see what it says. This may seem trivial, but Python also happens to > be my first language so this is all new to me.Using Python 2.4.2 > > > > Thanks for any help. > > > > Erik > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python-ldap
Hi, Looks like they are just constants. There is really no point in printing or making any sense of their content, just use them as they are defined in the module. This is like a C #define But this is all LDAP specific... let's see: > > ## The next lines will also need to be changed to support your search > requirements and directory > baseDN = "ou=Customers, ou=Sales, o=anydomain.com" > searchScope = ldap.SCOPE_SUBTREE SCOPE_SUBTREE is one of the avaliable search scopes. According to this(http://linuxjournal.com/article/6988) it should search for the object and its descendants.. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) Reading it as it is, looks like the result may be something different, but only those results that are of type RES_SEARCH_ENTRY are meaningful. That's why you check it. read, read, read. This is what I understand, not knowing crap about LDAP, and just using Google. Check the following docs: ` http://www.ldapman.org/ldap_rfcs.html http://www.cse.ohio-state.edu/cs/Services/rfc/rfc-text/rfc1823.txt Bingo! This is the LDAP application programming interface from which the Python LDAP implementation has been 'stolen' All these definitions are explained. For instance: " Parameters are: ldThe connection handle; base The dn of the entry at which to start the search; scope One of LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL, or LDAP_SCOPE_SUBTREE, indicating the scope of the search; Upon successful completion, ldap_result() returns the type of the result returned in the res parameter. This will be one of the following constants. LDAP_RES_BIND LDAP_RES_SEARCH_ENTRY LDAP_RES_SEARCH_RESULT LDAP_RES_MODIFY LDAP_RES_ADD LDAP_RES_DELETE LDAP_RES_MODRDN LDAP_RES_COMPARE " Google is your friend, and going through you may find most of your answers... Hope that help, Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python-ldap
On Nov 22, 2005, at 2:08 PM, Pat Martin wrote: > I am new to python and fairly new to programming. I have written some > ldap scripts in perl and am trying to learn how to do that in > python. I > found some code on the net using the python-ldap module (the unaltered > code is at the bottom of this email) and have adapted it to my needs, > the code works fine. I want to learn what some of the things in the > code > are. The two things I don't understand are > ldap.SCOPE_SUBTREE and > ldap.RES_SEARCH_ENTRY > when I print those out I get integers 2 and 100 respectively, I am not > sure if they change but that is what they start out at. I am figuring > other modules use similar things (variables?), can someone point me to > where I can understand what more about what these are. SCOPE_SUBTREE is one of three possible scopes you can use. Remember that LDAP is a tree-based heirarchy (arranged much like the old Windows Explorer file tree view). So that tree is divided into branches, sub branches, etc. How you limit your search depends on two things: 1. The starting branch point (the base) 2. The scope (which is applied to the base). So say you have ou=foo,ou=bar,o=root. There are three bases you could choose to start from. o=root ou=bar,o=root ou=foo,ou=bar,o=root If you used base o=root with a scope of SCOPE_BASE, the only possible entry that could be returned is o=root itself. SCOPE_BASE indicates that the scope of the search should be limited to the base itself - not to any of its sub branches or sub entries. Just itself. If you used base o=root with a scope of SCOPE_ONE, you would be able to obtain entries like this: ou=bar,o=root cn=something,o=root cn=another,o=root cn=third,o=root In other words, given a base, you can get entries one level below; the entries immediately subordinate to your base (but not the base itself). You could not get back ou=foo,ou=bar,o=root because that is not immediately beneath o=root. If you used base o=root with a scope of SCOPE_SUBTREE, you would be able to obtain any entry anywhere in the tree, including the base. This translates to: start the base, anything further down the line is okay. Therefore, if you used a base of ou=bar,o=root, you could get these entries: ou=bar,o=root cn=something,ou=bar,o=root cn=something-else,ou=foo,ou=bar,o=root But you could not get: o=root Because that is outside the scope (at a higher level than the base). Behind the scenes, the scopes have different numbers, which is why you get the integer value when you printed SCOPE_SUBTREE. These numbers don't really matter; they're just values used by the libraries. Just ignore them and use the constants SCOPE_BASE, SCOPE_ONE, SCOPE_SUBTREE. Unless you have a specific reason to use another scope, subtree is usually the default choice. I've had plenty of occasion to use the other two scopes, though. RES_SEARCH_ENTRY is, as far as I know, just a way to test if something is an LDAP entry object. So if you are iterating through a set of results, you can say if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) Which means, append the entry to the result set only if it actually is an entry object. More information here: http://python-ldap.sourceforge.net/doc/python-ldap/ldap-objects.html -dan -- Television is one of the Six Fundamental Forces of the Universe; with the other five being Gravity, Duct Tape, Whining, Remote Control, and the Force That Pulls Dogs Toward the Groins of Stranges. -Dave Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] command in menu and button
Hi all, I'm puzzled by the 'command' option in menu and Button of Tkinter. With the following lines, menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) Button(toolbar, text='Open Viewer', command=os.system("Open my viewer &")).pack(side=LEFT) I wanted to open a graphical viewer from the prompt (that is why I used os.system("Open viewer &")) once the user selects the option from the menu, or clicks the button, but this gets implements whenever the GUI is launched instead. Why is this? And how can I make it work? Many thanks, Joe Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: Hi Eric, Either - add this line to the end of your scripts - discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. This is preferred, since any exception traceback will remain visible. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson -Original Message- From: [EMAIL PROTECTED] [ mailto:[EMAIL PROTECTED]] On Behalf Of Douglass, Erik Sent: Wednesday, 23 November 2005 3:03 a.m. To: tutor@python.org Subject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work L).. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
A short-cut if you dont want to use DOS to traverse to your directory or if you are feeling too lazy to type in the entire path & script name. You can right-click on the script file in the Windows explorer and choose "Send to -> Command prompt". This opens a command prompt with the path already set to the one that you want, and the name of the script already typed in. Now, just cursor to the left untill you reach the ">" prompt and type in "python ". So now your command prompt reads "C:\whatever path>python yourfile.py". Press enter to run the script. From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of bobSent: Wednesday, 23 November 2005 10:44 a.m.To: Liam Clarke-Hutchinson; 'Douglass, Erik'; 'tutor@python.org'Subject: Re: [Tutor] Newbie question At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: Hi Eric, Either - add this line to the end of your scripts -discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there.This is preferred, since any exception traceback will remain visible. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson-Original Message-From: [EMAIL PROTECTED] [ mailto:[EMAIL PROTECTED]] On Behalf Of Douglass, ErikSent: Wednesday, 23 November 2005 3:03 a.m.To: tutor@python.orgSubject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work L).. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] command in menu and button
Apologies to Double Six for getting this twice; I forgot to cc: tutor.. On 23/11/05, Double Six <[EMAIL PROTECTED]> wrote: > menu.add_command(label="Open Viewer", command=os.system("Open my > viewer &")) Hi Joe, This is a fairly common gotcha. Think about what happens when python executes a function call: Firstly, it evaluates each of the arguments to the function. Then, it calls the function. So, with your line above, here's what python does: 1. Evaluate "Open Viewer". This is easy; it just produces a string. 2. Evaluate os.system("Open my viewer &"). Since this is a function call, in order to evaluate it, python calls the function to get its return value. 3. Call menu.add_command with the arguments it has just evaluated. Do you see what is happening now? What python wants is a _callable_ --- this is like a function that hasn't been called yet. Functions are first-class objects in python. That means you can do things like this: >>> def hello(): ... print 'hello world!' ... >>> hello() hello world! >>> f = hello # assign to f the function hello. >>> f()# f is now a function, so we can call it. hello world! Or, I could make a quit button like this: b = Button(self, text='Quit program', command=self.quit) # assuming 'self' is a Frame or Tk or something. Note the lack of () after self.quit: We're passing a reference to the method itself. So, to your specific problem: menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) It's a bit more difficult, because you want to pass an argument to os.system. And when Tkinter calls a menu callback, it doesn't give it any arguments. But, that's OK. You can just define a new function: def callback(): os.system("Open my viewer &") menu.add_command(label="Open Viewer", command=callback) Does this help? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question
Title: Message Ooer, weird keystrokes... my apologies Bob. >This is preferred, since any exception traceback will remain visible. That's a really good point... I believe associating a Python batch file using pause would allow tracebacks to remain also. @echo off c:\Python24\Python %1 %2 %3 %4 %5 %6 %7 %8 %9 pause or similar... Regards, Liam Clarke-Hutchinsonwww.med.govt.nz -Original Message-From: bob [mailto:[EMAIL PROTECTED] Sent: Wednesday, 23 November 2005 10:44 a.m.To: Liam Clarke-Hutchinson; 'Douglass, Erik'; 'tutor@python.org'Subject: Re: [Tutor] Newbie questionAt 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: Hi Eric, Either - add this line to the end of your scripts -discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson-Original Message-From: [EMAIL PROTECTED] [ mailto:[EMAIL PROTECTED]] On Behalf Of Douglass, ErikSent: Wednesday, 23 November 2005 3:03 a.m.To: tutor@python.orgSubject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work L).. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] command in menu and button
>>I'm puzzled by the 'command' option in menu and Button of >>Tkinter. With the following lines, The command value needs to be a *reference* to a function. That is not the function call itself but a reference to the function that will be \called. Let me illustrate the difference: def f(): print 'Its me!' f() # prints the message g = f # this assigns a reference to f g() # this now calls that reference, so calling g() is the same as calling f() >>menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) Here you assign the result of the os.system() call to command, in fact you want to assign a reference to a call of os.system which will be executed when the menu/button is activated. The more straightforward way to do that is to define a short function that calls os.system: def callSystem(): os.system(Mycommand) And make the menu/button reference callSystem: >>menu.add_command(label="Open Viewer", command=callSystem) Notice no parens, just the name of the function. Because we can wind up with loads of these little wrapper functions there is a shortcut called lambda. With lambda we can avoid defining a new mini function: >>menu.add_command(label="Open Viewer", command=lambda : os.system("Open my viewer &")) the thing that follows the lambda is what gets executed when the widget activates. Does that help? Alan G. http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] TRULY NEWBIE - MENTOR NEEDED
Greetings, I am new student to programming and am experimenting with PYTHON. >From what I have read, seems to be a very versatile language. In the following excercise I am getting an error class String(str, Object): shift = 6 mask = ~0 << (31 - shift) def __hash__(self): result = 0 for c in self: result = ((result & String.mask) ^ result << String.shift ^ ord(c)) & sys.maxint return result # ... Traceback (most recent call last): File "", line 11, in -toplevel- class String(str, Object): NameError: name 'Object' is not defined >>> _ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED
On Tue, 22 Nov 2005, mike donato wrote: > Greetings, I am new student to programming and am experimenting with > PYTHON. From what I have read, seems to be a very versatile language. > In the following excercise I am getting an error > > class String(str, Object): [class definition cut] > > Traceback (most recent call last): > File "", line 11, in -toplevel- > class String(str, Object): > NameError: name 'Object' is not defined Hi Mike, The error is true: Python doesn't know of any class named 'Object'. What you may be looking for is the 'object' class (lowercase 'o'). Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem using easy_install
On Tue, 22 Nov 2005, Miguel Lopes wrote: > I'm trying to get a handle on Python eggs using Easy Install. [question cut] Hi Miguel, Unfortunately, I don't think we here at Tutor will be able to help effectively with setuptools. I see that you're trying to do stuff with the PEAK stuff: http://peak.telecommunity.com/DevCenter/setuptools but since this is so specialized, you may want to talk with the setuptools folks instead. Try the PEAK developer list: http://www.eby-sarna.com/mailman/listinfo/PEAK/ They should be better able to help you figure out what's going on. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using py2exe
Hi, Im trying to convert a python program to a stand-alone executable that I can distribute. How do I use py2exe to do this? The python program consists of a py script that uses (imports) several other modules (py scripts) located in another directory. Heres what Ive tried so far: 1) Running "python setup.py py2exe" on the cmd line created the required exe file. Hoever, on running the exe file, it reports an error: File "log_all_msgs_spartacus.py", line 8, in ? ImportError: No module named listener 2) Running the command followed by comma seperated module names (all modules that are imported by the main script) python setup.py py2exe -i ..\lib\listener.py, ..\lib\ sender.py, ..\lib\gpsmsg.py, ..\lib\envmsg.py, ..\lib\cmds.py, ..\lib\logger.py, ..\lib\nmea.py Produced the foll error: invalid command name '..\lib\sender.py,' The contents of setup.py is as follows (got it off the py2exe website): from distutils.core import setup import py2exe setup( version = "0.0.1", description = "Log_all_msgs_from_Spartacus", name = "Spartacus_monitor", # targets to build console = ["log_all_msgs_spartacus.py"], ) Once I've created the exe file, can it be run on a PC which does not python setup in it? Note: - the program uses the standard pyserial module as well. Thanks, Hans ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED
At 02:41 PM 11/22/2005, mike donato wrote: >Greetings, I am new student to programming and am experimenting with PYTHON. > >From what I have read, seems to be a very versatile language. In the >following excercise I am getting an error > >class String(str, Object): try -> class String(str, object): >shift = 6 > > mask = ~0 << (31 - shift) > > def __hash__(self): > result = 0 > for c in self: > result = ((result & String.mask) ^ > result << String.shift ^ ord(c)) & sys.maxint > return result > > # ... > > > >Traceback (most recent call last): > File "", line 11, in -toplevel- > class String(str, Object): >NameError: name 'Object' is not defined > >>> > >_ >Express yourself instantly with MSN Messenger! Download today it's FREE! >http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED
Danny Yoo wrote: > > On Tue, 22 Nov 2005, mike donato wrote: > > >>Greetings, I am new student to programming and am experimenting with >>PYTHON. From what I have read, seems to be a very versatile language. >>In the following excercise I am getting an error >> >>class String(str, Object): > > The error is true: Python doesn't know of any class named 'Object'. What > you may be looking for is the 'object' class (lowercase 'o'). Though inheriting from str and object is redundant as str already is a subclass of object. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor