[Tutor] Looping
Hey everyone, First post to this list. I hope I'm doing it right. Let's say I want to run func 10 times Is there a more pythonic way to do it than this: for i in xrange(10): func() Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] String Encoding problem
Hey everyone, I'm hoping someone here can help me solve an odd problem (bug?). I'm having trouble with string encoding, object deletion, and the xml.etree library. If this isn't the right list to be posting this question, please let me know. I'm new to Python and don't know of any other "help me" Python mailing lists. I have tried debugging this ad-infinitem. Anyway, at the bottom of this e-mail you will find the code of a python file. This is a gross over-simplification of my code, with little exception handling so that the errors are obvious. Running this interactively, if you finish off with 'del db', it exits fine and creates a skeleton xml file called 'db.xml' with text ''. However, if you instead CTRL-D, it throws at exception while quitting and then leaves an empty 'db.xml' which won't work. Can anyone here help me figure out why this is? Stuff I've done: I've traced this down to the self.commit() call in __del__. The stacktrace and a few print statements injected into xml.etree leads me to the call 'root'.encode('us-ascii') throwing a LookupError on line 751 of xml.etree.ElementTree. This makes no sense to me, since it works fine normally. Thank you very much. Any and all help or pointers are appreciated. ~Matt db.py ### from xml.etree import ElementTree as ET import os class Database(object): def __init__(self, path): self.__dbpath = path## Path to the database self.load() def __del__(self): ## FIXME: Known bug: ## del db at command line works properly ## Ctrl-D, when there is no db file present, results in a LookupError ##and empty xml file from StringIO import StringIO from traceback import print_exc trace = StringIO() try: print 5 self.commit() print 7 except Exception: print_exc(100, trace) print trace.getvalue() def load(self): if os.path.exists(self.__dbpath): self.root = ET.parse(self.__dbpath).getroot() else: self.root = ET.Element("root") def commit(self): ET.ElementTree(self.root).write(self.__dbpath) db = Database('db.xml') ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looping
Thank you. Func is in fact a call to an external non-python program. =] Therefore, the loop must actually be mindlessly done. My question, however, has been answered. As an aside, why use range rather than xrange? I was under the impression that xrange is a generator and therefore more memory efficient. On Mon, Apr 20, 2009 at 1:27 PM, Alan Gauld wrote: > "Matt" > wrote > > Let's say I want to run func 10 times Is there a more pythonic way to do >> it >> than this: >> for i in xrange(10): >> func() >> > > Yes, use range() rather than xrange :-) > > But more seriously, as others have pointed out, if func() is well > written then calling it ten times will have no effect over calling > it once. (Except taking up 10 times as much time!) > > Its like saying > > for n in range(10): > x = 42 > > The assignment is identical each time through the loop > > In fact it's worse than that because you don't even store the > result of func() so it has no effect whatsoever on your program > outside the loop. It would be more normal to do something like: > > for value in mycollection: > result = func(somevalue) > > in other words apply func() to each value in a collection. > > So unless your func() really takes arguments or prints time > related output or modifies global data (a bad practice) then > what you are asking doesn't make much sense. > > Finally, if your function is really a program in disguise - ie it > does all its own input/output then it would make more sense > to put the loop inside the function and put the repeat count > as a parameter: > > def func(repetitions): > for n in range(repetitions): ># your old func code here > > And call it: > > func(repetitions=10) # use keyword for clarity of purpose > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Functional Derivatives
I'm trying to calculate the derivative of a function in Python like so: def D5(func,h=1e-5): ""' Return derivative of function func''' def df(x):return (func(x+h)-func(x))/h df.__name__ = func.__name__ + '_dx' return df However, I run into the problem of limited float precision. This is evident for this: import math print D5(D5(D5(D5(math.sin(0.3) => -5551.11512313 print math.sin(0.3) => 0.295520206661 Is there any way that any of you can think of to avoid this for general-purpose functions? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating & Handling lots of objects
Dear Tutor-list, I'm sorry for this appallingly dumb question, but I'm having a little problem with objects. I've written a class, with some methods. I then want to be able to call the class repeatedly, to create some objects. The number of objects, and some of their initialisation parameters need to be specified later (i.e. at run-time). When I generate all these objects, how do I keep track of them. For a finite (and small) number I can do this: a=MyClass("a") b=MyClass("b") but this is obviously not scaleable. If I use a list, I can do: MyObjects=[] l=["a","b","c"] for i in l: MyObjects.add(MyClass(i)) but then I have to search the list (MyObjects) for the object where Object.name="a". The only other option seems to be finding objects via their hash codes, which I'm sure isn't right I'd like to be able to automate something closer to the a=MyClass("a") but don't know how to do it....It may be that I'm trying to do it very badly, which is Python seems to make it hard for me. Thanks, Matt ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to find complex roots
Dick Mores wrote: My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are: 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is there a way to do this in Python? I think the neatest approach might be to consider that the n-complex roots form at equal angle around the origin on an Argand diagram (basically a cartesian plane) - here the points (in "standard") cartesian notation are at (1,0), (-0.5, 0.86) and (-0.5, -0.86). The whole effect looks a bit like a Mercedes-Benz symbol rotated clockwise by 90 degrees. The points, in this case, lie on the unit circle. As a result, I think you could just divide 360 by n (for the n-roots), set the 1st root at (1,0) and then position the others around the circle, incrementing by the required number of degrees. If I've remembered correctly, for c where |c| <>1, the argument is the same, but you need to take the nth root of the absolute value of c (this can be ignored when we're doing it for 1, as of course the nth root of 1 is 1). Obviously I haven't included any code....but I hope this helps a bit. Matt P.S. Thrilled to be able to answer something on the tutor list, instead of just asking dumb questions! -- Dr. M. Williams MRCP(UK) Clinical Research Fellow,Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 The views, opinions and judgements expressed in this message are solely those of the author. The message may not have been reviewed or approved by Cancer Research UK ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Complex roots
Further to my previous post, please find some code below: Hope this helps, Matt #Complex number Roots #Matt Williams 9.12.04 import math number=complex(0.5,0) n=float(3) size=math.sqrt((number.real**2)+(number.imag**2)) arg=math.radians(360/n) root=1/n modulus=size**root theta=float(0) roots={} i=0 while ihttp://mail.python.org/mailman/listinfo/tutor
[Tutor] Nifty
I'd be interested, Matt On Fri, 2004-12-17 at 11:01, [EMAIL PROTECTED] wrote: > Send Tutor mailing list submissions to > [EMAIL PROTECTED] > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > [EMAIL PROTECTED] > > You can reach the person managing the list at > [EMAIL PROTECTED] > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > >1. suggestion for group project (Brian van den Broek) > > > -- > > Message: 1 > Date: Fri, 17 Dec 2004 05:12:40 -0500 > From: Brian van den Broek <[EMAIL PROTECTED]> > Subject: [Tutor] suggestion for group project > To: Tutor <[EMAIL PROTECTED]> > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi all, > > A while ago, in a response: > > Danny Yoo said unto the world upon 2004-11-29 17:14: > > > > I just got in contact with Nick Parlante of the Nifty Assignments > > project; he's been collecting material on fun projects: > > > > http://nifty.stanford.edu/ > > > > The projects there look pretty nice. In fact, I'm thinking of > > adapting material on that page for us here on Python-Tutor. > > > > Is there a particular project that sounds interesting to folks? > > Personally, I'm interested in: > > > > http://nifty.stanford.edu/catandmouse/html/ > > > > But that's only because I helped tutor it back when I was at > > Berkeley's Self-Paced Center... *grin* But if people want, I'd be > > happy to convert Professor Clancy's support code from C++ to Python. > > > I've got a suggestion: would there be any interest among list members in > picking one of the assignments, working on it, and then doing a code > comparison/critique? > > When Danny posted, I did <http://nifty.stanford.edu/2003/randomwriter/>. > I thought about posting what I had done to the list and inviting such > comment/criticism, but was dissuaded by two things: 1) once I'd got my > code to a reasonable polish, with docstrings and all, it seemed a bit > long to just plunk onto the list, and, 2) I suspect much of the > interest, fun, and learning might well emerge from having a go at the > task and then seeing what others came up with. If I posted mine > unannounced, others wouldn't have the chance to go at the problem fresh. > > What do others think? > > I wonder if the length of code, the possible undesirability of a bunch > of answers to a collection of homework problems getting posted, and > other considerations might make this better as an off-list endeavour. > I'd be interested in doing it either here or on private channels. (If > there was interest and we opt for private, I could probably get my uni > to let me set up an unarchived listserv for the purpose.) > > Best to all, > > Brian vdB > > > > -- > > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 10, Issue 72 > * ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Dear Ara, I have been working on something similar. In the end I used a dictionary for each line in the file, and stored data from each file in a different set. I then matched using one (or more) element from each dictionary. This is really very close doing a join in a database, though, and if I had more time you might want to explore that route (csv -> sqlite, manipulate using sqlobject/ sqlalchemy/ django/ etc.) the csv module has some good facilities for reading/ writing csv files. However, as yet I don't think it, or csvutilities, lets you do the sort of merging you say. HTH, Matt Robert Jackiewicz wrote: On Wed, 13 Oct 2010 14:16:21 -0600, Ara Kooser wrote: Hello all, I am working on merging two text files with fields separated by commas. The files are in this format: File ONE: *Species, Protein ID, E value, Length* Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, File TWO: *Protein ID, Locus Tag, Start/Stop* ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) ZP_07281899, SSMG_05939, complement(NZ_GG657746.1:6565974..6581756) I looked around for other posts about merging text files and I have this program: one = open("final.txt",'r') two = open("final_gen.txt",'r') merge = open("merged.txt",'w') merge.write("Species, Locus_Tag, E_value, Length, Start/Stop\n") for line in one: print(line.rstrip() + two.readline().strip()) merge.write(str([line.rstrip() + two.readline().strip()])) merge.write("\n") merge.close() inc = file("merged.txt","r") outc = open("final_merge.txt","w") for line in inc: line = line.replace('[','') line = line.replace(']','') line = line.replace('{','') line = line.replace('}','') outc.write(line) inc.close() outc.close() one.close() two.close() This does merge the files. Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256,ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256,ZP_05477599, StAA4_01015861, NZ_ACEV0113.1:86730..102047 But file one has multiple instances of the same Protein ID such as ZP_05482482. So the data doesn't line up anymore. I would like the program to search for each Protein ID number and write the entry from file 2 in each place and then move on to the next ID number. Example of desired output: Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 2.82936001e-140, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 8.03332997e-138, 5256, complement(NZ_ACEV0178.1:25146..40916) I was thinking about writing the text files into a dictionary and then searching for each ID and then insert the content from file TWO into where the IDs match. But I am not sure how to start. Is there a more pythony way to go about doing this? Thank you for your time and help. Regards, Ara Why don't you try using the csv library which is part of the standard python library to parse you files. It allows simple and efficient manipulation of comma separated value files. -Rob Jackiewicz ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] output formatting
Hello, I have a series of lists that I need to output into files with a specific format. Specifically, I need to have line breaks after each entry of the list, and I need to do away with the ['..'] that accompany the data after I transform the list into a string. Can I simply append a '\n' to the end of all the list entries in order to enact line breaks? Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] output formatting
Hi Wayne, Yes, that should work perfectly, but it is in writing files that I'm having the problem. I'm still very new to python, so I only know to use something like filename.write(str(listname)) to write my list to a file.. Is there a straightforward method of combining the ease of the print function setup that you suggested with write? Or could I somehow use the print function itself to write to the file (rather than just output to my shell/prompt)? Thanks! Quoting W W : On Fri, Apr 24, 2009 at 10:57 PM, Matt Domeier wrote: Hello, I have a series of lists that I need to output into files with a specific format. Specifically, I need to have line breaks after each entry of the list, and I need to do away with the ['..'] that accompany the data after I transform the list into a string. Can I simply append a '\n' to the end of all the list entries in order to enact line breaks? Is this what you're looking for? In [3]: print '\n'.join(['the quick brown fox', 'jumps over', 'the lazy dog']) the quick brown fox jumps over the lazy dog HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] glob paramiko
Hey All. All I need to do in this script is scp or sftp a bunch of files to a remote server. This script will run from a cron job eventually. For whatever reason, paramiko can't cope with a list. --- AttributeErrorTraceback (most recent call last) /Users/msh/ in () AttributeError: 'NoneType' object has no attribute 'put' In [18]: type localpath ---> type(localpath) Out[18]: In [19]: for each in localpath -- script begins import paramiko import glob import os paramiko.util.log_to_file('/tmp/paramiko.log') host = "sftp.okcomputer.yo" port = 22 transport = paramiko.Transport((host, port)) password = "T0pS3kr1t!" username = "schizznits" transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) os.chdir("/home/fatcat/") filepath = '/' localpath = glob.glob("*.tab") sftp.put(localpath, filepath) sftp.close() transport.close() --- script ends -- -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] glob paramiko
On Fri, May 08, 2009 at 02:30:22PM -0400, Kent Johnson wrote: > On Fri, May 8, 2009 at 1:04 PM, Matt Herzog wrote: > > Hey All. > > > > All I need to do in this script is scp or sftp a bunch of files to a remote > > server. This script will run from a cron job eventually. > > > > For whatever reason, paramiko can't cope with a list. > > > > --- > > AttributeError ? ? ? ? ? ? ? ? ? ? ? ? ? ?Traceback (most recent call last) > > > > /Users/msh/ in () > > > > AttributeError: 'NoneType' object has no attribute 'put' > > It would be helpful to see the full stack trace. Here it is, unless I can give you something more verbose. Not sure how to produce "full stack trace." Do you mean this: http://docs.python.org/library/traceback.html ? (15)[datas...@iggy ~/AIG]$ ./parameek0.py Traceback (most recent call last): File "./parameek0.py", line 24, in ? sftp.put(localpath, filepath) File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 547, in put TypeError: coercing to Unicode: need string or buffer, list found > > > sftp = paramiko.SFTPClient.from_transport(transport) > > > > os.chdir("/home/fatcat/") > > filepath = '/' > > localpath = glob.glob("*.tab") > > sftp.put(localpath, filepath) > > It looks like sftp is None. That is why it has no attribute "put". Yeah, it shows up as a type list. I haven't been doing any python thinking in a couple months. The script works without the glob syntax on a single file defined as: localpath = '/home/foo/bar.txt' Thanks for helping. > > Kent -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] paramiko again
Hello again. This code comes straight from the http://oreilly.com/catalog/9780596515829/ book. The only actual code I changed was s/get/put on the second to last line. The author says I ought to be able to do this and have it Just Work. There are several things I don't understand. Would be nice if the books' author was on this list so I could ask him directly. Heh. The code runs but does not upload any files. I would rather be specifying the local dir on the source machine rather than path on the destination. 1. How can paramiko know whether the dir_path is on the local vs remote system? 2. I can't find sftp.put or sftp.get in ipython. Are they part of paramiko? If not, where do they come from? Thanks for any insight. --- begin -- #!/usr/bin/env python import paramiko import os hostname = '192.168.1.15' port = 22 username = 'revjimjones' password = 'C0ol4id3' dir_path = '/home/revjimjones/logs' if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) files = sftp.listdir(dir_path) for f in files: print 'Uploading', f sftp.put(os.path.join(dir_path, f), f) t.close() end --- -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] paramiko again
On Sun, May 10, 2009 at 12:53:49AM +0100, Alan Gauld wrote: > Have you used normal ftp in its command line version? > The put command specifies the location on the remote machine > where you want to store the files. This is normal ftp behaviour. The server supports only sftp. Yeah, I could turn on ftp on some server but that would be more work. Heh. > Yes. sftp is an object that you create with a call from paramiko. > The class exists in paramiko and you create an instance of it > called sftp. Oh. I could call it anything, not that I'd want to. Thanks. I kept thinking I could find it using ipython. > So you are trying to upload files that currently exist on the > remote machine from your machine, that is unlikely to work. Yes. That was not the plan though. Heh. > I suspect you probably need to change the listdir() call to use > os.listdir(local_path) instead of stftp.listdir(). Where local_path > is wherever you store the files on the local mnachine that you > want to transfer. Yes, that is exactly what I wanted, os.listdir. But now I have another issue: specifying the remote dir. When I login to the sftp server and type pwd: sftp> pwd Remote working directory: / Is what I see. Also, I don't think I want "join" in the below, do I? Why do I want to "join" the two dirs? As far as I'm concerned, I just want to dump files into the only dir I can reach, which is "/" on the remote host's jail. sftp.get(os.path.join(dir_path, f), f) > > HTH, It did help. Many thanks! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] moving files from one dir to another
Should be simple, right? Not for me, heh. def schmove(src,dst): ... src = '/home/datasvcs/PIG/cjomeda_exp/' ... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/' ... listOfFiles = os.listdir(src) ... for filez in listOfFiles: ... os.system("mv"+ " " + src + " " + dst) The above code does not copy anything. I sure wish it would spit just one error. I sure wish I could for the last line go, shutil.move("src", "dest") That would be cool. Plz halp! -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] simply moving files
On monday I posted the below code: def schmove(src,dst): ... src = '/home/datasvcs/PIG/cjomeda_exp/' ... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/' ... listOfFiles = os.listdir(src) ... for filez in listOfFiles: ... os.system("mv"+ " " + src + " " + dst) David Angel replied to my post and I guess I accidentally deleted his response. Today I found his response posted on mail-archive.com and tried some variations. They all failed. David said, "Just use os.rename() if the dest is a directory, it'll move the file there." Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " + src + " " + dst)" no files are coppied. os.renames happily renames the source directory, but that's not what I want. Any other suggestions? -- Matt -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sftp get single file
Hello All. I need to use paramiko to sftp get a single file from a remote server. The remote file's base name will be today's date (%Y%m%d) dot tab. I need help joining the today with the .tab extension. Do I need globbing? example: 20090716.tab #!/usr/bin/env python import paramiko import glob import os import time hostname = 'sftp.booboo.com' port = 22 username = 'booboo' password = '07N4219?' # glob_pattern='*.tab' today = time.strftime("%Y%m%d") remotepath = today.tab localpath = '/home/data/text' if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(remotepath, localpath) t.close() -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
On Fri, Jul 17, 2009 at 12:12:52PM -0400, Kent Johnson wrote: > On Fri, Jul 17, 2009 at 11:42 AM, Sander Sweers > wrote: > > > import time > > > > today = time.localtime() > > datestr = time.strftime("%Y%m%d",today) > > ext = ".tab" > > > > print datestr + ext > > You can include literal characters in the format string: > > In [4]: time.strftime("%Y%m%d.tab",today) > Out[4]: '20090717.tab' That does work and is compact while being intelligible. I'm still not getting the file. I thought this would work: if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp(remotepath,localpath) t.close() . . . but obviously something is missing. Traceback (most recent call last): File "./scpgetter.py", line 20, in ? sftp(remotepath,localpath) TypeError: 'SFTPClient' object is not callable I tried using the paramiko.SFTP.get method too. Failed. -- Matt H > > Kent -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
On Mon, Jul 20, 2009 at 10:22:37PM +0200, Sander Sweers wrote: > I do not know paramiko but looking over the client documentations... > > 2009/7/20 Matt Herzog : > > if __name__ == "__main__": > >t = paramiko.Transport((hostname, port)) > >t.connect(username=username, password=password) > >sftp = paramiko.SFTPClient.from_transport(t) > > Up to here it looks fine. > > >sftp(remotepath,localpath) > > If I understand it correctly you need to use sftp.get(remotepath, localpath). Yeah that's exactly what I have tried, and the error is: Traceback (most recent call last): File "./scpgetter.py", line 20, in ? sftp.get(remotepath, localpath) File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 584, in get File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 240, in open File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 609, in _request File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 656, in _read_response File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 682, in _convert_status IOError: (2, '') > > Greets > Sander > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
On Mon, Jul 20, 2009 at 11:02:52PM +0200, Sander Sweers wrote: > 2009/7/20 Matt Herzog : > > Traceback (most recent call last): > > ??File "./scpgetter.py", line 20, in ? > > ?? ?? ??sftp.get(remotepath, localpath) > > ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", > > line 584, in get > > ?? ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", > > line 240, in open > > ?? ?? ?? ?? ?? ??File > > "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 609, in > > _request > > ?? ?? ?? ?? ?? ?? ??File > > "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 656, in > > _read_response > > ?? ?? ?? ?? ?? ?? ?? ??File > > "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 682, in > > _convert_status > > ?? ?? ?? ?? ?? ?? ?? ??IOError: (2, '') > > Ah, now it get interesting. Genrally IOError means the file is not > found. And looking at the source for _convert_status it is axactly > that. The file you are trying to "get" is not found on the server so > check your remotepath. The file is there. I can sftp it using fugu. The path is /20090720.tab since the file lives in a jail. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
If I change remotepath = 'datestr' to remotepath = datestr I get: sftp.get(remotepath, localpath) File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 587, in get IOError: [Errno 21] Is a directory: '/tmp/testor/' So remotepath is really more like a path + filname. So I need to do something like os.join the two? -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] paramiko list user said,
A user of the paramiko mailing list said, "Paramiko has an SFTPClient class and an SSHClient that can be used to transfer files, why complicate it by using a Transport directly. The easiest thing is to open an SSHClient: c=paramiko.SSHClient() c.connect(username=username_, password=password_, hostname=hostname_)s=c.open_sftp() s.get/put etc.. " He lost me on the s.get/put part. I suppose he means s.get(remotepath, localpath) . . . or something. -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
On Mon, Jul 20, 2009 at 11:57:57PM +0200, Sander Sweers wrote: > Please reply to the list. > > 2009/7/20 Matt Herzog : > > Yeah. I have no idea if I am able to do this. The jail makes it ambiguous. > > There is no difference, the jail just moves the root directory as seen > by the client. > > Did you do as suggested earlier to use listdir()? This will tell you > how paramiko sees the server. Yeah, I managed to get that to work like so: if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) print sftp.listdir() t.close() It displays the contents of the dir no problem. > > I get the feeling you are in on over your head on this. Yes, and I have a deadline. > Maybe you need > to read the paramiko docs and play around in idle or other interactive > python interpreter. The SFTPClient has all the basic commands any ssh > client has (listdir, chdir etc). See [1]. I should not need to chdir, right? In fact, the server's policy forbids it. Perhaps I need to chdir on the local host? > Also have a look at [2] which is a good example of what can be done. Yeah I saw that page. The code seemed bloated to me. > > Greets > Sander > > [1] http://www.lag.net/paramiko/docs/paramiko.SFTPClient-class.html > [2] http://code.activestate.com/recipes/576810/ > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sftp get single file
On Mon, Jul 20, 2009 at 05:26:09PM -0500, Wayne wrote: > On Mon, Jul 20, 2009 at 5:18 PM, Matt Herzog wrote: > > > On Mon, Jul 20, 2009 at 11:57:57PM +0200, Sander Sweers wrote: > > > Please reply to the list. > > > > > > 2009/7/20 Matt Herzog : > > > > Yeah. I have no idea if I am able to do this. The jail makes it > > ambiguous. > > > > > > There is no difference, the jail just moves the root directory as seen > > > by the client. > > > > > > Did you do as suggested earlier to use listdir()? This will tell you > > > how paramiko sees the server. > > > > Yeah, I managed to get that to work like so: > > > > if __name__ == "__main__": > >t = paramiko.Transport((hostname, port)) > >t.connect(username=username, password=password) > >sftp = paramiko.SFTPClient.from_transport(t) > > print sftp.listdir() > >t.close() > > > > It displays the contents of the dir no problem. > > > Is the file present in the dir? What is it listed as? Is it just > 07232009.tab (or similar) or is it /home/user/jail/07232009.tab? That may > make a difference. Yes, the file 20090720.tab (today's date dot tab) is present in the dir listing. The dir contents are printed out in a comma delimited list from left to right that wraps several times. There are probably 30 subdirs and a dozen files in that dir. If you use the sftp cli binary and type, 'pwd' it tells you, '/'. > > > > > > > > > > > > I get the feeling you are in on over your head on this. > > > > Yes, and I have a deadline. > > > > > Maybe you need > > > to read the paramiko docs and play around in idle or other interactive > > > python interpreter. The SFTPClient has all the basic commands any ssh > > > client has (listdir, chdir etc). See [1]. > > > > I should not need to chdir, right? In fact, the server's policy forbids it. > > Perhaps I need to chdir on the local host? > > > That shouldn't make a difference as far as getting the file is concerned - > unless you're trying to put it in a file on your computer that doesn't > exist! I'm trying to put a file in a dir called /tmp/testor. The user the script runs as owns the dir. > > I'd really recommend playing around in the interpreter - especially if you > have ipython. I have ipython. I like ipython. I just don't get enough opportunities to do python scripting. > > Good luck, HTH, > Wayne -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] updating Unix config file
Hi All. The below script seems to work well enough to use but I'm wondering if I'm doing the file edit stuff in a "kosher" manner. I was just reading the Lutz O'Reilly "Learning" book and remembered that strings are immutable. So how was I able to change the strings for my dotted quad? I did not explicitly open a separate file in /tmp and then overwrite the ipf.conf file which seemed like the safer way. Yet somehow the below syntax works. Also I need to figure out how to update the LASTKNOWN variable after my IP changes. Thanks for any advice. import socket # import fileinput import subprocess import string import re SENDMAIL = "/usr/sbin/sendmail" CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] LASTKNOWN = '173.48.204.168' if CURRENT == LASTKNOWN: print 'Nevermind.' subprocess.sys.exit() else: cf = open("/etc/ipf.conf", "r") lns = cf.readlines() lns = "".join(lns) # close it so that we can open for writing later lns = re.sub(LASTKNOWN, CURRENT, lns) cf = open("/etc/ipf.conf", "w") cf.write(lns) cf.close() subprocess.call('/sbin/ipf -Fa -f /etc/ipf.conf', shell=True) subprocess.call('/sbin/ipnat -CF -f /etc/ipnat.conf', shell=True) ptchew = subprocess.Popen("%s -t" % SENDMAIL, "w") ptchew.write("To: m...@blisses.org\n") ptchew.write("Subject: YOUR IP ADDRESS HAS CHANGED\n") ptchew.write("\n") # blank line separating headers from body ptchew.write("Your IP address has changed to: ") ptchew.write(CURRENT) ptchew.write(time.asctime()) ptchew = p.close() -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > "Matt Herzog" wrote > > >remembered that strings are immutable. > >So how was I able to change the strings for my dotted quad? > > You didn't. > > >LASTKNOWN = '173.48.204.168' > > lns = cf.readlines() > > lns = "".join(lns) > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > I assume this is the line in question? > sub() returns a new string containing the substitutions. > > HTH, Yes! It sure does help. I just discovered that my script does not exit if the CURRENT IP is the same as the LASTKNOWN IP. -- snip -- CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] -- snip -- Turns out the above is an unreliable way to get the IP of the interface since the machine the above is running on does not have a proper hostname and is a dhcp client on a broadband network. Anyway, I'd like a hint as to how I could convert this: ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() x = string.split(ifcfg_lines[3])[1] to the subprocess module. The os module is going away, right? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Mon, Oct 19, 2009 at 07:51:06PM -0400, Matt Herzog wrote: > On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > > > "Matt Herzog" wrote > > > > >remembered that strings are immutable. > > >So how was I able to change the strings for my dotted quad? > > > > You didn't. > > > > >LASTKNOWN = '173.48.204.168' > > > lns = cf.readlines() > > > lns = "".join(lns) > > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > > > I assume this is the line in question? > > sub() returns a new string containing the substitutions. > > > > HTH, > > Yes! It sure does help. I just discovered that my script does not exit if the > CURRENT IP is the same as the LASTKNOWN IP. Please ignore the above. > -- snip -- > CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] > -- snip -- > Turns out the above is an unreliable way to get the IP of the interface since > the machine the above is running on does not have a proper hostname and is a > dhcp client on a broadband network. It's unreliable because it uses DNS, I believe. I'm not faulting the author. > > Anyway, I'd like a hint as to how I could convert this: > > ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > x = string.split(ifcfg_lines[3])[1] > > to the subprocess module. The os module is going away, right? > > > > > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > -- > The test of a first-rate intelligence is the ability to hold two opposed > ideas in the mind at the same time, and still retain the ability to function. > > -- F. Scott Fitzgerald > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Tue, Oct 20, 2009 at 08:29:59AM +0100, Alan Gauld wrote: > "Matt Herzog" wrote > > >Anyway, I'd like a hint as to how I could convert this: > > > >ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > >x = string.split(ifcfg_lines[3])[1] > > > >to the subprocess module. The os module is going away, right? > > The os module is not going away although the popen > function might some day. > > However subprocess is currently the recommended way > to do subprocess control and is more powerful and flexible > than popen. > > Did you see the subprocess documentation page that > shows how to do the equivalent of popen etc? > Look down to section 18.1.3.5 Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. > > http://docs.python.org/library/subprocess.html#module-subprocess > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Tue, Oct 20, 2009 at 02:49:53PM +, Tiago Saboga wrote: > On Tue, Oct 20, 2009 at 2:44 PM, Matt Herzog wrote: > > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to > > explicitly import PIPE from subprocess or python had no clue as to what > > PIPE was! > > > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't > > importing the subprocess module make all its methods available? I can't > > remember having to do this before. > > It is really like any other module. If you just import subprocess, you > can access all its methods and attributes by spelling it out: > > import subprocess > handler = subprocess.Popen(['cat'], stdout=subprocess.PIPE, > stdin=subprocess.PIPE) > > Or you can import just the names you will use in the global namespace: > > from subprocess import Popen, PIPE > handler = Popen(['cat'], stdout=PIPE, stdin=PIPE) > > HTH, It does help. I never knew this. I don't remember seeing this quirk before. Thanks. > > Tiago Saboga. -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Tue, Oct 20, 2009 at 07:53:17AM -0700, Steve Willoughby wrote: > On Tue, Oct 20, 2009 at 10:44:16AM -0400, Matt Herzog wrote: > > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to > > explicitly import PIPE from subprocess or python had no clue as to what > > PIPE was! > > > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't > > importing the subprocess module make all its methods available? I can't > > remember having to do this before. > I have been reading python books and trying to learn python for about a year now and this has never met my attention before. Thanks. > It's always been like that. Otherwise we'd have lots of collisions between > module global > names that namespaces are designed to avoid in the first place. So you > either name them > explicitly, or import them explicitly: > > import subprocess > # now you can reference subprocess.PIPE > > --or-- > > from subprocess import Popen, PIPE > # now you can reference PIPE without the namespace identifier > > --or-- > > from subprocess import * > # but I don't recommend this one (caution! danger!) > -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] cookielib and form authentication woes
dear tutors, I'm trying to use a GPS tracking service called InstaMapper. The service changes how frequently it updates the tracking device's position based on whether the UI is being accessed on the InstaMapper webpage. I'd like to have the increased update frequency happen all the time so I thought I'd write a python script to login to my account and access the page periodically: import urllib2, urllib, cookielib cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) params = urllib.urlencode(dict(username_hb='user', password_hb='resu')) opener.open('http://www.instamapper.com/fe?action=login', params) if not 'id' in [cookie.name for cookie in cj]: raise ValueError, "Login failed" # now try secured page resp = opener.open('http://www.instamapper.com/fe?page=track&device_key=abc ') print resp.read() resp.close() The ValueError is raised each time. If I remove this and read the response, the page thinks I have disabled cookies and blocks access. Why isn't cj grabbing the InstaMapper cookie? Are there better ways to make the tracking service think I'm viewing my account constantly? -Matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Database
I would recommend KirbyBase as a quick starter - it's nice and simple, and outputs text files, so you can always check things manually. http://www.netpromi.com/kirbybase.html Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] References in loops
In Python, one bug that often bites me is this: (example A) aList = [1,2,3] for i in aList: i += 1 print aList --> [1,2,3] This goes against my intuition, which is that aList == [2,3,4], probably because so much in Python is passed by reference and not by value. Of course I can always use range() or enumerate(): (example B) aList = [1,2,3] for i in range(len(aList)): aList[i] += 1 print aList --> [4,5,6] But example A seems more elegant, if only it did what I wanted it to do. :) So pardon my ignorance if the answer is obvious, but what is the simplest way in Python to get a reference to an element in a list? Is it really Example B? Thanks, Matt (My apologies if this double-posts; I accidentally sent it previously from a non-subscribed address. Moderator, please deny the other copy.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] OT: Google Gmail Accounts
If anyone is interested in an invitation to Google GMail, let me know and I will send you a free invitation to join. It works great for organizing mailing lists and with 1000 MB of storage, you don't have to manage your inbox. -- Have you seen the dog lately? Email - [EMAIL PROTECTED] Blog - invisibledog.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Filtering a String
Dear List, I'm trying to filter a file, to get rid of some characters I don't want in it. I've got the "Python Cookbook", which handily seems to do what I want, but: a) doesn't quite and b) I don't understand it I'm trying to use the string.maketrans() and string.translate(). From what I've read (in the book and the Python Docs), I need to make a translation table, (using maketrans) and then pass the table, plus and optional set of characters to be deleted, to the translate() function. I've tried: #!/usr/bin/python import string test="1,2,3,bob,%,)" allchar=string.maketrans('','') #This aiming to delete the % and ): x=''.translate(test,allchar,"%,)") but get: TypeError: translate expected at most 2 arguments, got 3 Please could someone explain this to me (slowly). As a measure of my slowness: This is my first programming language I couldn't get the tutor list to work for ages - until I realised I was sending all the desperate pleas for help to tutor-request. Perhaps there is no hope.. Matt Williams ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Accessing List items
Dear List, Thanks for the help with the previous problem - now all solved! I have a question about accessing lists. I'm trying to do something to each item in a list, and then assign it back into the list, overwriting the old value. However, the first loop here doesn't work, whereas the second loop does - but is very ugly. x = "200% inv_nodes=0-2 node_caps=no" y=x.split() for i in y: i="z" print y for i in range(len(y)): y[i]="z" print y Surely there must be a better way than this ? Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused "from module import Name" better than "import module"?
Kent Johnson wrote: > from module import * is problematic and discouraged. It causes namespace > pollution and makes it harder to find out where a name is defined. > > Other than that I think it is personal preference. > I have avoided the 'from module import *' style for the reasons you mentioned, but I have a question about 'import module' versus 'from module import name': is there a performance hit to consider when importing the entire module rather than just getting the specific niceFunction()? Right now,it's more of a curiousity as my programs are fairly small and don't do a whole lot. I would imagine that there would be a penalty, but for now I'm happy with keeping my namespaces distinct and knowing what came from where at a glance. Matt -- Matt Richardson IT Consultant College Of Arts & Letters CSU San Bernardino (909)537-7596 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused "from module import Name" better than "import module"?
Kent Johnson wrote: > > This is good stuff to understand, but really, it isn't going to make an > appreciable difference in most applications. Where it does matter, for > example if func() is called many times in a loop, the best solution will > probably be to bind func to a local variable which is the fastest to access. > > Pick the style that you find most practical and readable and don't worry > about efficiency. > > Kent Thanks for the explanation. It won't make a difference in this really short program I'm putting together, but I was curious about it. Going through the library reference I found a bunch of modules that would replace some ugly (but working) code I had, then started to wonder if importing a bunch of different modules would have much of an effect. In any case, I'm more concerned with readability. Matt -- Matt Richardson IT Consultant College Of Arts & Letters CSU San Bernardino (909)537-7596 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python FTP GUI - Possible project ?
Dear List, Does anyone know of a Python FTP GUI tool ? Preferably based around pyGTK+ ? I've had a look (Google, vaults of Parnassus, etc.) but haven't found one. If there isn't one, then would people consider it a useful project for newbie programmers (like myself). There have often been questions along the lines of "Where can I find projects to get involved in", and I thought this might help. Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to test for a remainder from division
Hi there, I'm trying to write a short function to test whether a year is a leap year or not. To do this I need to check whether the year divides exactly by 4, 100 and 400. I can't think of an easy way to test whether there is a remainder or not. The best I can come up with so far is: if (year / 4.0) - (year // 4.0) <> 0: This doesn't seem to work, it is always True, is there a problem with the comparison? The arithmetic seems to be the correct way to isolate the remainder of the division. Can anyone suggest a better way of performing this test or alternately, how can I get the line above to work. Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to test for a remainder from division
Hi, Thanks for all the help, I guessed that there would be a module out there providing a function to do this but wanted to go through the process as a learning exercise. The modulus operator was just what I was looking for, I had been trying to check for a difference between the division and the floor division - a bit of a long winded way of doing things. Here is the final code I have come up with, any comments? # A program to determine whether a year is a leap year or not def is_leap_year(year): # Function that accepts a year as input and returns true if it is a leap year, false if it is not if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): return True else: return False # Main program logic year = raw_input("What year? ") year = int(year) if is_leap_year(year): print year, "is a leap year." else: print year, "is not a leap year" Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help with excetion handing and making my code more efficient needed please
Hi, I am trying to write a simple program to display Conway's Game Of Life. I have the bones of the program together but I'm struggling with the function that tests for and applies the rules of the game (the important bit). I have the current state of the game stored in a 2d matrix with each cell represented by a 1 or 0 (alive or dead) i.e: [[0, 1, 0], [1, 0, 0], [0, 0, 0]]. I'm using a 15 * 15 matrix for testing purposes. I have come up with the following function to update the matrix so far: def update_matrix(matrix): matrix_updated = [matrix] # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 if matrix[x-1][y+1]: neighbour_count = neighbour_count + 1 if matrix[x][y+1]: neighbour_count = neighbour_count + 1 if matrix[x+1][y+1]: neighbour_count = neighbour_count + 1 if matrix[x+1][y]: neighbour_count = neighbour_count + 1 if matrix[x+1][y-1]: neighbour_count = neighbour_count + 1 if matrix[x][y-1]: neighbour_count = neighbour_count + 1 if matrix[x-1][y-1]: neighbour_count = neighbour_count + 1 if matrix[x-1][y]: neighbour_count = neighbour_count + 1 # Apply game of life rules to each item in the matrix if 2 < neighbour_count > 3: matrix_updated[x][y] = 0 elif neighbour_count == 3: matrix_updated[x][y] = 1 # No need to change values if neighbour count == 2 return matrix_updated I have two problems with this code: Firstly, when testing cells on the edges of the matrix, I get an IndexError because I am testing an item in the list that does not exist. I want the program to assume that cells outside the bounds of the board are automatically dead. I am not sure how to suppress or avoid this error so that neighbour_count is not incremented for indexes outside the matrix. My second problem is that this function seems to be very clunky to me (even if it did work...). I cannot think of a way of checking each of the 8 cells surrounding the one being tested without doing it this way. Is there a better way of doing this? Thanks in advance, Matt. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with excetion handing and making my code more efficient needed please
On Fri, 2007-05-18 at 23:49 +0200, Rikard Bosnjakovic wrote: > Something like this: > > try: >the_index_outside_matrix_test() > except IndexError: > suppress_the_error() Thanks Rikard, I'm not sure how I would go about actually suppressing the error - what would suppress_the_error() actually call? Cheers, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with excetion handing and making my code more efficient needed please
> > Is there a better way of doing this? > > Perhaps something like this: > > for n in (x, x+1, x-1): > for m in (y, y+1, y-1): > if matrix[n, m]: > neighbour_count = neighbour_count + 1 > I need to not text matrix[x][y] is there a simple way to exclude this from the possible combinations of values from the two tuples? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with excetion handing and making my code more efficient needed please
> the possible combinations of values from the two tuples? > see my other reply, Matt. > -Luke Hi Luke, Sorry if I'm missing something but which other reply? Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with excetion handing and making my code more efficient needed please
On Fri, 2007-05-18 at 17:03 -0500, Luke Paireepinart wrote: > see my other reply, Matt. > -Luke Apologies Luke, I have found your earlier post in the tutor archives - I don't seem to have received it from the list yet. Thanks for the help. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Still having trouble with my game of life algorithm
Hi, First of all, thanks to everyone who helped with my last post (http://mail.python.org/pipermail/tutor/2007-May/054360.html). I have re-written the function that applies the rules but it still doesn't return the expected result. I have been through it and corrected a couple of bugs bet as far as I can tell it should return a matrix that has had the rules of Conway's game of life (http://en.wikipedia.org/wiki/Conway%27s_game_of_life) applied. Here is my function: def update_matrix(matrix): matrix_updated = matrix # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 for n in (x-1, x, x+1): for m in (y-1, y, y+1): try: if matrix[m][n]: if (n,m) != (x,y): neighbour_count = neighbour_count + 1 except IndexError: pass # Apply game of life rules to each item in the matrix if neighbour_count < 2: matrix_updated[y][x] = 0 elif neighbour_count > 3: matrix_updated[y][x] = 0 elif neighbour_count == 3: matrix_updated[y][x] = 1 # No need to change value if neighbour count == 2 return matrix_updated I have also attached the full program and the input file that I am using for testing in case anyone is interested. The program does use curses to display the board so I guess it won't be any good for Windows users. I hope someone can see where I am going wrong here. Thanks, Matt #! /usr/bin/env python import curses def read_start(): # Read the starting configuration from a text file file = open('/home/matt/Python/game_of_life/r-pentomino.txt', 'r') matrix = [] for line in file: line = line.rstrip('\n') line_list=[] for i in range(len(line)): line_list.append(int(line[i])) matrix.append(line_list) return matrix def draw_board(matrix, stdscr, generation): # Draw the life board based on the matrix containing the current state for x in range(len(matrix[0])): for y in range(len(matrix)): if matrix[y][x]: stdscr.addch(y + 1, x + 1, '*') else: stdscr.addch(y + 1, x + 1, '.') stdscr.addstr(len(matrix) + 1, 0, 'Generation: %s' % (generation)) stdscr.refresh() def update_matrix(matrix): matrix_updated = matrix # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 for n in (x-1, x, x+1): for m in (y-1, y, y+1): try: if matrix[m][n]: if (n,m) != (x,y): neighbour_count = neighbour_count + 1 except IndexError: pass # Apply game of life rules to each item in the matrix if neighbour_count < 2: matrix_updated[y][x] = 0 elif neighbour_count > 3: matrix_updated[y][x] = 0 elif neighbour_count == 3: matrix_updated[y][x] = 1 # No need to change value if neighbour count == 2 return matrix_updated def main(stdscr): # Initialise some variables and put the screen in it's starting configuration matrix = read_start() generation = 1 draw_board(matrix, stdscr, generation) stdscr.addstr(len(matrix) + 2, 0, 'Press to advance a generation, to quit.') # The main program loop - respont to keyboard input while 1: key_press = stdscr.getkey() if key_press == 'q': break elif key_press == ' ': generation = generation + 1 matrix = update_matrix(matrix) draw_board(matrix, stdscr, generation) # Run the main program inside the curses wrapper to ensure it leaves the screen in a usable state` curses.wrapper(main) 000 000 000 000 000 000 0001100 0011000 0001000 000 000 000 000 000 000 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] More trouble debugging my game of life program
Hi, I've got my program working correctly (or so it seems) with my original data file (r-pentomino.txt - attached) but when I run it with a larger (30*30) file (big-r-pentomino - also attached) in an attempt to make it work with out so many edge effects it returns the following error message: Traceback (most recent call last): File "Python/game_of_life/life.py", line 75, in curses.wrapper(main) File "curses/wrapper.py", line 44, in wrapper File "Python/game_of_life/life.py", line 60, in main draw_board(matrix, stdscr, generation) File "Python/game_of_life/life.py", line 28, in draw_board stdscr.addch(y + 1, x + 1, ' ') _curses.error: addch() returned ERR I thought I had designed the program to work with any text file as long as the lines are all the same length so I cannot understand why I get this error message. When I read through the code I cannot see a reason why the program should work for one size file and not another. The part of the program that is failing is just drawing a space character at a particular location on the screen. Here is the listing of the program that I have also attached: #! /usr/bin/env python # Curses based Game of Life program # Written by Matt Smith import curses from copy import deepcopy def read_start(): # Read the starting configuration from a text file file = open('/home/matt/Python/game_of_life/r-pentomino.txt', 'r') matrix = [] for line in file: line = line.rstrip('\n') line_list=[] for i in range(len(line)): line_list.append(int(line[i])) matrix.append(line_list) return matrix def draw_board(matrix, stdscr, generation): # Draw the life board based on the matrix containing the current state for x in range(len(matrix[0])): for y in range(len(matrix)): if matrix[y][x]: stdscr.addch(y + 1, x + 1, '*') else: stdscr.addch(y + 1, x + 1, ' ') stdscr.addstr(len(matrix) + 1, 0, 'Generation: %s' % (generation)) stdscr.refresh() def update_matrix(matrix): matrix_updated = deepcopy(matrix) # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 for n in (x-1, x, x+1): for m in (y-1, y, y+1): try: if matrix[m][n]: if (n,m) != (x,y): neighbour_count = neighbour_count + 1 except IndexError: pass # Apply game of life rules to each item in the matrix if neighbour_count < 2: matrix_updated[y][x] = 0 elif neighbour_count > 3: matrix_updated[y][x] = 0 elif neighbour_count == 3: matrix_updated[y][x] = 1 # No need to change value if neighbour count == 2 return matrix_updated def main(stdscr): # Initialise some variables and put the screen in it's starting configuration matrix = read_start() generation = 1 draw_board(matrix, stdscr, generation) stdscr.addstr(len(matrix) + 2, 0, 'Press to advance a generation, to quit.') # The main program loop - respond to keyboard input while 1: key_press = stdscr.getkey() if key_press == 'q': break elif key_press == ' ': generation = generation + 1 matrix = update_matrix(matrix) draw_board(matrix, stdscr, generation) # Run the main program inside the curses wrapper to ensure it leaves the screen # in a usable state curses.wrapper(main) Can anyone come up with the reason why one input file works and the other one doesn't?? Thanks, Matt 0 0 0 0 0 0 0 0 0 0 0 0 0 00110 01100 00100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 000 000 000 000 000 0011000 011
[Tutor] Suggestions for a first object orientated program
Hi, I have been reading up on OOP in Python recently and feel ready to attempt my first program using OOP principals. Can anyone suggest a suitable first OOP project for me to get my teeth into? I haven't done any real GUI programming but I have started gutting to grips with the curses module under Linux (see my posts about the game of life program). The game of life program might also show the kind of stage I am at with my learning of Python at the moment. Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More trouble debugging my game of life program
On Sun, 2007-06-03 at 18:09 -0400, Brian van den Broek wrote: > The first thing I would do to try to track down the problem would be > to try 15x30 and 30x15 matrices. If you have two cases where one > behaves as expected and one does not, it is usually very useful to try > to match the two cases as closely as possible as an aid to pinpointing > the problem. Thanks Brian, Initially 15*30 worked but 30*15 didn't. I have just gradually increased the width of my text file up to 30 characters and it worked at 30*30 so I guess the problem must be with the text file I was using. Looking at my code - I can see it will break if the lists within the big list making up the matrix are not all the same length. Maybe this is something I need to test for in the program. Cheers, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Invoking Python from Vim
Hi, Bit of a Vim specific question this one but I hope someone might have an answer. I currently have the following line in my .gvimrc file (I'm using Ubuntu Linux): map :!gnome-terminal -e=python\ -i\ % This opens a window and runs the Python program I am working on. I don't really like the fact I can't do anything else in vim until I close the window and I don't really need the interactive prompt that I am left with. If I invoke Python without the -i then I don't get to see the error message if my program exits with an error. In 'normal' vim I use: map :w\|!python % This doesn't work for GVim which I prefer to use. Do any Vim users have a better way of running a Python program while it is being edited in Vim? Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python IDE
Check out geany. It's fairly simple but I've found it very neat and simple. http://geany.uvena.de/ On 6/11/07, scott <[EMAIL PROTECTED]> wrote: Could someone suggest a few good IDE's for me to look at. I would need a IDE that haves syntax highlighting and I also really like type completion where the IDE gives you suggestions as you type. -m ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to keep trying something until it doesn't return an error?
Hi there, I am currently working on a noughts and crosses program to try and teach myself some very simple AI programming and also to start to use OOP in Python. I am currently writing the framework for the game so I can then write a number of functions or a class to deal with the strategy side of things. I'm stuck trying to write a method which will only accept a legal move and will keep asking until it gets a legal answer. I can see that working out how to do this efficiently will be very useful in my future programming as well. I currently have the following code. while 1: try: xpos = input ("Where do you want to go? ") gameboard.addx(xpos) gameboard.draw() break except cantgo: print "You can't go there!" which calls the following method: def addx(self,pos): if pos in range(1,10) and self.state[pos-1] == "": self.state[pos-1] = "X" else: raise cantgo The cells of the game are referenced by the numbers 1 to 9. The code gave the following error: Traceback (most recent call last): File "noughts_and_crosses.py", line 49, in except cantgo: NameError: name 'cantgo' is not defined Interesting the first pass of the code above did not return an error but the second pass did. Currently I have the same code twice for X's and O's. Next, I defined the error using: cantgo = "can't go" And now I get: noughts_and_crosses.py:33: DeprecationWarning: raising a string exception is deprecated raise cantgo You can't go there! But the program will not let me enter any (valid) move at all now. This looks like it is not breaking out of the while loop correctly, which, when I look back at my code, is to be expected. Is there a typical 'Pythonic' way of dealing with this situation. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Use of sqrt() from math module
Hi, I need to find the square root of a number in a program I am writing. I have imported the 'math' module so I thought I could just call sqrt(x) but I get an error message. Extact from my code and error message below. import sys, pygame, math ... if ypos >= 384 and velocity > 0: impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 160))) ... Traceback (most recent call last): File "", line 32, in ValueError: math domain error This one has me stumped as the usage of the module looks straight forward from the documentation. Thanks for looking. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Use of sqrt() from math module
Matt Smith wrote: > import sys, pygame, math > > ... > > if ypos >= 384 and velocity > 0: > impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * > 160))) > > ... > > > Traceback (most recent call last): > File "", line 32, in > ValueError: math domain error Apologies, the actual error I get when I run the code above is: Traceback (most recent call last): File "", line 31, in NameError: name 'sqrt' is not defined The error I quoted first was when I tried to call 'math.sqrt(x)' Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Use of sqrt() from math module
Michael H.Goldwasser wrote: > After using "import math" you will need to use the qualified name > math.sqrt(blah) to call the square root function. That explains the > NameError when trying to use the unqualified name, sqrt. > > As to your first message, the ValueError that you are reporting with > the usage math.sqrt is likely due to an attempt to take the square > root of a negative number (presumably because your (ypos - 384 * 160) > factor is negative. Thanks Michael and Ziyad, it seems I just had my brackets in the wrong place leading to trying to square root a number less than 0. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] hey i need some help here
I just started attempting to program and thought i would try python as my first tool. However following the beginners guide on their page it says to insert python as a command and that it should come up with the program information. When i insert python it says it is not recognizable as an internal or external command. can somebody help me? _ 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] IDEs
I've used both PyDev and Wing IDE. PyDev seems good, and is getting better. Wing is pay-for (although only $40 or so), but can be trialled. I thought it was good, but had a huge problem trying to get it to play with a C library I was using... I've never managed to get Boa-Constructor to run... As regards using wxPython - I thought it was ok, but frankly Glade was s much easier.. (all IMHO) Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python DB
Dear List, I've been looking for a simple python based DB for a fairly simple app. Only a single user, single access needed, but with a dynamic structure (which needs to be extensible very easily). Having googled and read some stuff, I seem to come down to a choice between KirbyBase (very nice and simple, and has the advantages of text- based files) or ZODB. I have a bit of an allergy to SQL, even if mediated via SQLObject (which looks very nice) These seem to be at the opposite end of the spectrum - so do others have either comments on these options, or other suggestions. Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python DB
Dear List, Thanks for all the advice! Obviously, I'm still a bit torn, but some of the ideas looked good. In terms of spec, the DB can be fairly simple (single access, etc.). Lower dependency on other libraries is good. Also, it needs to be cross- platform. The problem (I have) with SQL-type DB is that I cannot be sure ahead of time of the exact data structure. The DB will be about patients, who have diseases, and also have treatments.Clearly, I can't specify now the exact structure of the table. The advantage of SQL is that you can (in general) do things like constrain types for fields, and give enumerated options, which makes the data more consistent. The thing I liked about KirbyBase was that it used text files. This is a real advantage, as it means that I can access the data from other application easily, and also makes it easier to back-up (can just copy a few files). The same would seem to be true of the XML-based options. The advantage of ZODB was that the "object" structure seemed to map well to the concept of patients, with diseases, with treatments, etc. (and Shelve would work at least as a trial implementation) The final thing is that I needs to have a simple GUI frontend. The nice thing about ZODB is that I could just map the eventhandlers to functions on objects.. If people have more comments in the light of the bigger spec. above, I'd still love to hear them... Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Linking with C programs
Dear List, Could someone explain how, in very general terms, one would use python to wrap some C libraries/ API. I ask because there are a few bits of C software that look quite interesting, and I know that Python can be used to wrap the C - but how does it work? Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Accessing Variables
Dear List, I'm trying to clarify something about accessing variables. If I have ONE.py file with some variable a, and ONE imports TWO, which has a variable b, can TWO access variable a (I don't think so, but I just thought I'd check). I guess the way round this is just to make some classes & objects, and then they can easily pass parameters to each other, but I just thought I'd check. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 20, Issue 26: New Python Book
IMHO, as regards the book using wxPython, rather than Tkinter: I've failed to get Tkinter to compile on several installs, whereas I can usually get wxPython to work. Also, wx seems to be better documented.I know it's not ideal to pick one platform, but I would guess that wx would be a reasonable default. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Listing all of an instances variables
Dear List, I'm stuck on trying to write a generic 'report' function: Class SomeClass: def __init__(self,a,b): self.a = a self.b = b def report(self): for i in dir(self): print self.i This is where I run into problems: How do I return all of the variables in an instance? I'm sure I'm not the first person to ask, but I couldn't find an answer anywhere else... Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7384 899570 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with class overloading (maybe it's just me)
Hi all, I've started the wxPython tutorials and have hit a problem already. When run from IDLE or by calling the script from the command line with [EMAIL PROTECTED]:~/wxpy$ python helloWorld.py the script works fine, generating a small text editor. Making the file executable and including the shebang, running [EMAIL PROTECTED]:~/wxpy$ ./helloWorld.py generates a cross-hair looking mouse pointer. Clicking the mouse generates the following error: [EMAIL PROTECTED]:~/wxpy$ ./helloWorld.py ./helloWorld.py: line 6: syntax error near unexpected token `(' ./helloWorld.py: line 6: `class MainWindow(wx.Frame):' Which to me looks like it doesn't know what to do with wx.Frame, or some problem in extending the class. In the hello world example previous to this, there's no problem with wx.Frame and the program runs when executed from the command line. Here's the details: python 2.3.5 this one works: [EMAIL PROTECTED]:~/wxpy$ cat hello.py #!/usr/bin/python import wx app = wx.PySimpleApp() frame = wx.Frame(None, -1, "Hello World") frame.Show(1) app.MainLoop() this one fails: [EMAIL PROTECTED]:~/wxpy$ cat helloWorld.py #!/usr/bin/python import wx class MainWindow(wx.Frame): """ We simply derive a new class of Frame. """ def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(200,100), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE) self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.Show(True) app = wx.PySimpleApp() frame = MainWindow(None, -1, 'Small editor') app.MainLoop() I'm sure it's something simple I'm overlooking, so I'll go get a cup of coffee and see if someone with better eyes spots my error. thanks, Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with class overloading (maybe it's just me)
Danny Yoo wrote: > Hope this helps! Helped a lot. Shows that syntax errors aren't always visible (like whitespace) and that I should know better than to attempt anything before having at least one cup of coffee. Thanks! Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] General programming questions
Dear List, I've got a few general programming (not really specific to python, although you're all so helpful, I thought I'd ask here). I understand some of these are a bit long, so if you could just point me to some resources, I'd be very grateful. 1: I need to create objects that have variable levels of behaviour (controlled perhaps by a .config file). I can do the file reading, etc. - but how do I implement the behaviour, apart from just re-writing all the functions for each config level? 2: I need to implement polmorphism in some methods (and a constructor). At the moment, I have something like: def __init__ (self, a, b, c): if type(a) == type("a") then. elif type(a) == type(["a"]) then I'm sure there must be a better way to do this (both the polymorphism and the type testing) - but I don't know how to do it. Thanks a lot, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7384 899570 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Nokia 60 series
There's some extra info here: http://comments.gmane.org/gmane.comp.python.announce/5658 HTH, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Easier way to access wxPython
Dear All, Just a note: When the next question about "which GUI for Python" comes around (and I should plead guilty to having asked a few times) I thought that the Dabo framework, which wraps wxPython in a nicer API would be worth pointing to. And even if the question didn't get asked, I thought people might like to know... http://daboenv.com/ HTH, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Mono
Dear List, Slightly off topic, but could someone explain/ point me to a URL that explains how one might use Python with Mono (I guess it would be IronPython, rather than CPython), and what advantages it might give you (apart from a possible speed up of IronPython vs. CPython). I'm especially interested in the idea of being able to write different bits in different languages, and then run them all on Mono. Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python and Semantic Web
Dear List, Does anyone know of any python semweb tools? I'm especially interested in tools to build and handle ontologies. I've come across CWM (built by Tim BL) but not that much else. I'd be really interested in anything that can interface with a DIG reasoner. Really, I'm looking for a pythonic version of something like Protege or SWOOP Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Semantic Web
Mea Culpa, Mea Culpa, Mea Maxima Culpa (or, MCMCMMC to repeat my sin of poly-acronymony. Semantic Web - (loosely) the idea of incorporating semantic information in the WWW, so it becomes machine understandable (rather than just parsable). CWM is Tim Berners-Lee's (and others) tool to handle ontologies. I think it has some rules in-built, but for reasons of efficiency, most ontology tools communicte with external Description Logic Reasoners via the DIG (Desc. Logic Implementation Group) interface, which is http/XML based. Much of the semweb stuff is OWL (Web Ontology Language - need to be a Winnie The Pooh fan to get the acronym) based. OWL is a layer that lies on top of RDF (which in turn, lies on top of XML). In general, yu build an ontology in OWL, and then interface with a reasoner to infer more info. about the model. The two big ontology building tools are Protege (with the Protege OWL plugin) and SWOOP, but both are Java based. HTH. Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Latin Perl
The suprising thing about Latin Perl is that it's more readable than normal Perl.... Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Symbolic maths In Python
I don't know if this will do anywhere near what you want... http://swiginac.berlios.de/ is a set of Python bindings to GiNaC, which handles symbolic maths in C/C++. Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] TurboGears - and some issues
Dear Alan, I haven't used it, but I've looked through it, and it looks v. interesting. One of the things I like is that it glues lots of different bits together (I came across it while looking at SQLObject), and so benefits from their advances. I was a bit surprised that you hadn't come across it before, as in general you seem to be one of the core team on the list (in that you tend to answer rather than ask most questions). This got me thinking about how we stay up with different, and new, python projects. I tend to look at the Daily Python URL, as well as some Technorati and del.icio.us tagged sites/blogs. Where else do other people look? Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Favourite Modules - wiki
I think the Wiki's a great idea. del.icio.us already has a Python tagged page: http://del.icio.us/tag/python Other pages I use are: http://mechanicalcat.net/pyblagg.html http://www.planetpython.org/ I've added a couple of things to the Wiki - SQLObject and RSPython Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python on Fedora
FC4 (the latest finished one) has python 2.4.1 as part of the distro (I think RedHat actually use python for some of their scripts). Just pull up a terminal and type 'python' and you should get the prompt... If you _are_ running FC4 and have more probs, feel free to drop me a line. at matt at mwilliams.org and I can try and help (since I am sat in front of an FC4 machine). WRT EMACS, I've never tried to get it going I use Eclipse and PyDev, or else SPE is worth a look. HTH, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python DB
You might also want to have a look at DABO; I don't know how well it work on a handheld, though. http://dabodev.com/about Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Struggling with writing results of loop into txt file
I'm using xmltramp to process some U.S. House of Rep. vote data. I can get it to print what I want but when I try to write it to a text file I had all sorts of problems. Can someone tell me what I'm doing wrong? I've done quite a bit of searching for the solution but as a novice to Python I'm at a loss. Here's the script:#votes data #import xmltramp for reading XML files import xmltramp#load up the house page with the vote I wantd= xmltramp.load(' http://clerk.house.gov/evs/2006/roll002.xml' )#loads up the vote data off the sitevd= d['vote-data']#makes a happy nonhyphenated variable out of metamd= d['vote-metadata']#counts the number of votes per roll votes= len(vd)#Produces the name, party and outcome of every Arizona house member on this votefor each in range(votes): st= str(vd[each].legislator('state')) vt= str(vd[each].vote) nm= (vd[each].legislator('unaccented-name')) pt= str(vd[each].legislator('party')) f= file('housevote.txt', 'w') if st == 'AZ': f.write(nm) else: passf.close()Before trying to write it to a file, my loop looked like this: for each in range(votes): st= str(vd[each].legislator('state')) if st == 'AZ': print vd[each].legislator('unaccented-name'), vd[each].legislator('party'), vd[each].vote else: pass Any help would be most appreciated. Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] unicode issue?
I'm having a new problem with my House vote script. It's returning the following error: Traceback (most recent call last): File "C:/Python24/evenmorevotes", line 20, in -toplevel- f.write(nm+'*'+pt+'*'+vt+'*'+md['vote-result'][0]+'*'+md['vote-desc'][0]+'*'+'\n') UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 172: ordinal not in range(128) Here's the code: http://pastebin.com/615240What am I doing wrong? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sockets
Just verifying what I looked up earlier: are strings and binary (through struct.pack) the only data types that can be sent through a socket? This is my first crack at socket programming, so I'll probably have lots of questions to bug you with. thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sockets
I need to send some data, 2 strings and a list, to a remote computer. After thinking about it some last night, it wouldn't be hard to just send it all as a string and then parse it on the receiving end. I'm writing a program for work (and for a class project, so no answers!) that will provide some info on the network location of a laptop. The client will gather IP address, MAC address, and a traceroute dump (the list mentioned above), then send this off to a super simple server that receives the data and puts it in a database. We've had a few laptops 'disappear' either through theft or people taking them home to do 'work from home' or whatever. Makes annual inventory a huge pain. Matt -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino (909)537-7598 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sockets
Kent Johnson wrote: > > This would be very easy to do with XML-RPC. On the server side, writ a > function that takes three parameters - the IP address, MAC address, and > traceroute dump - and saves them to a database. Use SimpleXMLRPCServer > to expose the function. On the client side, gather the data and use > xmlrpclib to call the remote function. Easy. Since this function will > presumably be exposed on the public internet you need to worry about > security; you should use some kind of authorization. A really simple > solution would be to add username and password arguments to the function > you expose. I thought that might be overkill after quickly glancing at it in 'Foundations of Python Network Programming', but I think you might have just convinced me that it is actually the easier route. My original thought was that it could be just a simple string, sent via UDP, that would happen after networking was established but before log in. I had done something simpler before using a bash script and sendmail, but I really don't want my inbox plugged up with a bunch of 'phone home' messages :) Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] debug process
Bob Gailer wrote: > Kent Johnson wrote: >> [EMAIL PROTECTED] wrote: >> >>> Hello, >>> >>> Is there a way to debug (trace) the python code line by >>> line? >>> I'll put in my $.02 for SPE. PyChecker and Tab Nanny are built in and run as you code, which saved me from making lots of silly mistakes. -- Matt Richardson IT Consultant College of Arts and Letters CSU San Bernardino work: (909)537-7598 fax: (909)537-5926 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MySQLdb: cant get '... where field in %s' to work for string sequences
On 6/22/06, Justin Ezequiel <[EMAIL PROTECTED]> wrote: > how can I get 'select ... from ... where field in %s' to work for > sequences of strings? > sequences of integers works just fine > > import MySQLdb > > DBCRED = {'host': 'localhost', 'user': 'userjustin', > 'passwd': 'passwdjustin', 'db': 'dbjustin'} > > ARTICLES = ('XXX9', 'ABZ2') > PIDS = (29379, 29380) > > FIXEDARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN ('XXX9', 'ABZ2')""" > TESTARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN %r""" % (ARTICLES,) > SQLARTICLENAME = """SELECT * FROM tblForTransfer2Prodsite > WHERE articleName IN %s""" > > FIXEDPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN (29379, 29380)""" > TESTPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN %r""" % (PIDS,) > SQLPID = """SELECT * FROM tblForTransfer2Prodsite > WHERE pid IN %s""" > > if __name__ == '__main__': > conn = MySQLdb.connect(**DBCRED) > try: > cur = conn.cursor() > print FIXEDARTICLENAME > print TESTARTICLENAME > print cur.execute(FIXEDARTICLENAME), > print cur.execute(TESTARTICLENAME), > # cannot get this to work > print cur.execute(SQLARTICLENAME, (ARTICLES,)) > print > print FIXEDPID > print TESTPID > print cur.execute(FIXEDPID), > print cur.execute(TESTPID), > # but this does > print cur.execute(SQLPID, (PIDS,)) > print > finally: conn.close() > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Can you post your error messages? -- Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Programming Books
On 7/14/06, wesley chun <[EMAIL PROTECTED]> wrote: > (LONG... you've been warned ;-) ) Heh, that was pretty long. I bought the first edition of Core Python and thought that it was well-written, but I didn't quite get it (stay with me, this gets better). It wasn't until after I had taken quite a few courses in C++ that I realized 1) that python was s much nicer to work with and 2) Wesley's book made a lot more sense. It's probably not a good one for someone new to programming, but I find that I pick it up when I need to see an example of how something is done in python. As for an absolute beginner, Alan's tutorial and How To Think Like a Computer Scientist are both pretty good. The latter had my daughter doing a fair bit of programming in a day. So Wesley's Big Book was a huge help in a project I did for work that involved socket programming, pickling, and interfacing with MySQL. Showing how particular things were done in python in clear, concise examples is it's big strength. Thanks for not getting sucked in to using lots of source code :) -- Matt Waiting for the second edition ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (*args, **kwargs)
Dear All, I have learnt to do bits of python, but one of the things I cannot get my head around is the *args, **kwargs syntax. I have tried reading stuff on the web, and I have a copy of the python cookbook (which uses it as a recipe early on) but I still don't understand it. Please could someone explain _very_ slowly? Apologies for the gross stupidity, Matt -- http://acl.icnet.uk/~mw http://adhominem.blogsome.com/ +44 (0)7834 899570 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (*args, **kwargs)
Dear Etienne & Carlos, Thanks so much for that - much clearer! I guess the next question is _how_ do you use it intelligently? I'm interested because I'm trying to put stuff into a db using sqlobject. Obviously one way would be: class MyClass: def __init__(self,**kw) self.property1 = self.kw['property1'] self.property2 = self.kw['property2'] etc Does anyone know of an example of this ? Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Regex
Dear All, I know this has come up loads of times before, but I'm stuck with what should be a simple Regex problem. I'm trying to pull all the definitions from a latex document. these are marked \begin{defn} \end{defn} so I thought I'd write something like this: filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex' infile = open(filename,'r') def_start = "\\begin\{defn\}" def_end = "\end{defn}" def_start_reg = re.compile(def_start) l = 0 while l < 500: line = infile.readline() #print l, line res = re.search(def_start_reg,line) print l, res l = l+1 but it doesn't return any matches (BTW, I know there's a defn tag in that section). I thought it was my regex matching, but I checked it with an online checker, and also with a small bit of text: def_start = "\\begin\{defn\}" def_start_reg = re.compile(def_start) text = """atom that is grounded. These formulae are useful not only for the work on valuation but are also used in later chapters. \begin{defn} A Patient-ground formula is a formula which contains a grounding of $Patient(x)$. The other atoms in the formula may be either ground or non-ground. \end{defn} Having defined our patient ground formulae, we can now use formulae of this form to define our patient values.""" res = re.search(def_start_reg, text) print res and this returns a MatchObject. I'm not sure why there should be any difference between the two - but I'm sure it's very simple. Thanks for any tips, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting a list in an add order
Dear List, I've written a small script to extract the definitions from my thesis, and output them as a .tex file, which works ok but I have a small problem. The input is done by specifying a directory, and using glob to find the ".tex" filenames. However, I want to process them so that they are arranged in the correct order, which means I need to sort the list of files. Of course, because they aren't named in any (obvious) order, I'm a bit stuck. I thought about using a dictionary to map names and order: so {"OAF":1, "Valuation":2...etc}, but I don't don't know how to take it on from here. I was thinking of looking up the filename in the dictionary (using .startswith() to get some basic rough-matching capacity) and then using that to return the order that the files should be handled in. Any comments/ better ideas? Thanks, Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Has anyone tried matplotlib...??
I just used it a couple of weeks ago to produce a histogram of randomly generated numbers. Read the documentation, it's well written and has good examples. Matt On 10/22/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote: > > Folks, > > Has anyone tried matplotlib ..//??? > > If yes, then is it easy to use... > > > > > -- > To HIM you shall return. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sloppy Code ?
Hi guys Very new to python programming but am really enjoying it. Anyway, I was just wondering if this code could be improved on in anway. ... stdin, stdout, stderr = os.popen3('/bin/hostname -f') system_name = stdout.read() stdin.close() stderr.close() stdout.close() ... report.write("System Report for: ") report.write(system_name) ... Is there a better way of doing this ? It works for what I want to do, but I would like to know if there's another way of doing things.... Thanks in advance. Matt E matt.erasmus (at) gmail (dot) com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sloppy Code ?
Hi Michael Yes, that does help, although it doesn't print the FQDN which is what I'm really after. But thanks to you I now know about the socket module (is that the right terminology ?) and using the Python script in Vim I found socket.getfqdn() which prints exactly what I needed... So my code goes from: stdin, stdout, stderr = os.popen3('/bin/hostname -f') system_name = stdout.read() stdin.close() stderr.close() stdout.close() ... to report.write(socket.getfqdn()) On 13/11/06, Michael Lange <[EMAIL PROTECTED]> wrote: > import socket > print socket.gethostname() > > I hope this helps Thanks so much Michael -Matt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lexicographic ordering (or something simpler)
Dear All, I'm trying to write something to calculate rule priorities, based on their provenance (ultimately I'm after a lexicographic ordering) I have a set of terms (the provenances) I'm try to sort. I've done it by associating each possible set of terms with a dictionary, and then using the elements of the set as keys of the dictionary, so that it can look up the values. This is (almost certainly) sub-optimal, but ok for now Where I get stuck is that each rule is compared pairwise to each other; the precedence of the set of rules is then based on that. Since there can be ties between the rules, the result of each pairwise comparison for two rules a & ) is either 1,0 or -1, where 1 == a beats b, -1 == b beats a and 0 == tie. At the moment I get back a list of results from testing one set of rules against the other. I now need to make a decision based on all the results. I've tried coding it as if...elif statements, but that all gets horrible. Given a list of the form [1,0,0,1,-1] I need to make decision (in this, it is undecided, so we drop down to the next criteria). Any ideas/ pointers as to how I implement this? Thanks, Matt -- http://acl.icnet.uk/~mw http://adhominem.blogsome.com/ +44 (0)7834 899570 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent of grep in python
- Forwarded message from Tiago Katcipis - i forgot, this might help you http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files I can't help wondering how to do this in python: perl -wnl -e '/string/ and print;' filename(s) Not that I want to forget the precious few bits of Perl I do know, but I'd rather be totally reliant on python for such tasks. On Sun, Dec 21, 2008 at 11:57 AM, Tiago Katcipis wrote: > i believe that the following should work > > file1 = open(fileO, 'r') > re.findall ('some_text', file1.read()) > > readlines returns a list with lists inside, where every list is a line of > the text. The read function returns the entire file as one string, so it > should work to what you are wanting to do. > > best regards > > Katcipis > > > On Sun, Dec 21, 2008 at 12:02 AM, ppaarrkk wrote: > >> >> The following works : >> >> file1 = open (file0, "r") >> >> re.findall ( 'some_text', file1.readline() ) >> >> >> But this doesn't : >> >> re.findall ( 'some_text', file1.readlines() ) >> >> >> >> How do I use grep for a whole text file, not just a single string ? >> -- >> View this message in context: >> http://www.nabble.com/Equivalent-of-grep-in-python-tp2356p2356.html >> Sent from the Python - tutor mailing list archive at Nabble.com. >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > "it might be a profitable thing to learn Java, but it has no intellectual > value whatsoever" Alexander Stepanov > -- "it might be a profitable thing to learn Java, but it has no intellectual value whatsoever" Alexander Stepanov ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor - End forwarded message - -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] optparse
Hi All. I want to write a script that will emulate grep to some extent. This is just an exercise for me. I want to run the script like this: ./pythongrep directory searchstring Just like grep, I want it to print: filename, instance_of_match As of now, the script can't find anything I tell it to look for. It prints, "None." Thanks for any advice. import optparse import os import re def main(): p = optparse.OptionParser(description="Python grepper", prog="greppar", version="0.1", usage="usage: %prog directory regex") options, arguments = p.parse_args() if len(arguments) == 2: directory = arguments[0] regex = arguments[1] s = re.compile(regex) for filename in os.listdir(directory): result = re.match(s, filename) print result else: p.print_help() if __name__ == '__main__': main() -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Redux: optparse
On Wed, Dec 24, 2008 at 01:12:55AM -, Alan Gauld wrote: > > "Kent Johnson" wrote > > >> for filename in os.listdir(directory): > >> result = re.match(s, filename) > >> print result > > > >You never open and read the files. You are searching for the pattern > >in the filename, not in the contents of the file. > > Also note that match() only searches starting at the start of the > string. > > Thus match will find foo at > > foobar > > but not in > > sofoo > > You usually need to use search() to find the pattern anywhere > within the string. > > Also look at the thread earlier this week on using listdir() and > the fileinput module. Hello again and thanks for the encouragement. I have been working on this problem again today and switched to the fileinput method. What I can't figure out now is how to pass a compiled regex to an optparse option. I'm confused ias to "option" versus "arg" when using the optparse module. In fact there seems to be no way to define what the arg should be; only options. Is the arg always implied? I have read several pages on optparse and am none the wiser. How do I fix the rx = re.compile('-x') line below so that the string I pass on the command line gets passed into the re.compile? #!/usr/bin/python import fileinput, sys, string, optparse, re #def main(): optparser = optparse.OptionParser() optparser.add_option("-x", "--regx", help="regular expression") # take the first argument out of sys.argv and assign it to searchterm #searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] (options, args) = optparser.parse_args() rx = re.compile('-x') for line in fileinput.input(): num_matches = string.count(line, rx) if num_matches: print "found '%s' %d times in %s on line %d." % (rx, num_matches, fileinput.filename(), fileinput.filelineno()) #if __name__ == '__main__': #main() > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Redux: optparse
> Do you want to use optparse, or get the command line arguments yourself? > It seems the pattern string will be the first arg, will it? Again I am confused. I assumed that optparse was the best way to pass in arguments (such as filenames) from the command line. Like so: ./script.py -x regex *.html > > rx = re.compile('-x') > > Then, if the note above is right, you have: > > pat_string = sys.argv[1] > rx = re.compile(pat_string) # pattern object > > Is that what you wish to do? Probablement. :) The below code does what I want: --- #!/usr/bin/python import fileinput, sys, string # Take the first argument out of sys.argv and assign it to searchterm. searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = line.count(searchterm) if num_matches: # A nonzero count means there was a match. print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) --- I wanted to use optparse instead of sys.argv. Perhaps I should study fileinput instead. I don't understand that either. > > for line in fileinput.input(): > > num_matches = string.count(line, rx) > Above you are counting the number of *regex pattern* may be inside a > string. Not the number of (sub)strings matching the pattern, which is > probably what you intend.[ Also, you are using a deprecated function > "count" of the string module. Use line.count(substring) instead. Anyway, > this is probably not what you want.] > To count the number of pattern matches, you must use the > "matching" (lol) regex method, namely findall: > > result_list = rx.findall(line) > > > if num_matches: > > print "found '%s' %d times in %s on line %d." % (rx, num_matches, > > fileinput.filename(), fileinput.filelineno()) > > Do you want to print only the last match? If not, you need to record > matches found by the search loop into a list. > > > #if __name__ == '__main__': > > #main() > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling setters of superclasses
On 12/18/2010 2:06 AM, Peter Otten wrote: I don't think /how/ you are trying it is stupid though I'm not so sure about /what/ . Thank you all for very helpful suggestions. It took me a while to chew on this before I could respond. I learned a lot about descriptors and their interactions with properties that I hadn't fully understood before. Peter and Alan's advice to create a check method that is overridden in subclasses makes sense in order to avoid the naming conflicts. And I also like Hugo's idea of applying separate descriptor classes to handle the constraints introduced. That seems to be a flexible way of doing things. As far as the /what/, my example given was obviously contrived. I'm really trying to create classes for 2D envelopes that describe the bounding extent of spatial data. I have both Envelope and RasterEnvelope classes - the former being just a bounding box around any spatial data, the latter additionally specifying a raster cell size and being able to discern rows, columns, etc. I had been using the setter to do bounds checking on the Envelope class (e.g. make sure x_min isn't bigger than x_max, etc. and rolling back changes if so). For the RasterEnvelope class, I first wanted to call the Envelope bounds checking and then to adjust rows/columns if a bigger extent was requested. But you've successfully scared me away from using properties (in a hierarchical way at least) and I've been able to get what I need by just defining __setattr__ in both classes. Whether I did that correctly is a story for another thread ... matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor