Re: [Tutor] Dynamic inheritance?
Jan Eden wrote: > Jan Eden wrote on 22.11.2005: >>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. Sorry about the bad advice. There is something about packages I don't fully understand - the modules in a package are not available as attributes in the package until the submodules have been imported. For example, using the standard email package as an example, if just email is imported then the submodules are not available as attributes: >>> import email >>> email.Charset Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Charset' If I explicitly import the sub-module then it becomes available as an attribute: >>> from email import Charset >>> email.Charset Your __import__() statement is doing the same magic as the explicit 'from email import Charset'. The thing that confuses me about this is that for some modules the extra import is not needed. For example: >>> import os >>> getattr(os, 'path') OK looking at os.py, it is actually not a package, it is a module that imports other modules as attributes. It just looks like a package from the outside. So maybe os is the only strange one. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Introspection (modules and functions)
Hi. My application hosts a module A that contains only a (variable) number of functions. In another part of this application I need to know which functions are defined inside module A. Initially I thought to use __dict__, but along with the functions of module A are listed all the builtins too. How is possible to obtain this information without defining return_all_functions() (see below)? Actually module A is something like: def f1(): pass def f2(): pass # def # def ... def return_all_functions(): t = (f1, f2, ) return t Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] files - strings - lists
I want to create a program that uses data from text files, makes appropriate calculations and produces report. First I need to find out what is the right way to retrieve appropriate information from an input file. This is a typical format of the input file: 1 Polonijna Liga Mistrzow |from the heading portion 26 wrzesnia 2005 |only 6 12 6 4 1 |'6' and '4' will be needed 0 1 0 Bohossian - Kolinski |all names and 1 |all scores 1.000 9 13 19 |(3rd column - 2.000 2 4 16 |'13', '4', '8', '6' 1.000 10 8 17 |will be needed 0.000 8 6 17 | Szadkowska - Szczurek | 2 |same here 0.000 11 16 20 | 3.000 1 -4 14 | 3.500 3 -7 13 2.500 10 13 19 .. 1 1 |skip the rest 1 1 1 |(at least for now) 6 4 5 10 8 3 9 1 11 2 12 7 -50 -7 7 0 0 0 400 0 0 -110 -2 2 -130 1 -1 100 -1 1 110 -4 4 150 4 -4 400 0 0 -90 -1 1 100 6 -6 100 -1 1 420 4 -4 110 5 -5 -480 -1 1 1310 15 -15 Should I use string manipulations or convert a file to lists of lists to retrieve names and numbers? I have unsuccessfully tried to code using the latter but I couldn't overcome the fact that lists representing each raw of a text file have different lengths. How could I associate each name with a score (a sum of scores)? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski office 416.652.4256 cell. 416.948.7767___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introspection (modules and functions)
Negroup - wrote: >Hi. > >My application hosts a module A that contains only a (variable) number >of functions. In another part of this application I need to know which >functions are defined inside module A. Initially I thought to use >__dict__, but along with the functions of module A are listed all the >builtins too. > > Negroup, You might want to try this: custom_list = [x for x in A.__dict__ if not x.startswith('_')] This should remove the builtins. Hope this helps, Frank. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pretty XML
Hello- I am in the process of creating an XML document from information stored in our database. One of my colleagues will use the record to format our information (health care claims) into all sorts of forms, reports, etc. He is partial to PHP5 but I like Python and would like to know if there is something that would read in my XML file and format it in a similar manner to "pretty print" so I can verify the correct information is being pulled. I have looked into the XML documentation and, to be honest, I am overwhelmed with the choices; SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time for 25 years, I'm new to XML and could use some pointers. My immediate concern is to read in an XML stream from a file and format it with indentation so that I can read and verify the data against out database. My long term concern is what tool(s) do you think would give the biggest return against the effort required to learn them? The claim files I am generating will be less than a meg each, if that matters. Thanks! --greg ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introspection (modules and functions)
Hi! I quick solution for a name module could be: >>> import os >>> for d in os.__dict__: ... a="os." + d ... if callable( eval(a) ): ... print "Callable %s" % ( eval(a)) but there should also be a recipe on activestate for that problem. I think I've red something in the Python Cookbook HTH, Ewald Negroup - wrote: > Hi. > > My application hosts a module A that contains only a (variable) number > of functions. In another part of this application I need to know which > functions are defined inside module A. Initially I thought to use > __dict__, but along with the functions of module A are listed all the > builtins too. > > How is possible to obtain this information without defining > return_all_functions() (see below)? > > Actually module A is something like: > > def f1(): > pass > > def f2(): > pass > > # def > # def ... > > def return_all_functions(): > t = (f1, f2, ) > return t > > Thanks > ___ > 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] files - strings - lists
Andrzej Kolinski wrote: > > I want to create a program that uses data from text files, makes > appropriate calculations and produces report. First I need to find out > what is the right way to retrieve appropriate information from an input > file. This is a typical format of the input file: > > 1 Polonijna Liga Mistrzow|from the heading portion > 26 wrzesnia 2005|only > 6 12 *6* *4* 1|'6' and '4' will be needed > 0 1 0 > *Bohossian* - *Kolinski*|all names and > 1|all scores > 1.000 9 *13* 19|(3rd column - > 2.000 2 *4* 16|'13', '4', '8', '6' > 1.000 10 *8* 17|will be needed > 0.000 8 *6* 17| > *Szadkowska* - *Szczurek*| > 2|same here > 0.000 11 *16* 20| > 3.000 1 *-4* 14| > 3.500 3 *-7* 13 > 2.500 10 *13* 19 > .. > > 1 1|skip the rest > 1 1 1|(at least for now) It's pretty simple to make an ad-hoc reader for this data. A couple of things you need: - You can get individual lines from a file by treating it as an iterator. Instead of the usual f = open('data.txt') for line in f: you can call f.next() to get a single line. This makes it easy to skip lines or process lines differently. The call to f.next() will raise StopIteration when there are no more lines - You can use split() to break a line into fields, then subscripting to pull out the data you want: >>> line = ' 1.000 9 13 19' >>> line.split() ['1.000', '9', '13', '19'] >>> line.split()[2] '13' >>> int(line.split()[2]) 13 With these tools the solution is pretty simple. I pull the data from a string but it will work with a file as well. I save the results in a dictionary which maps name to a list of scores. data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 '''.split('\n') #lines = open('data.txt') # to get the data from a real file lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next()# skip two headers lines.next() header = lines.next().split() six = int(header[2]) four = int(header[3]) print six, four lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try:# you don't say how you know the end of the names, I just run to the end of data while True: name = lines.next().strip() lines.next()# skip line after name scores = [ int(lines.next().split()[2]) for i in range(4) ] allScores[name] = scores except StopIteration: # no more lines pass for name, scores in allScores.items(): print name, scores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pretty XML
Greg Lindstrom wrote: > Hello- > I am in the process of creating an XML document from information > stored in our database. One of my colleagues will use the record to > format our information (health care claims) into all sorts of forms, > reports, etc. He is partial to PHP5 but I like Python and would like > to know if there is something that would read in my XML file and > format it in a similar manner to "pretty print" so I can verify the > correct information is being pulled. I have looked into the XML > documentation and, to be honest, I am overwhelmed with the choices; > SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time > for 25 years, I'm new to XML and could use some pointers. > > My immediate concern is to read in an XML stream from a file and > format it with indentation so that I can read and verify the data > against out database. My long term concern is what tool(s) do you > think would give the biggest return against the effort required to > learn them? The claim files I am generating will be less than a meg > each, if that matters. > Greg, Googling found the following Python/SAX XML indenter: http://mail.python.org/pipermail/xml-sig/1999-January/000756.html It should do what you want or at least give you a head start. Cheers, F. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
| | With these tools the solution is pretty simple. I agree that handling this with Python is pretty straightforward, but I'm wondering if there exists some sort of mechanism for reading these types of well structured (though not XML format, etc...) files. Something like a reverse template, somewhat like the templates that are used to interpret dates and such in the time module (strftime, is it?). Something like this, where you put a command on each line telling what (if anything) to do: templ = ''' 1 Polonijna Liga Mistrzow#no command other than signifying a line is to be read 26 wrzesnia 2005 6 12 6 4 1#here we need to do a split and keep 2 and 3, assigning them to a and b 0 1 0 Bohossian - Kolinski#c and d would have to be a list since there is a rpt command 1 1.000 9 13 19#the x4 says to do this command 4 times 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 /rpt> I know you could write an regex to handle it, but I'm wondering if there is a kinder method around. Wondering, /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sort list alphabetically
Hallo, i have a list with the dirs/files from the current path. When i use sort() to sort the list alphabetically the list is still unsorted. How to use ? dirs_files = os.listdir(os.getcwd()) print dirs_files dirs_files.sort() print dirs_files Thank you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] command in menu and button
Hi John and Alan, I got it! Thank you both for explaining this situation. Thanks, Joe Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag On Tue, 22 Nov 2005, [EMAIL PROTECTED] ([EMAIL PROTECTED]) wrote: > >>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
Re: [Tutor] sort list alphabetically
On Wed, 23 Nov 2005, lmac wrote: > i have a list with the dirs/files from the current path. When i use > sort() to sort the list alphabetically the list is still unsorted. How > to use ? > > dirs_files = os.listdir(os.getcwd()) > print dirs_files > dirs_files.sort() > print dirs_files Hi lmac, I can't duplicate this. Can you show us the output that you see? Do any of the list elements permute at all? Here's what happens on my own system: ## >>> files = os.listdir("/etc/init.d") >>> files ['README', 'acctadm', 'ldap.client', 'mkdtab', 'nscd', 'ufs_quota', 'devlinks', 'drvconfig', 'acct', 'dhcp', 'nfs.server', 'pcmcia', 'slpd', 'sendmail', 'Wnn6', 'sysetup', 'cachefs.daemon', 'PRESERVE', 'deallocate', 'autoinstall', 'dodatadm.udaplt', 'uucp', 'lu', 'ncakmod', 'appserv', 'audit', 'samba', 'apache', 'imq', 'volmgt', 'init.wbem', 'boot.server', 'llc2', 'dtlogin', 'webconsole', 'atsv', 'init.dmi', 'init.snmpdx', 'mipagent', 'ncalogd', 'IIim', 'pppd', 'loc.ja.cssd', 'init.sma', 'installupdates', 'cswopenldap', 'cswmysql', 'samba.old', 'mysql.server', 'patchserver', 'mysql.server~', 'init.wbem.119314-03'] >>> files.sort() >>> files ['IIim', 'PRESERVE', 'README', 'Wnn6', 'acct', 'acctadm', 'apache', 'appserv', 'atsv', 'audit', 'autoinstall', 'boot.server', 'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate', 'devlinks', 'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'imq', 'init.dmi', 'init.sma', 'init.snmpdx', 'init.wbem', 'init.wbem.119314-03', 'installupdates', 'ldap.client', 'llc2', 'loc.ja.cssd', 'lu', 'mipagent', 'mkdtab', 'mysql.server', 'mysql.server~', 'ncakmod', 'ncalogd', 'nfs.server', 'nscd', 'patchserver', 'pcmcia', 'pppd', 'samba', 'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt', 'webconsole'] ## Everything appears to sort fine. The files that start with uppercase come first because of the way those strings compare to lowercase strings. If we want a case-insensitive sort, we can do something like this: ## >>> def case_insensitive_cmp(a, b): ... return cmp(a.upper(), b.upper()) ... >>> files.sort(case_insensitive_cmp) >>> files ['acct', 'acctadm', 'apache', 'appserv', 'atsv', 'audit', 'autoinstall', 'boot.server', 'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate', 'devlinks', 'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'IIim', 'imq', 'init.dmi', 'init.sma', 'init.snmpdx', 'init.wbem', 'init.wbem.119314-03', 'installupdates', 'ldap.client', 'llc2', 'loc.ja.cssd', 'lu', 'mipagent', 'mkdtab', 'mysql.server', 'mysql.server~', 'ncakmod', 'ncalogd', 'nfs.server', 'nscd', 'patchserver', 'pcmcia', 'pppd', 'PRESERVE', 'README', 'samba', 'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt', 'webconsole', 'Wnn6'] ## Hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
On Wed, 23 Nov 2005, Chris or Leslie Smith wrote: > I agree that handling this with Python is pretty straightforward, but > I'm wondering if there exists some sort of mechanism for reading these > types of well structured (though not XML format, etc...) files. Hi Chris, Yes, take a look at "parser" tools like pyparsing, mxTextTools, and Martel: http://pyparsing.sourceforge.net/ http://www.egenix.com/files/python/mxTextTools.html http://www.dalkescientific.com/Martel I have to admit that I don't use these tools much, since my data is already in some kind of predefined structure. If it's at all possible, I'd recommend sticking with pre-defined formats like XML: parsing can be a tedious job at times. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to discover which OS my python is running?
Hi! I'm using a program that I want to know if I'm running the program in Linux or Windows. How can I do this? I want this because I created all my program in Linux but if someone runs it in Windows I have to do some things to make it work well, and I want to do this verification automatically. Thx, Diego ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pretty XML
Greg Lindstrom wrote: > Hello- > I am in the process of creating an XML document from information > stored in our database. One of my colleagues will use the record to > format our information (health care claims) into all sorts of forms, > reports, etc. He is partial to PHP5 but I like Python and would like > to know if there is something that would read in my XML file and > format it in a similar manner to "pretty print" so I can verify the > correct information is being pulled. I have looked into the XML > documentation and, to be honest, I am overwhelmed with the choices; > SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time > for 25 years, I'm new to XML and could use some pointers. > > My immediate concern is to read in an XML stream from a file and > format it with indentation so that I can read and verify the data > against out database. My long term concern is what tool(s) do you > think would give the biggest return against the effort required to > learn them? The claim files I am generating will be less than a meg > each, if that matters. > > Thanks! > --greg Try 4Suite / Amara: http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/ (I downloaded the allinone package) >>> from Ft.Xml import Parse >>> from Ft.Xml.Domlette import PrettyPrint >>> xmlfile = open('c:/test.xml') >>> xml = "".join(xmlfile.readlines()) >>> xml 'some textlevel 3some other textHi!\n' >>> doc = Parse(xml) >>> PrettyPrint(doc) some textlevel 3 some other text Hi! It isn't a great representation... Perhaps my xml was malformed. Try it yourself to see if it works for you. HTH! Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
Danny Yoo wrote: | On Wed, 23 Nov 2005, Chris or Leslie Smith wrote: | || I agree that handling this with Python is pretty straightforward, but || I'm wondering if there exists some sort of mechanism for reading || these types of well structured (though not XML format, etc...) files. | | Hi Chris, | | Yes, take a look at "parser" tools like pyparsing, mxTextTools, and | Martel: | |http://pyparsing.sourceforge.net/ | |http://www.egenix.com/files/python/mxTextTools.html | |http://www.dalkescientific.com/Martel | Great links, Danny. Thanks. I had seen mxTextTools before but didn't search for the right thing before raising the question. The pyparsing seems very interesting. The code that I attach below is a very light-weight version of a formatted reader. It assumes that you just want to pluck white-space delimited values out of lines in a text file (something I've had to do from time to time and something others have asked about on tutor before). Perhaps this is the sort of simple approach that evolves into one of the tools above as more complex parsing rules are needed. Again, thank for the pointers. OK, here's a first draft of a simple formatted reader that can be used to read and keep certain white-space delimited strings from lines in an input stream/file. The basic idea is to write the template using a representative chunk of the text file (so the codes that you write can be seen directly next to the data that you are going to read) or else you can separate the two. At the start of a line that you want processed, you put in angle brackets the number of items that (should) appear on the line when separated by white space and then a comma-delimited list of items that you want to keep. Here's a working example using the data submitted in this thread: ## #a template can be done like this (w/ no visual reference to actual lines)...but don't forget to put the \ #after the triple quotes or else an extra line will be processed and don't put an extra return before the #last triple quote. The example below indicates that 4 lines will be processed. templ1 = '''\ _ _ <5x2,3> _''' # or like this, where a sample line is shown templ1 = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 <5x2,3> 6 12 6 4 1 0 1 0''' # here is another template that will be used to parse the lines templ2='''<3x0,2>Bohossian - Kolinski 1 <4x2> 1.000 9 13 19 <4x2> 2.000 2 4 16 <4x2> 1.000 10 8 17 <4x2> 0.000 8 6 17''' # ---here is the data- data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 and then here is single line '''.split('\n') lines = iter(data) # to get data from a string that has been split into lines #-- def partition(s, t): # from python-dev list, I believe if not isinstance(t, basestring) or not t: raise ValueError('partititon argument must be a non-empty string') parts = s.split(t, 1) if len(parts) == 1: result = (s, '', '') else: result = (parts[0], t, parts[1]) return result def temp_read(templ, lines): ''' Use a template to extract strings from the given lines. Lines in the template that start with "<" are assumed to contain a parsing command that is in the format, , where N = number of white space separated items expected on the line x is the letter x L = a list of comma separated integers indicating which items to keep from the line e.g. <4x2,3> appearing at the start of a line in the template means that the corresponding line of data should have 4 items on it, and 2 and 3 should be returned If one or more lines of the data do not jive with the parsing instructions, a value of None will be returned. This may indicate the end of the data that can be interpreted with the template you gave. ''' rv = [] #all return values for the template will go here try: for ti in templ.splitlines(): #get a template line li = lines.next()#and a physical line of data if ti.startswith('<'):#check to see if there is a parse command on the line # get the command cmd = ti[1:].split('>')[0] things,_,keep = partition(cmd, 'x') things = int(things) keep = [int(x.strip()) for x in keep.split(',')] #split the physical line data = li.split() #check that the # of items matches the template specs assert len(data)==things #add the items to the return list for k in keep: rv.append(data[k])
Re: [Tutor] Introspection (modules and functions)
Negroup - wrote: > Hi. > > My application hosts a module A that contains only a (variable) number > of functions. In another part of this application I need to know which > functions are defined inside module A. Initially I thought to use > __dict__, but along with the functions of module A are listed all the > builtins too. > > How is possible to obtain this information without defining > return_all_functions() (see below)? How about a return_all_functions() that uses introspection? def return_all_functions(module): callables = [] for name in dir(module): value = getattr(module, name) if callable(value): callables.append(value) return callables Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to discover which OS my python is running?
Diego Galho Prestes wrote: > Hi! I'm using a program that I want to know if I'm running the program > in Linux or Windows. How can I do this? I want this because I created > all my program in Linux but if someone runs it in Windows I have to do > some things to make it work well, and I want to do this verification > automatically. Try sys.platform or os.name. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to discover which OS my python is running?
On Wed, 23 Nov 2005, Kent Johnson wrote: > Diego Galho Prestes wrote: > > Hi! I'm using a program that I want to know if I'm running the program > > in Linux or Windows. How can I do this? I want this because I created > > all my program in Linux but if someone runs it in Windows I have to do > > some things to make it work well, and I want to do this verification > > automatically. > > Try sys.platform or os.name. Hi Diego, Yes, even Distutils takes this approach. We can take a look at the function get_platform_lib(), where they use os.name to figure out what platform the program is running under. http://svn.python.org/projects/python/trunk/Lib/distutils/sysconfig.py (Hey, I didn't realize that python.org moved their source code repository from CVS to Subversion! When did this happen?! Oh, ok, I see the PEP now. http://www.python.org/peps/pep-0347.html. Cool!) Sorry, got off track. Anyway, Distutils appears to do a fairly simple case analysis: ## if os.name == "posix": ## text cut elif os.name == "nt": ## text cut elif os.name == "mac": ## text cut elif os.name == "os2": ## text cut ## So if it's good enough for Distutils, it may work out for you. *grin* You may want to isolate whatever platform-dependent parts of your application you have off to a separate module. That is, if you can, try writing modules that hide away the platform ugliness, so that the rest of your application can behave as if everything were platform-independent. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
> Great links, Danny. Thanks. I had seen mxTextTools before but didn't > search for the right thing before raising the question. The pyparsing > seems very interesting. The code that I attach below is a very > light-weight version of a formatted reader. It assumes that you just > want to pluck white-space delimited values out of lines in a text file > (something I've had to do from time to time and something others have > asked about on tutor before). Perhaps this is the sort of simple > approach that evolves into one of the tools above as more complex > parsing rules are needed. Hi Chris, Yes, I suspect that this happens a lot. I have my own little formatting reader that simulates some of the features of C's scanf, for example: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ so I think it's one of those little exercises that everyone ends up doing at least once. *grin* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
Thank you Kent, Chris, Danny, This is superb, let me work on my part for now and I promise get back to the group with more ... _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski wrote: > > I want to create a program that uses data from text files, makes > appropriate calculations and produces report. First I need to find out > what is the right way to retrieve appropriate information from an input > file. This is a typical format of the input file: > > 1 Polonijna Liga Mistrzow |from the heading portion > 26 wrzesnia 2005 |only > 6 12 *6* *4* 1 |'6' and '4' will be needed > 0 1 0 > *Bohossian* - *Kolinski* |all names and > 1 |all scores > 1.000 9 *13* 19 |(3rd column - > 2.000 2 *4* 16 |'13', '4', '8', '6' > 1.000 10 *8* 17 |will be needed > 0.000 8 *6* 17 | > *Szadkowska* - *Szczurek *| > 2 |same here > 0.000 11 *16* 20 | > 3.000 1 *-4* 14 | > 3.500 3 *-7* 13 > 2.500 10 *13* 19 > .. > > 1 1 |skip the rest > 1 1 1 |(at least for now) It's pretty simple to make an ad-hoc reader for this data. A couple of things you need: - You can get individual lines from a file by treating it as an iterator. Instead of the usual f = open('data.txt') for line in f: you can call f.next() to get a single line. This makes it easy to skip lines or process lines differently. The call to f.next() will raise StopIteration when there are no more lines - You can use split() to break a line into fields, then subscripting to pull out the data you want: >>> line = ' 1.000 9 13 19' >>> line.split() ['1.000', '9', '13', '19'] >>> line.split()[2] '13' >>> int(line.split()[2]) 13 With these tools the solution is pretty simple. I pull the data from a string but it will work with a file as well. I save the results in a dictionary which maps name to a list of scores. data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 '''.split('\n') #lines = open('data.txt') # to get the data from a real file lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next() # skip two headers lines.next() header = lines.next().split() six = int(header[2]) four = int(header[3]) print six, four lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try: # you don't say how you know the end of the names, I just run to the end of data while True: name = lines.next().strip() lines.next() # skip line after name scores = [ int(lines.next().split()[2]) for i in range(4) ] allScores[name] = scores except StopIteration: # no more lines pass for name, scores in allScores.items(): print name, scores ___ 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] sort list alphabetically
At 09:55 AM 11/23/2005, lmac wrote: >i have a list with the dirs/files from the current path. When i use >sort() to sort the list alphabetically the list is still unsorted. When you say "unsorted" - are the list members in the same order as before the sort? >dirs_files = os.listdir(os.getcwd()) >print dirs_files >dirs_files.sort() >print dirs_files Works for me. On my computer: >>> dirs_files = os.listdir(os.getcwd()) >>> for x in dirs_files[:10]:x "'01GRTfiles" 'archive' 'backup' 'CU' 'data' 'documents' 'error_tbls_in' 'error_tbls_out' 'forms' 'GRTFiles' >>> dirs_files.sort() >>> for x in dirs_files[:10]:x "'01GRTfiles" 'CU' 'DIST_TEST.DBF' 'DUP_ATTR2.BAK' 'DUP_ATTR2.DBF' 'GRTFiles' 'GRT_CS_SA.DBF' 'GRT_ITEM_XREF.DBF' 'IMP_MC_CR.BAK' 'IMP_MC_CR.DBF' You may notice that sort is case sensitive. The names beginning with lower case letters follow all the names beginning with upper case letters. If you want case insensitivity, dirs_files = [x.lower() for x in dirs_files] before sorting. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sort list alphabetically
On 24/11/05, Danny Yoo <[EMAIL PROTECTED]> wrote: > The files that start with uppercase come first because of the way those > strings compare to lowercase strings. If we want a case-insensitive sort, > we can do something like this: > > ## > >>> def case_insensitive_cmp(a, b): > ... return cmp(a.upper(), b.upper()) > ... > >>> files.sort(case_insensitive_cmp) > >>> files [...] > ## In python2.4, you can also use the key= keyword argument: ### def toUpper(s): return s.upper() files.sort(key=toUpper) ### This is more efficient, I believe, because the key function is only called once for each element, whereas cmp is called more than once. (we could use string.upper here instead of defining our own, but string.upper is deprecated these days...) -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sort list alphabetically
> In python2.4, you can also use the key= keyword argument: > > ### > def toUpper(s): > return s.upper() > files.sort(key=toUpper) > ### > > This is more efficient, I believe, because the key function is only > called once for each element, whereas cmp is called more than once. > > (we could use string.upper here instead of defining our own, but > string.upper is deprecated these days...) Hi John, The 'string' module might be deprecated, but the 'str' type should be fine: ## >>> names = ['bill', 'Ted', 'Excellent'] >>> names.sort() >>> names ['Excellent', 'Ted', 'bill'] >>> names.sort(key=str.upper) >>> names ['bill', 'Excellent', 'Ted'] ## Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to discover which OS my python is running?
At 06:31 PM 11/23/2005, Diego Galho Prestes wrote: >Hi! I'm using a program that I want to know if I'm running the program >in Linux or Windows. How can I do this? I want this because I created >all my program in Linux but if someone runs it in Windows I have to do >some things to make it work well, and I want to do this verification >automatically. import os print os.name # on my system I get nt # The following names have currently been registered: 'posix', 'nt', 'mac', 'os2', 'ce', 'java', 'riscos'. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files - strings - lists
Danny wrote: | Hi Chris, | | Yes, I suspect that this happens a lot. I have my own little formatting | reader that simulates some of the features of C's scanf, for example: | |http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ | | so I think it's one of those little exercises that everyone ends up | doing at least once. *grin* I've always taken a personal pride in (eventually) following the in the footsteps of those that have gone before me. There is certainly a joy in rediscovery :-) (There is also a lot to learn from those whose stride is greater!) I was able to pretty easily take your sscanf facility and couple it with the template reader to read Andrzej Kolinski's data. FWIW, here it is: # data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 and then here is single line '''.split('\n') lines = iter(data) template1 = '''\ _ _ < %*s %*s %d %d %*s> #same sort of format as before, but now an explicit token identification occurs _''' template2 = '''\ <%s %*s %s>Bohossian - Kolinski _1 < %*s %*s %i %*s> 1.000 9 13 19 # I get around having to worry about the decimal by using %s < %*s %*s %i %*s> 2.000 2 4 16 < %*s %*s %i %*s> 1.000 10 8 17 < %*s %*s %i %*s> 0.000 8 6 17''' if __name__ == '__main__': def tread(template, lines): #reading lines using lines of the template to parse them if the #lines start with "<" rv = [] try: for i,li in enumerate(template.splitlines()): dat = lines.next() if li.startswith('<'): fmt = li.split('>')[0][1:] #take everything between the <> rv.extend(sscanf(dat, fmt)) return rv except: #print 'error at line',i #print 'in template:' #print template1 return None print tread(template1, lines) while True: vals = tread(template2, lines) if not vals: break print vals ## Hey, Andrzej, it will be interesting to see what you come up with as a solution. This has been a helpful problem for me :-) /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor