Re: [Tutor] PDF and Python
Quoting Kent Johnson <[EMAIL PROTECTED]>: > The reportlab toolkit is frequently recommended, though I haven't tried it > myself. > http://www.reportlab.org/ > > Kent Whoa ! Just has a play with that ReportLab toolkit and it looks well funky. It makes creating simple PDF's a doddle. Thanks for the link Kent :) Nick . ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 78, Issue 97
From: tutor-bounces+nblack3=student.gsu@python.org [tutor-bounces+nblack3=student.gsu@python.org] on behalf of tutor-requ...@python.org [tutor-requ...@python.org] Sent: Saturday, August 21, 2010 1:25 PM To: tutor@python.org Subject: Tutor Digest, Vol 78, Issue 97 Send Tutor mailing list submissions to tutor@python.org 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 tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: prime test problem (Evert Rol) 2. Re: prime test problem (Steven D'Aprano) 3. Re: prime test problem (Roelof Wobben) 4. Re: Windows Power Shell (Bill Allen) 5. Re: prime test problem (Evert Rol) -- Message: 1 Date: Sat, 21 Aug 2010 17:11:53 +0200 From: Evert Rol To: Roelof Wobben Cc: tutor@python.org Subject: Re: [Tutor] prime test problem Message-ID: <6732a98e-e155-41b4-9330-ff78db90f...@gmail.com> Content-Type: text/plain; charset=us-ascii > Hello, > > I know. > I have read them all I believe but I can't see how I can convert the algebra > to a working programm. And if you just search Google for "Python prime number algorithm"? Perhaps it's cheating, so you'll have to try and fully understand the code first before you run it (be sure to read comments if there are any, eg the activatestate recipes; can have tons of useful extra info & links). Generally, try to start with a program yourself, and then see where you get stuck. You could then post your stuck algorithm to the list and ask for advice; your current question is a bit too general, and thus harder to answer. Evert > > Roelof > > > Date: Sat, 21 Aug 2010 19:15:03 +0530 > Subject: Re: [Tutor] prime test problem > From: nitin@gmail.com > To: rwob...@hotmail.com > CC: tutor@python.org > > For this problem u will get lots of solutions on the net. > e.g wilson's theorem , sieve of eranthoses etc. > > --nitin > > On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: > Hello, > > I have to make a programm which can test if a number is a prime. > I know a prime is a number which can only be diveded by 1 and itself. > > One way is was thinking about is to make a loop which try if % has output 0. > But that don't work. > > Can someone give me a hint what's the best approach is. > > Roelof > -- Message: 2 Date: Sun, 22 Aug 2010 02:49:26 +1000 From: Steven D'Aprano To: tutor@python.org Subject: Re: [Tutor] prime test problem Message-ID: <201008220249.27986.st...@pearwood.info> Content-Type: text/plain; charset="utf-8" On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > Hello, > > I know. > I have read them all I believe You've read all 64 million pages that Google finds? Wow, you must be a fast reader! Well done! > but I can't see how I can convert the > algebra to a working programm. Have you *tried*? Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7. Then generalise that third program. Off you go. Come back when you have some code. Even if it isn't working code, at least try something. -- Steven D'Aprano My reply: I may be formatting this wrong. This is my first time posting to this list as I'm a relatively new subscriber. I think I read the directions right in that it said don't top post, post under what you're responding to. I'm sorry to anyone I offend if I got this wrong. I was interested in this specific topic as I've been working some problems on project euler. I've been stuck on a prime one more or less because I don't understand all the scripts I've been viewing (trying to learn how to approach it). I get stuck in various areas specific to each one. While that is general here is my real question. "Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7." The very first problem for projecteuler.net makes you write a program that finds all factors of 3 and 5 for n < 1000. Were they trying to lead me down the path you're alluding to? I'm not seeing the connection between that particular problem and finding primes. I would appreciate more insight. Thanks everyone! -- Message: 3 Date: Sat, 21 Aug 2010 17:14:05 + From: Roelof
Re: [Tutor] Tutor Digest, Vol 78, Issue 99 -- Prime numbers
"Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7. Then generalise that third program. Steven D'Aprano" *** Sorry for posting like that to the list. I thought I was doing it correctly, but really messed that one up. I think I'm doing everything correctly now, but please tell me what I'm not-- if such is the case. I was interested in this specific topic as I've been working some problems on project euler. I've been trying to generate prime numbers as a first step to go about solving a problem. I don't have a particular question about solving the problem, but want to ask about a relationship. The very first problem for projecteuler.net makes you write a program that finds all factors of 3 and 5 for n < 1000. Were they trying to lead me down the path you're alluding to? I'm not seeing the connection between that particular problem and finding primes. I would appreciate more insight. Thanks everyone! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 78, Issue 100 -- Prime numbers using square root of n
"We're still doing too much work. Why go all the way up to n? We know that (say) 93 can't possibly divide into 99, or 57 into 59. The largest number we need to check is the square root of n. The reason is a little subtle, so think about it, don't just take my word. Hint: write down the factors of, say, 60: Can you see the pattern? 2*30, 3*10, 5*6, 6*5, 10*3, 30*2 -- Steven D'Aprano" Thanks so much Steven. I get it all except I don't think I see the pattern. I see that we're already covering those higher factors since they're divisble by 2, 3, 5, etc. I'm just not connecting the final dot with the square root of n. It's almost there in my mind! I just need a little more of a push! Also I can write a program that tests whether the number is a factor of 2, 3, 5, 7, but I think you're trying to point to me that this is cumbersome and not necessary. I just don't see the rest of the light quite yet. I have been looking at code on the internet too, but there are lots of different ways to skin a cat and it seems people are taking advantage of that. I keep hitting road blocks in code. I want to understand! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing a prime number program using upper bound of square root of n
"1 * 120 = 120 2 * 60 = 120 3 * 40 = 120 4 * 30 = 120 5 * 24 = 120 6 * 20 = 120 8 * 15 = 120 10 * 12 = 120 10.9545 * 10.9545 = 120 12 * 10 = 120 <=== already seen this one! > Also I can write a program that > tests whether the number is a factor of 2, 3, 5, 7, but I think > you're trying to point to me that this is cumbersome and not > necessary. Sort of. I'm not suggest that you create lists of multiples of 2, 3, 5, 7 etc, and then cross off non-primes by checking to see if they are in one of those lists. That truly would be cumbersome and slow. But the two problems are similar. For simplicity, let's ignore 2 as a prime, and only think about odd numbers: (1) For each odd number N between 3 and (say) 1000, check if it is a multiple of 3, 5, 7, 9, ... and IF SO, put it in the list "nonprimes". versus: (2) For each odd number N between 3 and (say) 1000, check if it is a multiple of 3, 5, 7, 9, ... and IF NOT, put it in the list "primes". See, they are very nearly the same problem. The tricky bits are: * dealing with 2 is a special case; * you don't want to exclude (say) 3 from being a prime because it is divisible by 3; and * you can stop testing at square-root of N. Steven D'Aprano" Is there a way I can set my email program to insert the ">" symbol to mark what I'm replying to without manually doing it? I get the picture now, that was a great example. I wrote some code last night before going to bed that did what you were saying checking if it was divisible by 2, 3, 5, or 7. I'm going to paste that. And so in my range function in this code could the upper bound be n*.5 instead of n+1 ? is that how I would eliminate the checking of the repeated factors ? I hope I'm not beating a dead horse guys. thankis primes = [2, 3, 5, 7] def p(n): for i in range(3, n+1, 2): if i % 3 == 0 or i % 5 == 0 or i % 7 == 0: pass else: primes.append(i) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] project euler prime factorization problem
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? #don't forget 2,3,5,7. this function doesn't deliver those as output. def is_prime(b): #checks a number greater than 7 to see if it is prime and returns if is. if b % 2 != 0 and b % 3 != 0 and b % 5 != 0 and b % 7 != 0: print b, def factor(num): x = num b = 1 c = num while b <= c: #starts at 1 and searches all the numbers up to the number you put in if x % b == 0: is_prime(b) b += 1 else: b += 1 print "Don't forget to consider primes 2, 3, 5, and 7\n" #600851475143 #shows what numbers in given range are prime ''' def is_prime(b): return [2,3,5,7] + [x for x in xrange(3, 1, 2) if x % 2 != 0 and x % 3 != 0 and x % 5 != 0 and x % 7 != 0] ''' I'm looking for some help with this problem. I realize my code is inefficient for such a big number, and also I'm not quite sure it works perfectly in and of itself. My current reasoning was something of this sort: Find all the factors of a number, then reduce them to just the prime factors and you can then multiply them together to get that number thus having the prime factors. I need a lot of help haha. Thanks in advance everyone. If anyone has a good resource to point me to other than the open book project and dive into python it would be much appreciated. Would it be useful for me to buy a book, and if so what are some easily accessible ones? I feel dive into python is just too advanced for me. I understand a lot of the teachings, but the examples seem unwieldy and esoteric. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] project euler prime factorization problem
"Did you test the program? That is one way to tell whether it works perfectly. What you showed above will do one visible thing - it will print "Don't forget to consider primes 2, 3, 5, and 7\n". The rest is a somewhat confusing collection of function definitions and comments. You never call the functions so nothing else will happen. As Alan said - research prime factors to see how others approach it. My current reasoning was something of this sort: Find all the factors of a number, then reduce them to just the prime factors Very inefficient. IMHO the proper way is to generate a list of all the prime numbers up to the square root of 600851475143, then test each (starting with the largest and working down) till you discover a factor. That then is the answer. There are many published algorithms for generating primes. and you can then multiply them together to get that number thus having the prime factors. I need a lot of help haha. Thanks in advance everyone. If anyone has a good resource to point me to other than the open book project and dive into python it would be much appreciated. Would it be useful for me to buy a book, and if so what are some easily accessible ones? I feel dive into python is just too advanced for me. I understand a lot of the teachings, but the examples seem unwieldy and esoteric. -- Bob Gailer " Yeah, thanks everyone for the comments. I will follow your advice Bob. I didn't call the functions in the program because I was calling them myself in the interpreter after running it. I don't know if that is the way everyone else programs, but I just write it in idle and save it and run it over and over making sure it is doing what I want ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Scribbler Robot
http://www.georgiarobotics.com/roboteducation/robot-kit.html you can check the robot out at this link. is this a good buy you guys think, or is there a better python compatible robot out there? I just want something to keep me interested in programming and that gives me ideas of programs to write. The benefit of the scribbler is also that free book online learning with robotics... It has all kinds of sample code for programs for the scribbler. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is pydoc the right API docs?
I'm not sure I'm using pydoc correctly. I only seem to get abbreviated help rather than full documentation. It happens often enough that I think I'm doing something wrong. For example, I want to upgrade my scripts to use .format() from using %. $ pydoc format Help on built-in function format in module __builtin__: format(...) format(value[, format_spec]) -> string Returns value.__format__(format_spec) format_spec defaults to "" Well, that just tells me that there is an entity called format_spec. I want to know what format_spec actually IS so I can use it. I try: $ pydoc -k format_spec $ Nothing. I found the answer using google, but that won't work if I'm offline. Am I using pydoc correctly? Or is there a more complete language spec? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the art of testing
As well as the other replies, consider that you are doing "unit" testing: http://en.wikipedia.org/wiki/Unit_test One method is black-box testing, which is where the thing (class, function, module) you are testing is treated as a black box, something that takes input and returns output, and how it does it are irrelevant from the tester's perspective. You remove the implementation of the thing from the test of the thing, which allows you to focus on the tests. In fact, you can write the tests before you code up the black box, which is a valid development technique that has many proponents. You throw all sorts of data at the black box, particularly invalid, boundary and corner-case data, and test that the black box returns consistent, valid output in all cases, and that it never crashes or triggers an exception (unless part of the design). Once you have run your tests and have produced a set of test failures, you have some leads on what within the black box is broken, and you take off your tester's hat, put on your developer hat, and go fix them. Repeat. A pre-built test suite makes this easier and gives consistency. You know that your input data is the same as it was before your changes and you can test for consistency of output over your development cycle so that you know you haven't inadvertently introduced new bugs. This process is regression testing. Clearly, ensuring your test data covers all possible cases is important. This is one reason for designing the test suite before building the black box. You won't have inadvertently tainted your mind-set with preconceived notions on what the data contains, since you haven't examined it yet. (You've only examined the specs to find out what it *should* contain; your black box implementation will handle everything else gracefully, returning output when it should and triggering an exception when it should.) This frees you up to create all sorts of invalid, i.e. non-specification, and boundary test data, without preconceived ideas. Once you are passing your test data, throw lots of samples of real-life data at it. If your test data was comprehensive, real-life data should be a piece of cake. Obviously I'm a fan of unit-testing. Sure, the first time they're a bit of work to build up, but you'll find you can re-use them over and over with a small amount of editing. Many conditions are the same for any program, such as (off the top of my head) file-not-found, file-has-one-record-only, file-has-a-trillion-records, string-where-int-expected, int-out-of- expected-range, and so on. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
Quoting "Gopinath V, ASDC Chennai" <[EMAIL PROTECTED]>: > Hi > Can any1 please tell me how do i open an editor in python running in > linux os > Hi Gopinath, try os.system, ie import os os.system('/usr/bin/xterm &') Regards Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Python-ideas] "value" ~ "data" ~ "object"
spir ☣ wrote: > What useful distinctions are or may be done, for instance in documentation? Python mainly considers: object identity (x is y, determined by id()) object value (x == y, determined by the implementations of relevant __eq__ methods) For many objects, their value degenerates to being the same as their identity (i.e. they compare equal only with themselves), but others have for more useful comparisons defined (e.g. containers, numbers). In addition to objects with their identities and values, there are references to objects. These 'references' are the only things in Python which aren't first class objects, since they reflect lookup entries in some namespace or container, such as the mapping from names to pointers in a class or module __dict__ or a function's locals, or the items stored in a list or set. Cheers, Nick. -- Nick Coghlan | ncogh...@gmail.com | Brisbane, Australia --- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] newbie to gui programming
Please excuse if I'm jumping on the topic. Haven't done any GUI work so this interests me too. wxPython always seemed a great choice as it works on all platforms, and uses GTK+ for linux. Well, what mainly bugs me about wxPython is that most of it's API names come from the wx C library, you almost can feel the C code underneath. I would really love a more pythonic wrapper around it. Really good news is that on this very list on another thread, someone suggested Dabo http://dabodev.com/ It's a python library on top of wxPython and it's database-logic-GUI separation looks a lot like the MVP of django, which I'm familiar with. Of course, a bit not that easy to install if you're just starting out and there are no books for it. It's also database oriented, but I consider this a plus. I'd like to hear your views on whether you think it might be a good choice for a new python programmer, exactly for the above reasons. I think it might be worth the hurdles and pay off in the end. Nick On 07/06/2010 09:48 PM, Alan Gauld wrote: There are many toolkits but these have as many similarities as differences. But none of them will be easy to learn if you have not done GUI work before because GUI programming is a whole new style and that's what takes the time. Once you learn one framework picking up another is not that hard - just a lot of new API names to learn! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] newbie to gui programming
Well, choice is a great thing! Except when you're new and all that choice seems overwhelming :) When I started out python a year ago, I knew just enough C to know that I didn't want C/C++ to be my first language that I learned. That's why I found the wxPython style a nuisance, because I was at the same time trying to learn the python way of doing things. I do see the merits you say in how wxPython does things, it just didn't work out then. In the end, I never did any GUI work because of the overwhelming choice and instead did a little pygame stuff and then got into django, mostlly because my local community did. So, db-centric seems good to me right now and will definately check dabo out, although to be honest, a webkit application on top of django sounds as good. Anyways, I'm drifting all this while away from the purpose of this list. Thank you so much for the answers, you're such a helpful bunch. Nick On 07/07/2010 10:16 AM, Alan Gauld wrote: "Nick Raptis" wrote Really good news is that on this very list on another thread, someone suggested Dabo http://dabodev.com/ It's a python library on top of wxPython and it's database-logic-GUI But its not a complete wrapper for wxPython so you still need to revert to wxPython at some stages. Also its being database centric is great if thats what you are doing, not so great for games programming etc. But the tight coupling of wxPython to its C++ roots can be seen as a bonus because it means you can quickly use its Ruby and Perl incarnations too - and if you need to the base C++. This is one of the reasons I mainly use Tkinter - because I already knew the underlying Tk and I can use those same skills in Lisp and Ruby and Perl UI code. You pays your money and makes your choice! :-) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] differences between mmap and StringIO
Actually, for simple file operations I'd neither. Standard file usage is described here, if you haven't checked it out, which I'm sure you have http://docs.python.org/library/stdtypes.html#file-objects StringIO is useful as a buffer. That is, you make a file-like object in memory with StringIO, manipulate it as a file, and can then copy it to a real file with standard file operations. Really really useful for very intensive file operations. Pdf creation comes in mind. mmap... Well I didn't even know it existed until you mentioned it! Seems to be an advanced method of reading a file in memory and manipulating it from there with choice of whether it actually affects the physical file or not. It's help page says it is also used for communicating with subprocesses.. wow! You definately won't need that :) Anyway, files, StringIOs and mmaps are file-like objects, which means they have the same methods and functionality, so you know how to use one, you know them all from this aspect. My recommendation would be, either manipulate a file directly which is fine for most cases. Or if you really want to: open your file for reading, make a StringIO instance, copy your file to it, close the file, do whatever you want in memory, open your file again for writing, copy the StringIO to it, close both. I'd consider that overkill for most projects Is there something in particular you want to do? Nick On 07/08/2010 01:52 AM, Eduardo Vieira wrote: Hello, I'm getting confused about the usage of those 2 modules. Which should I use one to get/manipulate data from a text file? Regards, Eduardo www.express-sign-supply.com ___ 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
Re: [Tutor] newbie to gui programming
Thanks a lot for the mails all of you. Someone commented that wxpython occassionally shows it C/C++ roots. Will that haunt me cos' I have zero knowledge of C/C++. That would be me, sorry about that, didn't mean to confuse you further. Well, think it this way, if you have zero knowledge of C, you won't even notice. What about py-gtk? Is it more pythonic to learn and hence easy? Not really, every library shows it's roots every now and then. Or can I start with tkinter (and maybe remain with it), if it is easy to learn? (I liked fetchmailconf and I think it was done in tkinter). It comes bundled with python, is easy for easy tasks but 'might' be a burden as you scale up your projects. Why not? I get discouraged a bit fast, so I want the first toolset to be as easy as possible. With warm regards, -Payal Well I can relate to that. Was not so long ago when all choice seemed overwhelming and I thought that I better learn the best language/library from the start or I'll be wasting time. Truth is, it doesn't really matter this much. Start with one, anyone and for whatever reason (eg, you found a book for it) and go for it for a week. If it doesn't work for you, you'll know by then, and not a lot of energy got wasted. GUI programming is hard cause there a lot of new concepts to learn. Learning those concepts so you can apply them to any library should be your goal. Anyway, my personal story is that after trying wxPython with a book a bit I decided that GUI programming was not my thing at all, and started writing games with pygame. Many similar concepts, twice the fun. Now I'm doing web work. Give it time, trust your gut and don't panic, you'll end up right where you want :) Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Django Read
There actually aren't that many books on django around yet which is a pity. You should definitely read "The django book": http://www.djangobook.com/en/2.0/ either on the online version on that link, or it's printed counterpart (yes, it's really the same book): http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ The printed one is a bit more updated (1.1) and pays off it's money because of it's great reference section :) Nick On 07/08/2010 03:48 PM, Dipo Elegbede wrote: Hi all, I have done a little basic on python and have to start working on a major django platform. I'm starting new and would like recommendations on books I can read. Kindly help me out. I want to get my hands dirty as fast as I can so that I can be part of the project. Thanks and Best regards, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having a return when subprocess.Popen finishes
subprocess.Popen is a class, and as such it returns an object which can do a lot of stuff besides just reading the output. What you want to do here is using it's communicate() method as such: output, errors = ping.communicate() Also, there is a quicker way, I think from version 2.7 forward: use the shortcut output = subprocess.check_output("your command here") Always check latest documentation for your python version too http://docs.python.org/library/subprocess.html Nick On 07/08/2010 04:04 PM, Paul VanGundy wrote: Hi All, I'm trying to get data from subprocess.Popen. To be specific, I am trying to read a ping echo and take the output and assign it to a variable like below: ping = subprocess.Popen("ping -c 5 %s" % (server), stdout=subprocess.PIPE, shell=True) However, when I run the command the output that gets assigned to my ping variable is something along the lines of '' and am not returned to>>> prompt. I know that is the proper output but I need to be able to capture the ping replies and assign those to a variable. I tried adding a \r and \n at the end of my cmd. Any help would be greatly appreciated. I'm open to improvements, different ways of doing it and corrections. :) If more info is needed let me know. Thanks. /paul ___ 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
Re: [Tutor] Function returns 'None'
On 07/11/2010 04:59 PM, Dominik Danter wrote: Hello As en exercise I wrote the following function: def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x recursfac(x-1, carryover) else: return carryover print recursfac(3) Very much to my surprise I get the following output: x: 3 carryover: 1 x: 2 carryover: 3 x: 1 carryover: 6 None Where did I go wrong? Your problem is that you expect the "return" to exit the recursion altogether. Instead, carryover is passed to the previous level of the recursion, which has nothing more to execute and returns None. So the first step to fix this would be to make sure that your function returns carryover no matter what: def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x recursfac(x-1, carryover) return carryover else: return carryover Or simply (to remove the code duplication): def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x recursfac(x-1, carryover) return carryover Now there's still one more problem. The output is this: x: 3 carryover: 1 x: 2 carryover: 3 x: 1 carryover: 6 3 Why is it returning 3 istead of 6? Well, the function didn't catch the returned carryover value on the way up, so it's just returns what it knows: the value of carryover that it self has computed. Instead, you have to do this: def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x carryover = recursfac(x-1, carryover) return carryover And this returns x: 3 carryover: 1 x: 2 carryover: 3 x: 1 carryover: 6 6 Done! What you should learn from this is that, when doing recursion, figuring out what your function should do on the way up is as crucial as what you want it to do on the way down. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function returns 'None'
On 07/11/2010 06:28 PM, Nick Raptis wrote: def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x carryover = recursfac(x-1, carryover) return carryover And this returns x: 3 carryover: 1 x: 2 carryover: 3 x: 1 carryover: 6 6 Done! Also, I realized that my final code may be tough to decipher now.. A nicer way to write it would be (the functionality is still exactly the same): def recursfac(x,carryover=1): print 'x:',x,'carryover:', carryover if x > 1: carryover *= x result = recursfac(x-1, carryover) else: # done with recursion, start our way up result = carryover return result ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function returns 'None'
On 07/11/2010 06:50 PM, Luke Paireepinart wrote: I think the new version is harder to understand. Sent from my iPhone On Jul 11, 2010, at 10:43 AM, Nick Raptis wrote: Aww! A critic! You humble me (really, I'm not being sarcastic here, I welcome it gladly) I won't argue about it, though. If you prefer it, the last version is still there :) My reasoning is that, with the new variable name ('result') in place, now it is evident (to me at least) that 'passover' is passed on the way down, while 'result' is passed on the way up. Harder it not, it seems more """"""clean"""""" Also, another preference of mine, would you be kind enough to answer to the list and cc the original poster if you can? Doing it the other way around breaks my (quite stupid I admit) filters, and perhaps others' too. Thanks for the feedback. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Documentation Clarification
compile(source, filename, mode[, flags[, dont_inherit]]) I see within this built in function, the first argument can be what they define as source, the second argument as the filename and the third as the mode. But what confuses me is sometimes I see a bracket, above as [, flags[, dont_inherit]]. Is this an optional argument like flags=dont_inherit? Brackets do indeed mean optional arguments. So you can do compile(source, filename, mode, flags=whatever, dont_inherit=True) or something. The nested brackets most likely show that (in your example), dont_inherit is optional, but can be used only if you (optionally) also provide the flags argument. Of course, don't take my word for it and read the rest of the description in the documentation. Also read here: <http://docs.python.org/reference/introduction.html?highlight=brackets>http://docs.python.org/reference/introduction.html?highlight=brackets#notation Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching a text file's contents and comparing them toalist
On 07/14/2010 11:57 PM, Eric Hamiter wrote: Last question (for today, at least): Right now, the output is less than aesthetically pleasing: (['Located on aisle 1: ', 'bread', 'magazines'], ['Located on aisle 2: ', 'juice', 'ice cream'], ['Located on aisle 3: ', 'asparagus'], ['Not found in the database: ', 'butter', 'soap']) How can I format it so it looks more like this: Located on aisle 1: bread magazines Located on aisle 2 [etc...] I tried putting "\n" into it but it just prints the literal string. I'm sure it has to do with the list format of holding multiple items, but so far haven't found a way to break them apart. Readup on str.join() http://docs.python.org/library/stdtypes.html#str.join (link is not that helpful I admit, google some uses too) For example, print "\n".join(first_run) will get you started. I think the end code you're looking for is something like output = ["\n".join(run) for run in sorted_list] print "\n".join(output) but I'm not sure if you've got the hang of list comprehensions by now. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nested list help
On 07/27/2010 04:48 PM, Evert Rol wrote: On the other hand, if you want to combine lists based on their first element, consider using dictionaries and extend lists which have the same key. Depending on how you create the lists (eg, when reading columns from a file), you can actually do this during creationi. I'm very much with Everet on this one. Your data would be better contained in a dictionary as such: x = {'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13], 'NM200': [15, 16, 17]} Choosing your data structure is, most of the time, as important as the rest of your code. The rest of the time, the format of your input is not something you can control so: If your data is already on a nested list, as it's on your example, you can convert them quite easily to a dictionary. You then can manipulate them with ease, and if you do want them back on nested list format, convert them back. Here's a very quick script I wrote on how to do it. Please read it through and hit me with questions on what you don't understand. - input = [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]] # Convert and combine the input into a dictionary output_dict = {} for entry in input: key = entry[0] values = entry[1:] if key in output_dict: output_dict[key].extend(values) else: output_dict[key] = values print output_dict # Convert the dictionary back into a nested list output = [] for key in output_dict: entry = output_dict[key] entry.insert(0, key) output.append(entry) print output Of course, my script is very basic and it doesn't tend to a lot of things you'd might want, like eliminating double values or sorting, but it should start you on your path. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help with msvcrt.getch()
On 07/27/2010 05:22 PM, Richard D. Moores wrote: Python 3.1 on Vista. Please see <http://tutoree7.pastebin.com/f3TaxDBc>. I'm trying to recall what I used to know, thus this simple script. But 'y' or 'q' do nothing. What's wrong? Thanks, Dick Moores Hi Dick! I'm not on Windows here so this might be a wild guess. From the documentation I gather that msvcrt can work either on binary or text mode. Perhaps you operate in the wrong one and need to switch with msvcrt.setmode(/) Anyway, insert some print lines to see what exactly is it that /getch() gets and debug from there Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calculating and returning possible combinations of elements from a given set
On 07/28/2010 01:20 AM, ZUXOXUS wrote: Hi all pythoners I've got a probably easy to answer question. Say I've got a collections of strings, e.g.: 'man', 'bat', 'super', 'ultra'. They are in a list, or in a sequence or whatever, say a bag of words And now I want to know how many couples I can do with them, and I want the program to show me the actual couples: 'manman', 'manbat', 'mansuper', 'manultra', 'batbat', 'batman', 'batsuper', etc. But hey, why building up new words from just two strings? I also want to know the possible combinations of three words, four words, and perhaps, why not, five words. So, is it easy to do? Sorry, I'm new in programing, and am probably far from being a math-master I'm clueless, I think probably the code have some FOR I IN SEQUENCE... but then what? I don't know how to say: take every element and paste it to another one from the bag, and with another one, and with another one,... If it's too complex, I dont need the whole code recipe, just need some clues, or perhaps a useful link Thank you very much in advance! Take a look in the itertools module http://docs.python.org/library/itertools.html Check the section "*Combinatoric generators:" (website doesn't have an anchor link for that, search around a bit) Nick * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with simple script
On 07/28/2010 02:51 PM, Richard D. Moores wrote: I have a practical need for a script that will give me a random int in the closed interval [n, m]. Please see <http://tutoree7.pastebin.com/xeCjE7bV>. This works fine when I enter both n and m as, for example, "23, 56", or even "56, 23". But often the closed interval is [1, m], so I'd like to not have to enter the 1 in those cases, and just enter, say, "37" to mean the interval [1, 37]. Highlighted lines 9-11 are my attempt to do this, but it fails. This seems like it should be so simple to do, but it isn't not for me. Advice, please. Thanks, Dick Moores Split the input before the if. Fork based on the length of the resulting list. :) Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String replace question
On 07/28/2010 03:41 PM, Rod wrote: Hello, I need to replace a period (.) in a domain name with a slash period (\.). I'm attempting to use the string replace method to do this. Example: uri = domain.com uri.replace('.', '\.') This returns 'domain\\.com' Of course it does! Try to print the value. Now the extra backslash is gone. Confused yet? Well, the backslash is an escape character in Python and other languages too. It's used for special characters like newlines ( \n ). But then how can you enter just a backslash by itself? Easy, escape it with a backslash. So \ becomes '\\' The representation under your uri.replace() line reflects that (escaped) syntax. When you're printing it though, you see the string as you meant it to. So, nothing is wrong with your lines of code , there's only one backslash there, it just get's represented as two. In fact, you should have escaped \. your self writing the line as such: uri.replace('.', '\\.') but since \. is not a special character, python is smart enough to not mind Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input problem
On 08/22/2010 09:35 PM, Roelof Wobben wrote: Hello, I made this programm : def count_letters(n,a): count = 0 for char in n: if char == a: count += 1 return count fruit="" letter="" fruit= input("Enter a sort of fruit: ") teller = input("Enter the character which must be counted: ") x=count_letters (fruit,letter) print "De letter", letter , "komt", x , "maal voor in het woord", fruit The problem is that I can't have the opportuntity for input anything. I use python 2.7 on a Win7 machine with as editor SPE. Roelof You are using Python 2.x, so you should use raw_input() instead of input(). Note that in Python 3.x, raw_input() has been renamed to just input(), with the old 2.x input() gone. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input problem
On 08/22/2010 09:35 PM, Roelof Wobben wrote: Hello, I made this programm : def count_letters(n,a): count = 0 for char in n: if char == a: count += 1 return count fruit="" letter="" fruit= input("Enter a sort of fruit: ") teller = input("Enter the character which must be counted: ") x=count_letters (fruit,letter) print "De letter", letter , "komt", x , "maal voor in het woord", fruit The problem is that I can't have the opportuntity for input anything. I use python 2.7 on a Win7 machine with as editor SPE. Roelof Also, you have a typo in your code (teller instead of letter) so fix that too :) A couple more comments: - You don't have to initialize fruit and letter. Doesn't make sense in this context. - Although I can see you made the count_letters() function as an exercise, there is a build in method of string that accomplishes the same effect. Try x=fruit.count(letter) - Give a bit of thought about what would happen if someone enters a whole string instead of a character for letter. How should your program accommodate that? Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input problem
Please try and reply to the list instead of just me. raw_input did not the trick. fruit.count is the next exercise. Oke, I deleted the initialazion and change teller into letter. Roelof Should be alright now.. Hmmm Can you paste your exact code AND the error you're getting? As I understand you never get the prompts, right? Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print the installed web browser
On 09/01/2010 11:17 AM, Alan Gauld wrote: "Ranjith Kumar" wrote I`m using ubuntu how to find and print the installed web browsers using python scripting. How would you do it without Python scripting? Is it even possible? And on a multiuser system like Linux would you print out all the browsers installed for the current user or for all users? Alan, let me make a wild guess here. Ubuntu does have little "Preferred applications" config tool. I don't know how or where it stores this data, but my guess is it's the same place xdg (as in xdg-open) gets it's configuration from. This article might help http://www.crystalorb.net/mikem/xdg-settings.html Quote from above article (near the end): "...especially as there is (currently) no single, portable, authoritative way for applications to query the values of these settings..." Ranjith, get ready for some configuration file parsing. But if you just want to open a url with the default browser, you can just execute "xdg-open your-url" as a subprocess. Hope I shifted you to the right direction. Nick PS-trivia: I got to guess these just because I've read the source from "import antigravity" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to print the installed web browser
On 09/01/2010 11:46 AM, Nick Raptis wrote: Alan, let me make a wild guess here. Ubuntu does have little "Preferred applications" config tool. I don't know how or where it stores this data, but my guess is it's the same place xdg (as in xdg-open) gets it's configuration from. This article might help http://www.crystalorb.net/mikem/xdg-settings.html Quote from above article (near the end): "...especially as there is (currently) no single, portable, authoritative way for applications to query the values of these settings..." Ranjith, get ready for some configuration file parsing. But if you just want to open a url with the default browser, you can just execute "xdg-open your-url" as a subprocess. Hope I shifted you to the right direction. Nick PS-trivia: I got to guess these just because I've read the source from "import antigravity" Ooops! Sorry if I caused any confusion, I thought the goal was to print the default browser, not all of the installed ones. Silly me. Still, the "Preferred applications" tool seems to know that info (so to give you a choice) so it might be something to dig into. Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] returning the entire line when regex matches
How do I make this code print lines NOT containing the string 'Domains'? import re for line in log: if re.search (r'Domains:', line): print line This does not work... if re.search != (r'Domains:', line): ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] returning the entire line when regex matches
So far the script works fine, it avoids printing the lines i want and I can add new domain names as needed. It looks like this: #!/usr/bin/python import re outFile = open('outFile.dat', 'w') log = file("log.dat", 'r').read().split('Source') # Set the line delimiter for line in log: if not re.search(r'notneeded.com|notneeded1.com',line): outFile.write(line) I tried the in method but it missed any other strings I put in, like the pipe has no effect. More complex strings will likely be needed so perhaps re might be better..? the next task would be to parse all files in all subdirectories, regardless of the name of the file as the file names are the same but the directory names change I have been playing with os.walk but im not sure if it is the best way. for root, dirs, files in os.walk I guess merging all of the files into one big one before the parse would work but I would need help with that too. the tutelage is much appreciated -nick On Sun, May 3, 2009 at 6:21 PM, Alan Gauld wrote: > > "Alan Gauld" wrote > >>> How do I make this code print lines NOT containing the string 'Domains'? >>> >> >> Don't use regex, use in: >> >> for line in log: >> if "Domains" in line: >> print line > > Should, of course, be > > if "Domains" not in line: > print line > > Alan G. > > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] returning the entire line when regex matches
Compiling the regular expression works great, I cant find the tutorial Mr. Gauld is referring to!! I searched python.org and alan-g.me.uk. Does anyone have a link? On Mon, May 4, 2009 at 1:46 PM, Martin Walsh wrote: > Nick Burgess wrote: >> So far the script works fine, it avoids printing the lines i want and >> I can add new domain names as needed. It looks like this: >> >> #!/usr/bin/python >> import re >> >> outFile = open('outFile.dat', 'w') >> log = file("log.dat", 'r').read().split('Source') # Set the line delimiter >> for line in log: >> if not re.search(r'notneeded.com|notneeded1.com',line): >> outFile.write(line) > > There is a subtle problem here -- the '.' means match any single > character. I suppose it's unlikely to bite you, but it could -- for > example, a line containing a domain named notneeded12com.net would > match. You should probably escape the dot, and while you're at it > compile the regular expression. > > # untested > pattern = re.compile(r'notneeded\.com|notneeded1\.com') > for line in log: > if not pattern.search(line): > outFile.write(line) > > HTH, > Marty > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] returning the entire line when regex matches
for root, dirs, files in os.walk('./'): for f in files: if f.endswith('.txt'): allfiles.append(os.path.join(root, f)) This returns a list of the *.txt files. Of course now I am stuck on how to apply the delimiter and search function to the items in the list..? Any clues/examples would be great. ty On Mon, May 4, 2009 at 7:32 PM, Alan Gauld wrote: >> Mr. Gauld is referring to!! I searched python.org and alan-g.me.uk. >> Does anyone have a link? > > I posted a link to the Python howto and my tutorial is at alan-g.me.uk > You will find it on the contents frame under Regular Expressions... > Its in the Advanced Topics section. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] returning the entire line when regex matches
forgot to add this at the top, allfiles = [] On Tue, May 5, 2009 at 6:15 PM, Nick Burgess wrote: > for root, dirs, files in os.walk('./'): > for f in files: > if f.endswith('.txt'): > allfiles.append(os.path.join(root, f)) > > This returns a list of the *.txt files. Of course now I am stuck on > how to apply the delimiter and search function to the items in the > list..? Any clues/examples would be great. ty > > On Mon, May 4, 2009 at 7:32 PM, Alan Gauld wrote: >>> Mr. Gauld is referring to!! I searched python.org and alan-g.me.uk. >>> Does anyone have a link? >> >> I posted a link to the Python howto and my tutorial is at alan-g.me.uk >> You will find it on the contents frame under Regular Expressions... >> Its in the Advanced Topics section. >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> ___ >> Tutor maillist - tu...@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] converting xls to csv
Hi list, I am trying to make this code work. I don't have any experience with defining things and this is my second program. The error returmed is "SyntaxError: invalid syntax" code: #!/usr/bin/python import cvs def convertXLS2CSV(aFile): '''converts a MS Excel file to csv w/ the same name in the same directory''' print "-- beginning to convert XLS to CSV --" try: import win32com.client, os excel = win32com.client.Dispatch('Excel.Application') fileDir, fileName = os.path.split(aFile) nameOnly = os.path.splitext(fileName) newName = nameOnly[0] + ".csv" outCSV = os.path.join(fileDir, newName) workbook = excel.Workbooks.Open(aFile) workbook.SaveAs(outCSV, FileFormat=24) # 24 represents xlCSVMSDOS workbook.Close(False) excel.Quit() del excel print "...Converted " + nameOnly + " to CSV" #except: #print ">>> FAILED to convert to CSV!" convertXLS2CSV(r"F:\python\MasterList.xls") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting xls to csv
Thank you for your response and my apologies for the non-useful output. After searching again this task has been done by pyExcelerator, the tool xls2csv-gerry.py does this great. I am now trying to parse through the csv's and return the rows containing the matching strings. Python is looking for string or buffer, this method worked from a text search script, I am stumped on this for now. import re import csv pattern = re.compile(r'10\.229\.127\.255') spamReader = csv.reader(open('MasterIPList.csv'), delimiter=' ', quotechar='|') for row in spamReader: if pattern.search(row): print ', '.join(row) error F:\python>MastIPparse.py Traceback (most recent call last): File "F:\python\MastIPparse.py", line 9, in if pattern.search(row): TypeError: expected string or buffer When I comment out line 9 it returns all of the rows, so I now its reading OK.. Thanks for your time, -nick On Sun, May 31, 2009 at 3:57 AM, Alan Gauld wrote: > > "Nick Burgess" wrote >> >> I am trying to make this code work. I don't have any experience with >> defining things and this is my second program. The error returmed is >> "SyntaxError: invalid syntax" > > Please post the whole error message, much of the useful stufff - like the > location of the problem! - is in the earlier lines. > > However taking a wild guess - are you using Python v3? > >> print "-- beginning to convert XLS to CSV --" > > If so print is now a function so you need to surround the string with () > > But if you are not using v3, then please send the fuill error text. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting xls to csv
Got it. the row is not a string or buffer but the cell is.. for row in spamReader: for cell in row: if pattern.search(cell): print ', '.join(row) On Sun, May 31, 2009 at 5:09 AM, Nick Burgess wrote: > Thank you for your response and my apologies for the non-useful > output. After searching again this task has been done by > pyExcelerator, the tool xls2csv-gerry.py does this great. I am now > trying to parse through the csv's and return the rows containing the > matching strings. Python is looking for string or buffer, this method > worked from a text search script, I am stumped on this for now. > > > import re > import csv > > pattern = re.compile(r'10\.229\.127\.255') > spamReader = csv.reader(open('MasterIPList.csv'), delimiter=' ', > quotechar='|') > for row in spamReader: > if pattern.search(row): > print ', '.join(row) > > > error > > F:\python>MastIPparse.py > Traceback (most recent call last): > File "F:\python\MastIPparse.py", line 9, in > if pattern.search(row): > TypeError: expected string or buffer > > > When I comment out line 9 it returns all of the rows, so I now its reading > OK.. > > Thanks for your time, > > -nick > > On Sun, May 31, 2009 at 3:57 AM, Alan Gauld wrote: >> >> "Nick Burgess" wrote >>> >>> I am trying to make this code work. I don't have any experience with >>> defining things and this is my second program. The error returmed is >>> "SyntaxError: invalid syntax" >> >> Please post the whole error message, much of the useful stufff - like the >> location of the problem! - is in the earlier lines. >> >> However taking a wild guess - are you using Python v3? >> >>> print "-- beginning to convert XLS to CSV --" >> >> If so print is now a function so you need to surround the string with () >> >> But if you are not using v3, then please send the fuill error text. >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> ___ >> Tutor maillist - tu...@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting xls to csv
Thank you. The data is pretty much random throughout the csv's so I think I it would have to iterate over the entire rows . I need to search all .csv files in the current directory. I can get glob to return a list of files. How could I get csv.reader to open all the files in the list? My loop logic must be bad.. I am using ActivePython 2.6.1.1. Any clues would be appreciated. pattern = re.compile(r'10\.191\.239\.0') files = glob.glob("*.csv") csv.reader(open (files), delimiter=' ', quotechar='|') for f in files: for row in f: for cell in row: if pattern.search(cell): print ', '.join(row) Traceback (most recent call last): File "Q:\FILES\COMPUTER_NETWORKING\Python\CVSs\ipSrch-v1.0.py", l csv.reader(open (files), delimiter=' ', quotechar='|') TypeError: coercing to Unicode: need string or buffer, list found On Sun, May 31, 2009 at 12:45 PM, Richard Lovely wrote: > 2009/5/31 Nick Burgess : >> Got it. >> >> the row is not a string or buffer but the cell is.. >> >> for row in spamReader: >> for cell in row: >> if pattern.search(cell): >> print ', '.join(row) >> >> > Alternatively, if you know that the string you want to search for only > appears in a single cell from the row, you could use > > for row in spamReader: > if pattern.search(cell[coll_number_here]): > print ', '.join(row) > > If there is a range of adjacent cells that could contain the text, you > could try something like > if pattern.search('|'.join(row[3:5]) > > For non-adjacent cells, try something like > > targetCells = [1,3,5] > for row in spamReader: > if pattern.search('|'.join(row[i] for i in targetCells)) > > Both of these solutions will be faster than iterating over th entire > row, unless tht is specifically what you want. > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting xls to csv
f seems to be a string containing the file names, so csv.reader isnt actually opening them.. maybe i will play with os.walk..? files = glob.glob("*.csv") for f in files: print f csv.reader(open (f), delimiter=' ', quotechar='|') for row in f: for cell in row: if pattern.search(cell): print ', '.join(row) XLS.xls.org1.csv XLS.xls.org2.csv XLS.xls.org3.csv On Sat, Jun 6, 2009 at 3:33 PM, Emile van Sebille wrote: > On 6/6/2009 12:19 PM Nick Burgess said... >> >> Thank you. The data is pretty much random throughout the csv's so I >> think I it would have to iterate over the entire rows . I need to >> search all .csv files in the current directory. I can get glob to >> return a list of files. How could I get csv.reader to open all the >> files in the list? > > Open the files from within your loop. > >> My loop logic must be bad.. I am using >> ActivePython 2.6.1.1. Any clues would be appreciated. >> >> >> >> pattern = re.compile(r'10\.191\.239\.0') >> files = glob.glob("*.csv") >> >> csv.reader(open (files), delimiter=' ', quotechar='|') >> for f in files: > > do the open here > >> for row in f: >> for cell in row: >> if pattern.search(cell): >> print ', '.join(row) >> > > > Emile > > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting xls to csv
Thanks everyone, the following code works great. It returns the name of the file and the row that matched the reqex. Is it posible to take the regex compile from user input? To make it take an argument, like > csvSearch.py 10.192.55 af = re.compile(sys.argv[1]) pattern = re.compile(af) ? pattern = re.compile(r'10\.191\.2') files = glob.glob("*.csv") for f in files: ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in f: for row in ff: for cell in row: if pattern.search(cell): print f print ', '.join(row) On Sat, Jun 6, 2009 at 4:39 PM, Sander Sweers wrote: > 2009/6/6 Emile van Sebille : >>> for f in files: >>> print f >>> csv.reader(open (f), delimiter=' ', quotechar='|') >> >> you open it here, but don't save a reference to the opened file. Try... >> ff = csv.reader(open (f), delimiter=' ', quotechar='|') > > > >> reader(...) >> csv_reader = reader(iterable [, dialect='excel'] >> [optional keyword args]) >> for row in csv_reader: >> process(row) > > If you are on windows you should open the file in binary mode. > open(f, 'rb') > > Greets > Sander > ___ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] searching for an ip and subnets in a dir of csv's
Good evening List, I am trying to have this script search for an IP or nearest subnet match in a dir of csv's. It works with an absolute match, It will be receiving a whole IP address, so if there is no absolute match no data is returned, however if it is listed somewhere in a subnet I want to know. I need it to search and loop through the 32 bit, then the 24 bit, 16, 8. I am stumped at how to cut of the numbers on the right with the period as the delimiter. I have looked at strip, split need a clue what else to try. Thanks! args.append(arg.strip("\n")) args = list(set(args)) for arg in args: for f in files: pattern = re.compile(sys.argv[1]) < I am thinking loop 4 times and do something different here ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in ff: if any(pattern.search(cell) for cell in row): print f print ', '.join(row) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] searching for an ip and subnets in a dir of csv's
And you were looking for 192.168.1.2, do you want it to return nothing? Or both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest match? I would like it to return both, all possible matches. The data looks something like this in the CSV's, Server foo.bar.org 10.2.2.2such&such org Apache farm subnet 10.2.3.0/24so&so corp. the format is random The script will be ran from a third party tool so only one argument can be passed to it which will be an entire IP address. If within the CSV's there is no 32 bit match there could be a subnet that might match, thats why I need it to loop over the dots. If there is a 32 bit and a subnet match both will be returned which is desirable . I figured out a way to cut of the ends from the dots using the following code, string.rsplit('.',1)[:1]; looping over this and incrementing the first digit cuts of the octets from the IP correctly. My problem now is that the rsplit returns a list and I need a string. I am stuck on how to use the rsplit. Thanks. ipAdres = re.compile(sys.argv[1]) print ipAdres.pattern print ipAdres.pattern.rsplit('.',1)[:1] for arg in args: for f in files: ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in ff: if any(ipAdres.search(cell) for cell in row): print f print ', '.join(row) On Wed, Jul 29, 2009 at 8:13 AM, Wayne wrote: > On Tue, Jul 28, 2009 at 9:36 PM, Nick Burgess > wrote: >> >> Good evening List, >> >> I am trying to have this script search for an IP or nearest subnet >> match in a dir of csv's. It works with an absolute match, It will be >> receiving a whole IP address, so if there is no absolute match no data >> is returned, however if it is listed somewhere in a subnet I want to >> know. I need it to search and loop through the 32 bit, then the 24 >> bit, 16, 8. I am stumped at how to cut of the numbers on the right >> with the period as the delimiter. I have looked at strip, split need a >> clue what else to try. >> >> Thanks! >> >> >> >> args.append(arg.strip("\n")) >> args = list(set(args)) >> for arg in args: >> for f in files: >> pattern = re.compile(sys.argv[1]) < I >> am thinking loop 4 times and do something different here >> ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') >> for row in ff: >> if any(pattern.search(cell) for cell in row): >> print f >> print ', '.join(row) > > It's often helpful to provide example data and solutions so we know exactly > what you're looking for. If we understand quickly, chances are we'll reply > just as quickly. > > If you have the IPs > > 192.168.1.1 > 192.168.1.10 > 192.168.2.2 > 192.169.1.1 > > And you were looking for 192.168.1.2, do you want it to return nothing? Or > both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest > match? > > Also, I don't know if I'd do re.compile on the raw sys.argv data, but > perhaps filter it - just compiling is error prone and possibly a security > hole. Even if you're doing it just for yourself, I'd still try to make it as > break-proof as possible. > > HTH, > Wayne > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clear screen inside python interpreter
I don't think there's a Python command to do this. You can always print enough newlines to clear your view of the window: print "\n" * 80 or use os.system to issue a command the shell/terminal/cmd will understand import os os.system("cls") or import os os.system("clear") I resently made a 'game of life' clone and used the first method to clear the screen. It's good enough for many things! Nick Monte Milanuk wrote: Okay, simple question: is there anything similar to to 'clear' or 'cls' to clean up a console window full of commands in the python shell? Short of exiting and restarting the interpreter I'm not having a lot of luck here. Thanks, Monte ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] droplet like behaviour in Python
pedro wrote: #!/usr/bin/env python # encoding: utf-8 import sys theFilePath = sys.argv[1] print theFilePath But when I try to drop something on it nothing happens. Sorry I guess there is something fundamental that I am missing. Pete Pedro, I'll reply to this message instead of the last one because, I actually tried the little script you have there, and it does work I'm on Windows though. Well, my version of your script is this: - import sys for arg in sys.argv: print arg raw_input() - The raw_input() at the end is what keeps the window open so I can see that something really happened before the window closed. When I drop a file into my script, it prints two lines: The script filename and the filename of the file I dropped. So I call it a win. I don't know how it behaves in mac, but please try and tell. (Also put your usual #!/usr/bin/env python in there to work for you) Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] droplet like behaviour in Python
For the Windows users out there: A google search returned me this: Make Python Scripts Droppable in Windows <http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/> I checked my registry and the extension was there. That must be why my drop script works. No idea how it got there though. FWIW, I have installed Python through the .msi installer. PS: What I like is that the page I linked actually has my little test script in it :D I must be doing something right. PS2: I guess I'm starting to deduce that the answer is platform/installation specific rather than python/script specific. That turns the question it to a whole new direction for me. Nick Nick Raptis wrote: pedro wrote: #!/usr/bin/env python # encoding: utf-8 import sys theFilePath = sys.argv[1] print theFilePath But when I try to drop something on it nothing happens. Sorry I guess there is something fundamental that I am missing. Pete Pedro, I'll reply to this message instead of the last one because, I actually tried the little script you have there, and it does work I'm on Windows though. Well, my version of your script is this: - import sys for arg in sys.argv: print arg raw_input() - The raw_input() at the end is what keeps the window open so I can see that something really happened before the window closed. When I drop a file into my script, it prints two lines: The script filename and the filename of the file I dropped. So I call it a win. I don't know how it behaves in mac, but please try and tell. (Also put your usual #!/usr/bin/env python in there to work for you) Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] To write data in two different fonts?
Your main concern when displaying plain text in HTML is actually only 5 characters: &, <, >, ", ' which you should escape(replace) with their coresponding HTML entities. Here's a few lines of code to give you an idea how to do it: #put this somewhere in the beginning of your script, #tailor it as you like entities = {'&' : '&', '<' : '<', '>' : '>', '"' : '"', "'" : '''} .. #put this in the file crunching loop #I'll use *line* as the text variable, like it would happen #in a *for line in file* scenario for character, entity in entities.items(): line = line.replace(character, entity) . . #do the rest of your stuff with the line --- That's a simple implementation and it actually performs 5 replacements on every line of your file (which is not as slow as you might think though) but should get you started if you need it. You also might want to consider escaping other characters as well (maybe spaces to preserve whitespace without a ) Get your hands on an online HTML entity reference online. Extra points: Include a CSS file with your HTML output to handle representation. With some more lines in your script you can then code different fonts or sizes according to any logic you want. Won't go into explaining HTML though (hint: use the class HTML attribute) If it sounds more complex than you'd like, it's ok. It's more powerful and more rewarding too. Once you get the basic structure in, you can extend your script to do pretty much anything with your text. Nick Alan Gauld wrote: "prasad rao" wrote I put in tag and it worked. But at one particular line in a module the font changed colour.After that all the lines are in blue colour and under lined. How are you viewing the file? As Kent poinred out pure text files have no fonts or colours. So the blue colour must be coming from the tyool you are using to display the contents. It is interpreting sometjhing in the data as a command to switch format. Since you are using HTML it is probably a tag. Have you checked the data for any sequences (or and other < characters for that matter)? figure out why the change of colour of font took place. Open it in a simple text editor like notepad or nano and see what it looks like. HTH, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] To write data in two different fonts?
Dave Angel wrote: As I said, you'd probably get in trouble if any of the lines had '&' or '<' characters in them. The following function from the standard library can be used to escape the line directly, or of course you could use the function Nick supplied. xml.sax.saxutils.escape(/data/[, /entities/]) Escape '&', '<', and '>' in a string of data. You can escape other strings of data by passing a dictionary as the optional /entities/ parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. The characters '&', '<' and '>' are always escaped, even if /entities/ is provided. Let us know if that doesn't do the trick. DaveA Thanks Dave for the info on xml.sax.saxutils.escape Didn't know about this one. For the rest: It is sometimes This is the source code of the xml.sax.saxutils.escape function: --- def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ # must do ampersand first data = data.replace("&", "&") data = data.replace(">", ">") data = data.replace("<", "<") if entities: data = __dict_replace(data, entities) return data - As you can see, it too uses string.replace to do the job. However, using a built-in function that works for what you want to do is preferable. It's tested and might also be optimized to be faster. It's easy and fun to look into the source though and know exactly what something does. It's also one of the ways for a begginer (me too) to progress. From the source code I can see this for example: *Don' t pass the entity dictionary I proposed earlier to this function:* entities = {'&' : '&', '<' : '<', '>' : '>', '"' : '"', "'" : '''} If you pass an entity for '&' into escape(), it will escape it in the already partially escaped string, resulting in chaos. Think of it, this function not checking for a '&' entity passed to it might worth qualifying as a bug :) Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] To write data in two different fonts?
Dave Angel wrote: However, if someone had tried to do that in a single call to the current function, their code would already be broken because the dictionary doesn't preserve order, so the & substitution might not happen first. Wow, I never thought about the dictionary not being sorted messing things up. Thanks for the insight. Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Which version to start with?
What is the best version of python to start out with? I see some discussions on the net about not going to 3.1 but staying with the 2.x releases. But then i see that 3.1 is better if your just starting. Thanks for any insight on which version to go with. -Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which version to start with?
Thanks all! I think i will install the newly released 2.6.3 and go from there. Its a little intimidating but i guess i gotta jump right in and get my feet wet. Thanks again! -Nick On Mon, Oct 5, 2009 at 5:59 PM, wesley chun wrote: > On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: >> What is the best version of python to start out with? I see some >> discussions on the net about not going to 3.1 but staying with the 2.x >> releases. But then i see that 3.1 is better if your just starting. > > > greetings nick! > > ironically, i just gave a talk on this very subject yesterday afternoon(!) > http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 > > basically, if you're starting from scratch as a hobby with no > pre-existing code, then learning 3.x is okay. however, since most of > the world still runs on Python 2, most printed and online books and > tutorials are still on Python 2, and the code at most companies using > Python is still on version 2, i would recommended any release 2.6 (and > newer). the reason is because 2.6 is the first release that has > 3.x-specific features backported to it, so really, it's the first > Python 2 release that lets you start coding against a 3.x interpreter. > > you can learn Python using 2.6+ then absorb the differences and move > to Python 3.x quite easily. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- --Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Not storing the PATH in ZipFile?
I was reading another thread and decided to work on a little project to backup some files on a regular basis. Since this will mostly be on windows i am using zipfile and i can create my zip file just fine and all the files are there, it works great! My question is however, is there a way to NOT store the path in the zip file? When i decompress the files, i would like them to not be associated with a particular folder or path, just the files. I looked through the docs but didn't see anything to disable the path. Thanks, -Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Not storing the PATH in ZipFile?
That was it. Thanks so much! I was looking at the docs and didn't think that applied to the path that was stored. Thanks Again! -Nick On Wed, Oct 14, 2009 at 12:16 PM, Kent Johnson wrote: > On Wed, Oct 14, 2009 at 11:38 AM, Nick Hird wrote: >> I was reading another thread and decided to work on a little project >> to backup some files on a regular basis. Since this will mostly be on >> windows i am using zipfile and i can create my zip file just fine and >> all the files are there, it works great! My question is however, is >> there a way to NOT store the path in the zip file? When i decompress >> the files, i would like them to not be associated with a particular >> folder or path, just the files > > ZipFile.write() takes an optional arcname parameter, this is the name > the file wll have in the archive. If you pass the plain file name (no > path components) as arcname I think it will do what you want. > > Kent > -- --Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Can python determine Battery or AC Power?
Is there a way in python to tell if the power source for a laptop is ac or battery? I am trying to write a small script to print out my system stats and would like to know if the laptop is on battery power or using ac power. I just dont know enough python to know where to look for that info. Thanks! -Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can python determine Battery or AC Power?
I am running Windows XP. On Wed, Oct 28, 2009 at 5:19 PM, Luke Paireepinart wrote: > If you're on Windows and you can find an example using the Win32 api (in C++ > for example) you can use pywin32 module to do the same thing through > python. It's a little complicated sometimes though. So what O.S. are you > on? > > On Wed, Oct 28, 2009 at 4:15 PM, Nick Hird wrote: >> >> Is there a way in python to tell if the power source for a laptop is >> ac or battery? I am trying to write a small script to print out my >> system stats and would like to know if the laptop is on battery power >> or using ac power. I just dont know enough python to know where to >> look for that info. >> >> Thanks! >> -Nick >> ___ >> Tutor maillist - tu...@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- --Nick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introduction - log exercise
> I will read lines from file, with the 'for loop', and then I will check them > for > 'foo' matches with a 'while loop', if matches I (somehow) re-initialise the > list, and if there is no matches for foo, I will append line to the list. > When I > get to a blank line (end of block), write myList to an external file. And > start Can you please explain what you mean by _re-initialize the list_ ? > with another line. > > I am stuck with defining 'blank line', I don't manage to get throught the > while > loop, any hint here I will really appreciate it. > I don't expect the solution, as I think this is a great exercise to get wet > with python, but if anyone thinks that this is the wrong way of solving the > problem, please let me know. > > Can you explain why the following won't work? #!/usr/bin/python import sys import gzip # At the moment not bother with argument part as I am testing it with a # testing log file #fileIn = gzip.open(sys.argv[1]) fileIn = gzip.open('big_log_file.gz', 'r') fileOut = open('outputFile', 'a') for line in fileIn: while line != 'blank_line': if 'foo' not in line: fileOut.write(line) > > > Somehow rename outputFile with big_log_file.gz > > fileIn.close() > fileOut.close() > > - > > The log file will be fill with: > > > Tue Nov 17 16:11:47 GMT 2009 > bladi bladi bla > tarila ri la > patatin pataton > tatati tatata > > Tue Nov 17 16:12:58 GMT 2009 > bladi bladi bla > tarila ri la > patatin pataton > foo > tatati tatata > > Tue Nov 17 16:13:42 GMT 2009 > bladi bladi bla > tarila ri la > patatin pataton > tatati tatata > > > etc, etc ,etc > .. > > Again, thank you. > > -- > - > Antonio de la Fuente Mart?nez > E-mail: t...@muybien.org > - > > ___ > 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] walking directories
Hi folks, Im running python2.4 on linux. I have many python scripts in various directories of varying depth under my home directory, and I need to change one line in each of these files. I thought about using os.walk with os.path.join eg >>> for r,d,f in os.walk('.'): ... print os.path.join(r,d,f) but I get this error Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.4/posixpath.py", line 60, in join if b.startswith('/'): AttributeError: 'list' object has no attribute 'startswith' which makes sense. I know I can use glob.glob on the current directory, but Im struggling to see how I can access these files, change them and save the changes. Im also a little annoyed with myself cos I feel that I really should know how to do this by now. If anyone can just give me a pointer in the right direction I would be very grateful. Many thanks Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] walking directories
>>From: Ryan Davis [mailto:[EMAIL PROTECTED] ?? >>I think you want to be doing something like: >> >>>for r,d,f in os.walk('.'): >>... for filename in f: >>... print os.path.join(r,filename) >> >>I think that would give you the full path of every file, and then you can open it, do a regex substitution or whatever close it and >>keep going. >> >>From: Jacob Schmidt >> >>for root, dirs, files in os.walk(directory): >>for x in files: >>print os.path.join(root,x) Thankyou Ryan and Jacob, I obviously did not read the docs for os.walk correctly, many thanks. >>Alan G. >>personally I'd use find and sed in Linux, right tool >>for the job etc.. Yes I could use *nix tools for the job, but I want to do it in python to see if I can :) Thanks again everyone for your help. Nick . -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 265.6.9 - Release Date: 06/01/2005 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
FW: [Tutor] walking directories
Hello, I sent this reply a few days ago, but it doesn't seem to have appeared on the list, so Im resending it. Many thanks Nick . -Original Message- From: Nick Lunt [mailto:[EMAIL PROTECTED] Sent: 08 January 2005 19:44 To: 'python tutor' Subject: RE: [Tutor] walking directories >>From: Ryan Davis [mailto:[EMAIL PROTECTED] ?? >>I think you want to be doing something like: >> >>>for r,d,f in os.walk('.'): >>... for filename in f: >>... print os.path.join(r,filename) >> >>I think that would give you the full path of every file, and then you can open it, do a regex substitution or whatever close it and >>keep going. >> >>From: Jacob Schmidt >> >>for root, dirs, files in os.walk(directory): >>for x in files: >>print os.path.join(root,x) Thankyou Ryan and Jacob, I obviously did not read the docs for os.walk correctly, many thanks. >>Alan G. >>personally I'd use find and sed in Linux, right tool >>for the job etc.. Yes I could use *nix tools for the job, but I want to do it in python to see if I can :) Thanks again everyone for your help. Nick . -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 265.6.9 - Release Date: 06/01/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.300 / Virus Database: 265.6.9 - Release Date: 06/01/2005 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 3 questions for my port scanner project
Nr 3. If your using python sockets try socket.settimeout(x) Nick . On Sat, 2005-02-26 at 15:12 +0200, Mark Kels wrote: > Hi list. > > Here are the questions (-: > 1. How do I make a progress bar in Tkinter ? > 2. I got a while loop which does the port scan itself. How can I end > it while its working ? > 3. For some reason the scan is too slow (2-3 seconds for a port). Is > there a way to make it faster (other port scanner work allot faster... > ) ? > > Thanks in advance !! > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sys.argv[1: ] help
Richard, if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] then you are bound to get an empty list returned, [] . Im not sure I understand the problem you think you've got but here's what happens with sys.argv for me, and it's correct. [argl.py] $ cat argl.py #!/usr/bin/python import sys print sys.argv[1:] ./argl.py [] ./argl.py a b c ['a', 'b', 'c'] Is that what your getting ? > Sorry for the late response, I tried all of the the suggestions, > including correcting my typo of print sys[1:] and tried print > sys,argv[1:], this does now work as long as I run 'python test.py fred > joe' it returns all the arguments. If I try just test.py all I get is > '[]' . Is there something wrong with my environmental variables in > Windows XP, I would like to be able to just use the file name rather > than having to type python each time. Any help would be gratefully received. > > Richard G. > ___ > 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] reading from stdin
Hi folks, I've been pondering how to get python to read from a pipe outside of itself, sort of. For example I tried a simple python prog to do a grep, eg # ps -e | myprog.py cron would give this output 3778 ?00:00:00 crond same as # ps -e | grep cron The way I did this was to use sys.stdin.readlines() to get the output from the pipe. Here is the program: [code] import sys, glob args = sys.stdin.readlines() # found on the net pat = sys.argv[1] for i in args: if (i.find(pat) != -1): print i, [/code] My question is am I getting the output from the pipe in the correct way ? The way Im doing it works (so far) but should I be doing it another way ? Many thanks Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > unless you want the output for some other reason, a more idiomatic way > is: > > for line in sys.stdin.readlines(): > # handle the line > > I tend to use xreadlines() which does not read the entire input at once. > For stdin this make sense, you have no idea how much data will be > piped in. Thanks Sean, I agree with you on both accounts there. Cheers Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
On Tue, 2005-03-01 at 22:20 +, Max Noel wrote: > I don't think you are. You're using readlines(), which means your > program won't execute until ps terminates. > UNIX philosophy is to have programs start acting as soon as possible > -- in that case, as soon as the first line is available. You should be > reading sys.stdin as an iterator (same thing you'd do for a file): > > import sys > for line in sys.stdin: > # do stuff with that line of input Aha, that makes sense. Thanks very much. Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
On Wed, 2005-03-02 at 11:22 +1300, [EMAIL PROTECTED] wrote: > Quoting Sean Perry <[EMAIL PROTECTED]>: > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > xreadlines() these days just does 'return self', I believe. File objects are > their own iterators; you can just do: > > for line in sys.stdin: > # do stuff > Same as Max Noel said, must be a good idea ;) Thankyou Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
Thanks to everyone who helped me with this. It's certainly given me something to think about :) Cheers Nick . On Tue, 2005-03-01 at 23:13 -0600, David Rock wrote: > * Nick Lunt <[EMAIL PROTECTED]> [2005-03-01 22:23]: > > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > > > > unless you want the output for some other reason, a more idiomatic way > > > is: > > > > > > for line in sys.stdin.readlines(): > > > # handle the line > > > > > > I tend to use xreadlines() which does not read the entire input at once. > > > For stdin this make sense, you have no idea how much data will be > > > piped in. > > > > Thanks Sean, I agree with you on both accounts there. > > For another approach to this, I like to use the fileinput module. In the > case of the original example of mimicing grep, it allows you to easily > handle both a list of files passed to the command or use it as a pipe. > The default action if there are no files given is to use stdin. > > http://www.python.org/doc/2.4/lib/module-fileinput.html > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
Hi Hugo, many thanks for pointing that out. It all helps :) Thanks again, Nick . On Tue, 2005-03-01 at 17:35 -0600, Hugo GonzÃlez Monteverde wrote: > Everypne else has answered pretty muh about this. I just want to add > that if you want to read noncanonically (less thana line ending in "\n" > you'll have to do it char by char =( AFAIK, there's no way to redefine a > separator por readlines() (other than \n..) > > Hugo > > Nick Lunt wrote: > > Hi folks, > > > > I've been pondering how to get python to read from a pipe outside of > > itself, sort of. > > > > For example I tried a simple python prog to do a grep, eg > > > > # ps -e | myprog.py cron > > > > would give this output > > > > 3778 ?00:00:00 crond > > > > same as > > # ps -e | grep cron > > > > The way I did this was to use sys.stdin.readlines() to get the output > > from the pipe. > > > > Here is the program: > > > > [code] > > import sys, glob > > args = sys.stdin.readlines() # found on the net > > pat = sys.argv[1] > > for i in args: > > if (i.find(pat) != -1): > > print i, > > [/code] > > > > My question is am I getting the output from the pipe in the correct > > way ? The way Im doing it works (so far) but should I be doing it > > another way ? > > > > Many thanks > > Nick . > > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [HELP]how to test properties of a file
I've gotten into the habit of just using the os.?_OK stuff. eg >>> import os >>> os.access('/', os.W_OK) False >>> os.access('/tmp', os.W_OK) True Thats gotta be simple if I understand it lol :) Nick . Alan Gauld wrote: The simplest, IMHO, is : try: f = file(filename, "w") [...] except IOError: print "The file is not writable" Of course, not that this method empty the file if it is writable ! The best is to just put your IO code in such a try block ... That way, you're sure the file has the right mode. Its not really the simplest, its not efficient and it might be dangerous if the file is not empty. At the very least open using 'a' to avoid obliterating the file!! However the os.stat function and stat module do what you want safely and more comprehensively: --- Help on module stat: NAME stat - Constants/functions for interpreting results of os.stat() and os.lstat(). FILE /usr/lib/python2.3/stat.py DESCRIPTION Suggested usage: from stat import * DATA ST_ATIME = 7 ST_CTIME = 9 ST_DEV = 2 ST_GID = 5 ST_INO = 1 ST_MODE = 0 ST_MTIME = 8 ST_NLINK = 3 ST_SIZE = 6 ST_UID = 4 S_ENFMT = 1024 - The constants above are the indices into the tuple returned by os.stat() That will tell you most of the things you need to know, check the docs to find out what they all mean. For your purposes the important one is ST_MODE. So import os from stat import * status = os.stat('somefile.txt')[ST_MODE] if status & S_IWRITE: print 'writable' elif staus & S_IREAD: print 'readable' else: print 'status is ', status Notice you have to use bitwise AND (&) to extract the status bits. HTH Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [HELP]how to test properties of a file
Shidai Liu wrote: I found out in the following situation, it fails to work. Say, 'somefile.csv' is opened by EXCEL, os.access('somefile.csv', os.W_OK) True file('somefile.csv', 'w') IOError: [Errno 13] Permission denied: 'somefile.csv' By the way, using os.stat & stat as suggested by Alan doesn't work either. Any idea how solve it? I havent got access to a windows box unfortunately at the moment. And I have no idea about permissions on windows boxes anyway :) However, did you already have the .csv file open in Excel or some other app ? Or is is password protected maybe ? Sorry not much help. Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clock.py
Feziwe Mpondo wrote: >clock.py,problem is to get the last two digits to be random.her's what i >tried >from time import time,ctime >prev_time = "" >while(1): >the_time = ctime() >if (prev_time != the_time): > print "The time is :",ctime(time()) >prev_time = the_time >guess = 0 >number = 1-60 >while guess != number: >guess = input ("Guess the last two digits:") >if guess > number: >print "Too high" >elif guess < number: >print "Too low" >print "Just right" >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > Hi Feziwe, you might want to look at the random module to generate 'guess' ramdon.randrange() more specifically. Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are Empty "Placeholder" Functions possible?
Hi John, you can use 'pass' . This works the same as with exceptions, eg try: open('somefile') except IOError: pass so we can have class doNothing: def __init__(self): pass def boring(self, other): pass Hope that helps :) Nick -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Gooch, John Sent: 26 May 2005 16:43 To: tutor@python.org Subject: [Tutor] Are Empty "Placeholder" Functions possible? Is there a way to create an empty function definition with no lines of code in it? In my coding style I will often do this ( in other languages ) for RAD just to remind myself that I will need to implement the function later. Example: For a file handling class, I may need functions such as copy,delete,move,etc so I want to start off with: class FileHandler: def __init__(self): def copy(self): def delete(self): . . . then in my driver/aka testing file: import FileHandler def main() MyHandler = FileHandler() print "Handler Created." main() Right now, this won't work as the compliler will error on functions with nothing in them. Is there a "no-op", "do nothing", or some similar command I can put in the empty functions to keep the compiler/interpreter from erroring on them? This would really help speed up my development so that I can create the class skeleton quickly and then implement each function and test it as I go. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- No virus found in this incoming message. Checked by AVG Anti-Virus. Version: 7.0.322 / Virus Database: 266.11.17 - Release Date: 25/05/2005 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] screen scraping web-based email (Alan Gauld)
Alan, Please let us know when you have a draft of your tutorial on Beautiful Soup and such. I'd be eager to have a look! Thanks, Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python internet archive API?
I'm a novice Python programmer, and I've been looking for a way to collect archived web pages. I would like to use the data on Internet Archive, via the "Wayback Machine". Look, for example, at http://web.archive.org/web/*/http://www.python.org <http://web.archive.org/web/*/http:/www.python.org> . I'd like to crawl down the first few levels of links of each of the updated archived pages (the ones with *'s next to them). The site's robots.txt exclusions are complete, so a screen-scraping strategy doesn't seem doable. Does anyone have any suggestions for a way to go about this pythonically? Many thanks, Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sys.path, managing modules and packages
Can someone help me better understand how I ought to manage the modules and packages that I download? I often find that I can't use the code I've just downloaded, despite putting it into Lib/site-packages. Often I've added the subdirectory path via sys.path.append, but this seems to go only one level down, whereas I thought that when trying to import something python would search all subdirectories of the directories in the sys.path. I'd be glad for some basic instruction on the steps I need to take between downloading code from sourceforge and importing the functions in my scripts or at the command line. Thanks, Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] number guessing game
here is my code so far from Tkinter import* root = Tk() root.title("main screen") root.maxsize(width=350,height=200) root.minsize(width=350,height=200) root.resizable(width=YES,height=YES) def child1(): c1 = Toplevel(root) c1.guess_ent = Entry(c1, width = 35,) c1.guess_ent.grid(row = 14, column = 0) c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) c1.box_txt.grid(row = 3, column = 0, columnspan=2) c1.title("easy") c1.geometry("200x200") Button(c1,text="clear").grid(row=1,column=0) Button(c1,text="new game",).grid(row=1,column=1) def child2(): c2 = Toplevel(root) box_txt = Text(c2, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c2.title("medium") c2.geometry("200x200") def child3(): c3 = Toplevel(root) box_txt = Text(c3, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c3.title("hard") c3.geometry("200x200") Label(root,text = "choose which game you would like to play").grid(row=0,column=0,columnspan=2) Button(root,text="easy",command=child1).grid(row=1,column=0) Button(root,text="medium",command=child2).grid(row=1,column=1) Button(root,text="hard",command=child3).grid(row=1,column=3) This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] random number guessing game
i am tying to buil a program using child screens the program is going the make a random number and the user has to guess it . so far i have made the gui but how do i progame it to make the random number This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] were do i put the random number genorator
i am tyin to make a number guesing game were do i put the random genorator it the top of each child screen def here is my code from Tkinter import* root = Tk() root.title("main screen") root.maxsize(width=350,height=200) root.minsize(width=350,height=200) root.resizable(width=YES,height=YES) def child1(): c1 = Toplevel(root) c1.guess_ent = Entry(c1, width = 35,) c1.guess_ent.grid(row = 14, column = 0) c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) c1.box_txt.grid(row = 3, column = 0, columnspan=2) c1.title("easy") c1.geometry("200x200") Button(c1,text="clear", command = NIck).grid(row=1,column=0) Button(c1,text="new game",).grid(row=1,column=1) def NIck(): child1.box_txt.delete(0.0, END) def child2(): c2 = Toplevel(root) box_txt = Text(c2, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c2.title("medium") c2.geometry("200x200") def child3(): c3 = Toplevel(root) box_txt = Text(c3, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c3.title("hard") c3.geometry("200x200") Label(root,text = "choose which game you would like to play").grid(row=0,column=0,columnspan=2) Button(root,text="easy",command=child1).grid(row=1,column=0) Button(root,text="medium",command=child2).grid(row=1,column=1) Button(root,text="hard",command=child3).grid(row=1,column=3) This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
how do you import sounds This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyCrust IDE/Shell
Hi Alan, Your excitement for the PyCrust IDE made me want to check it out, but after downloading wxPython and the "Docs and Demos" at http://www.wxpython.org/download.php#prerequisites I've not been able to find an IDE to launch. Can you explain what I need to do? Thanks, Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyCrust IDE/Shell
Hi Hieu, In my Scripts folder there are MS-DOS batch files and files without extensions that include "pycrust" and "pyalamode". Double-clicking either version of pycrust in this folder doesn't do anything I can see. There are no .py files (apart from CreateBatchFiles.py and CreateMacScripts.py, which creates the MS-DOS batch files from the extension-less files), so how should I run pycrust? Thanks in advance for any further help you can provide. Nick -Original Message- From: Hiếu Hoàng [mailto:[EMAIL PROTECTED] Sent: Friday, June 01, 2007 3:42 PM To: Switanek, Nick Cc: tutor@python.org Subject: Re: [Tutor] PyCrust IDE/Shell Hi Nick, Installing wxPython on Windows creates a Scripts folder, in which the goodies like PyCrust and Pyalamos are installed, you can run it and be good to go. On *nix, the scripts would be installed in the prefix's bin dir, hopefully all starting with py :-) The PyCrust is a better python shell (than the defacto one and the one in IDLE), not quite a full blown IDE. I know of the SPE by Stani at <http://pythonide.blogspot.com/> that use PyCrust, but I'm not aware of any other one. HTH, Hieu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyCrust IDE/Shell
Hi Alan, Thanks for the path. I find a .py, .pyc, and an icon file name PyCrust, but no .pyw. Any ideas? Thanks, Nick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyCrust IDE/Shell
Thanks for this suggestion, Grant, it might prove illuminating. I got this import error when I tried running PyCrust.py from within PythonWin (version 2.5). "ImportError: Module use of python24.dll conflicts with this version of Python." I also have previous versions of python installed, so maybe there is some confusion there? If so, I'd be grateful for help understanding what I need to do to resolve it. Thanks, Nick From: Grant Hagstrom [mailto:[EMAIL PROTECTED] Sent: Friday, June 01, 2007 4:33 PM To: Switanek, Nick Cc: tutor@python.org Subject: Re: [Tutor] PyCrust IDE/Shell Nick, Have you tried copying the contents of PyCrust.py into your current IDLE? Running that script will cause PyCrust to open on my machine. Perhaps this is a start . . . - Grant On 6/1/07, Switanek, Nick <[EMAIL PROTECTED]> wrote: Hi Alan, Thanks for the path. I find a .py, .pyc, and an icon file name PyCrust, but no .pyw. Any ideas? Thanks, Nick ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
im not sure why this progrm isnt running properly one of the button wont open and it teel me a computer_guess is not defined here is my code #NiCk TrEloaR PrOgRaMiNg Co. #scissors paper rock #10/6/07 from Tkinter import* from random import choice class Application(Frame): def __init__(self,master): """Initalize Frame.""" Frame.__init__(self,master) self.grid() self.create_widget() self.computer_guess() #creating user indstructions def create_widget(self): #create description label Label(self, text="scissors paper rock " ).grid(row = 0,column = 0,sticky = W) #create the exit button self.exit_bttn = Button(self, text = "Exit", font = ("Arial", 12, "bold"), command = self.quit) self.exit_bttn.grid(row = 30, column = 0, sticky = E) #create the rock button self.rock_bttn = Button(self, text = "rock", font = ("Arial", 12, "bold"), command = self.rock) self.rock_bttn.grid(row = 1, column = 1, sticky = W) #create the scissors button self.scissors_bttn = Button(self, text = "scissors", font = ("Arial", 12, "bold"), command = self.scissors) self.scissors_bttn.grid(row = 2, column = 2, sticky = W) #create the paper button self.paper_bttn = Button(self, text = "paper", font = ("Arial", 12, "bold"), command = self.paper) self.paper_bttn.grid(row = 3, column = 3, sticky = W) def rock(self): value = "rock" computer_guess == random.choice(["scissors", "paper", "rock"]) if computer_guess == "rock": Label(self, text = "this is a draw!!", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) elif computer_guess == "paper": Label(self, text = "you lose paper smothers rock", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) else: Label(self, text = "you win rock smashes scissors", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) def scissors(self): value = "scissors" computer_guess == random.choice(["scissors", "paper", "rock"]) if computer_guess == "rock": Label(self, text = "computer wins rock smashes scissors", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) elif computer_guess == "paper": Label(self, text = "you win rock smaches scissors", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) else: Label(self, text = "this is a draw", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) def paper(self): value = "paper" computer_guess == random.choice(["scissors", "paper", "rock"]) if computer_guess == "rock": Label(self, text = "yau win paper smothers rock", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) elif computer_guess == "paper": Label(self, text = "this is a draw", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) else: Label(self, text = "computer wins scissors cut paper", fg = "blue", font = ("Arial", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) root=Tk() root.title("scissors paper rock") root.geometry("600x600") app = Application(root) _ Advertisement: Ministry of Sound's Sessions 4 has arrived. Have a listen! http://ninemsn.com.au/share/redir/adTrack.asp?mode=click&clientID=788&referral=hotmailtagline&URL=http://music.ninemsn.com.au/playlist.aspx?sectionid=2465§ionname=artistfeature&subsectionid=9961&subsectionname=sessions4&categoryid=2602 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] lan with python
hey i was just wondering if any one could tell me if they know if you can make multi player games through lan with python heres the code i want to lan. just hash out the sound files #NiCk TrEloaR PrOgRaMiNg Co. #scissors paper rock #10/6/07 from Tkinter import* import pygame from random import choice class Application(Frame): def __init__(self,master): """Initalize Frame.""" Frame.__init__(self,master) self.grid() self.create_widget() self.comput_count = 0 self.user_count = 0 pygame.mixer.init() self.gun = pygame.mixer.Sound("shotgun1.wav") self.bang = pygame.mixer.Sound("explosion.wav") self.laugh = pygame.mixer.Sound("evil_laf.wav") self.music = pygame.mixer.Sound("Unholy_confessions.wav") self.music.play() self.music.set_volume(0.4) self.bang.set_volume(1.0) self.laugh.set_volume(1.0) #creating user indstructions def create_widget(self): root.configure(bg = "green") #create description label Label(self, text="scissors paper rock ", font = ("Bauhaus 93", 28, "bold", ) ).grid(row = 1,column = 0,sticky = W, columnspan = 4) #create the exit button self.exit_bttn = Button(self, text = "Exit", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.end ) self.exit_bttn.grid(row = 16, column = 3, sticky = W) #create the rock button self.rock_bttn = Button(self, text = "rock", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.rock) self.rock_bttn.grid(row = 3, column = 0, sticky = W) #create the scissors button self.scissors_bttn = Button(self, text = "scissors", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.scissors) self.scissors_bttn.grid(row = 5, column = 0, sticky = W) #create the paper button self.paper_bttn = Button(self, text = "paper", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.paper) self.paper_bttn.grid(row = 7, column = 0, sticky = W) # reset button self.reset_bttn = Button(self, text = "new game", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.reset) self.reset_bttn.grid(row = 16, column = 0, sticky = W) # dynamite self.reset_bttn = Button(self, text = "dynamite", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.dynamite) self.reset_bttn.grid(row = 8, column = 0, sticky = W) #dynamite lable Label(self, text="you can only use the dynamie button when you have a score of ten", font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 17,column = 0,sticky = S, columnspan = 8) # help button self.reset_bttn = Button(self, text = "help", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.help1) self.reset_bttn.grid(row = 16, column = 2, sticky = W) def rock(self): if self.user_count ==(20): self.victory() if self.comput_count ==(20): self.loss() value = "rock" computer_guess = choice(["scissors", "paper", "rock"]) if computer_guess == "rock": Label(self, text = "this is a draw!! ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) elif computer_guess == "paper": self.laugh.stop() self.laugh.play() Label(self, text = "you lose paper smothers rock", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.comput_count = (self.comput_count+1) else: self.laugh.stop() self.gun.play() Label(self, text = "you win rock smashes scissors
[Tutor] Should I be thinking of threads for this ?
Hello folks, I have the following code taken from the Twisted examples - [code] # filewatcher.py from twisted.application import internet def watch(fp): fp.seek(fp.tell()) for line in fp.readlines(): sys.stdout.write(line) import sys from twisted.internet import reactor s = internet.TimerService(1.0, watch, file(sys.argv[1])) s.startService() reactor.run() s.stopService() [/code] I find this piece of code amazing and I am keen to put it to use. If I run './filewatcher.py myfile' it will print out any changes made to 'myfile', very similar to 'tail -f' . Now if I want to have this program monitor several files at once I could run './filewatcher.py file1 file2 filex' or './filewatcher.py file1 & ./filewatcher file2 & etc' both with minor modifications to the code, but I think that could cause performance problems relating to the OS. So I'm thinking I will need to learn python threads (no bad thing) instead, but Im hoping that someone could tell me if that seems the best way to go ? I will be getting to grips with python threads anyway but I'd appreciate any input on this. Many thanks, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Should I be thinking of threads for this ?
Hi Kent, > > > > [code] > > # filewatcher.py > > from twisted.application import internet > > > > def watch(fp): > > fp.seek(fp.tell()) > > for line in fp.readlines(): > > sys.stdout.write(line) > > > > import sys > > from twisted.internet import reactor > > s = internet.TimerService(1.0, watch, file(sys.argv[1])) > > s.startService() > > reactor.run() > > s.stopService() > > [/code] > > > > What performance problems you you anticipate? I don't know much > about Twisted but my understanding is that tasks are run in a > single thread when they are ready. In your case you are > scheduling a simple task to run every second. I would think that > you could schedule several such tasks and they would each run > every second. If your task were time-consuming you might have to > worry about doing something different but in this case I think it > will be fine. Just try something like > > for name in sys.argv[1:]: > s = internet.TimerService(1.0, watch, file(name)) > s.startService() > That's one way I was thinking of doing it. I'll run it like that on about 10 active files and see how it stacks up. > twisted.protocols.basic.FileSender and > twisted.internet.stdio.StandardIO look like they may be starting points. Thanks for the twisted pointers. I've been using twisted for a little while but it's such a massive thing that it can be difficult to fully understand whats happening. Thanks for you help, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tail -f problem
Hi Alberto, > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] Behalf Of > Alberto Troiano > Sent: 31 August 2005 22:01 > To: tutor@python.org > Subject: [Tutor] Tail -f problem > > > Hey > I thought about tail-f > /var/log/radacct/max/detail but this thing opens a console and I > won't end > but how can I get the output of the command to python.. Have a look here for a possible solution to your tail -f problem http://twistedmatrix.com/projects/core/documentation/examples/filewatch.py > I know the second option has nothing to do with this forum but if anyone > knows of any manual to upgrade MySQL over Linux Red HAt I would appreciate If your using a recent Redhat then try this as root (im on a windows box at the moment so this is untested) $ yum upgrade mysql mysql-server Naturally this will only work if your current mysql install is an RPM. Cheers Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to create GUI for Python progs
Hi Olexiy, > I'm really confused on the issue how to create windows, forms, etc. in > Python & can't find any manual for that. > Could you possibly advise me smth useful? > -- > Best regards, > > Olexiy Kharchyshyn this has come up quite a bit recently on the list. I would recommend that you go here http://pythoncard.sourceforge.net/index.html to get PythonCard and then go here http://pythoncard.sourceforge.net/walkthrough1.html to read the docs. It will take all of 10 minutes to be able to create a decent GUI. Hth, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to alter list content
Hi marc, > > i create a list of all JPG files with: > >>> list = glob.glob('*.JPG') > the content of 'list' is now: > >>> print list > ['DSC1.JPG', 'DSC2.JPG', 'DSC3.JPG'] > > but what i want is this type of list: > ['DSC1', 'DSC2', 'DSC3'] > i.e. the names w/o the file extension. > > what's the easiest way of doing this? > > marc You need the split() method. ie >> l = ['DSC1.JPG', 'DSC2.JPG', 'DSC3.JPG'] >> print [i.split('.')[0] for i in l] Hth, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path
Hi Andy, > Behalf Of Andy Dani > > Python 2.3.2 came with the linux distribution which is located in > /usr/lib. > > Installed 2.4.1 in /usr/local/Python-2.4.1 > > updated /etc/profile path so IDLE or "python" would point to the > latest version (2.4.1). > > PATH="$PATH:/usr/local/Python-2.4.1/:." > export PATH > > But it is still pointing to the old one unless I go > /use/local/Python-2.4.1/python. > > I want to be able to launch and run python 2.4.1, from the user > account so I do not need to be "root" every time. The default install of python on Mandrake probably install the python executable in /usr/bin/python. /usr/bin/ is in your PATH, so if you put PATH=$PATH:/usr/local/Python-2.4.1 in /etc/profile it will still pick up the default python install. Try typing 'which python' at the command line and see what it picks up. Chances are it will be /usr/bin/python. You could solve this by either putting PATH=/path/to/my/wanted/python/dir:$PATH in /etc/profile (or ~/.bash_profile) or by putting an alias in ~/.bashrc, such as 'alias python='path/to/my/wanted/python/dir/python'. What I must stress is that you do not overwrite your default python installation, leave it as it is, otherwise many of mandrakes GUI tools will no work. I hope that helps, feel free to ask more questions about this as I have had to overcome the same issue on RHEL serveral times. Hth, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.4.1 on Mndrk Linux 10.1 - path
Hi Andy, Andy Dani wrote: >Thanks Nick, > >Any idea about the second question? When I python from >/usr/loca/Python-2.4.1/bin, it does launch the interpreter but with an >traceback error saying there is some conflict with "import readline" line on >pythonrc.py file located somewhere in /etc/ directory. Is there any harm If I >comment the it out (import readline)? > >Thanks - Andy > > Im sorry I have no idea what problem your having with "import readline", I have never come across that error. However, Im certain that one of the python tutors will be able to help you out. Good Luck, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] new user question about while loops
Sorry for potential double post, error with first send -- Hello all, I had a new question about python. I am pretty much in tutorial learning stages, but attempting to create sample programs not in my book to learn how to construct scripts. I understand the format of while loops, but is it possible to use the random.randrange function in them? My goal, create a program that flips a coin 100 times, at the end it says the number of times it flipped heads and flipped tails. My dilemia, how do I get this to work with a while loop? I tried intially assigning heads=0 tails=1 then I figured I could just do a while loop and then use the random function each time. At the end it could count the number of times the random generated a 0 or a 1. However I can't seem to construct it in a way that makes or works. Thanks!___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new user question about while loops
print "This is a coin flip game" print "\n100 flips will be made and it will show the amount of times heads or tails came up" import random #assigning variables to track the amount of times heads or tails comes up heads=0tails=1 flip=100while flip < 100: flip -= 1 random.randrange(2) if flip < 100: break print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads raw_input() From: bob [mailto:[EMAIL PROTECTED]Sent: Tue 10/25/2005 10:58 PMTo: Nick Eberle; tutor@python.orgSubject: Re: [Tutor] new user question about while loops At 10:53 PM 10/25/2005, Nick Eberle wrote: Content-class: urn:content-classes:messageContent-Type: multipart/alternative;boundary="_=_NextPart_001_01C5D9F1.A836CF4F"Sorry for potential double post, error with first send--Hello all, I had a new question about python. I am pretty much in tutorial learning stages, but attempting to create sample programs not in my book to learn how to construct scripts. I understand the format of while loops, but is it possible to use the random.randrange function in them? My goal, create a program that flips a coin 100 times, at the end it says the number of times it flipped heads and flipped tails. My dilemia, how do I get this to work with a while loop? I tried intially assigning heads=0tails=1 then I figured I could just do a while loop and then use the random function each time. At the end it could count the number of times the random generated a 0 or a 1. However I can't seem to construct it in a way that makes or works. Show us your code, as flawed as it might be. Then we can advise you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new user question about while loops
Ahh makes much more sense, thanks for all the help! I'll go back and rework it, keeping in mind trying to solve each piece separately. Thanks again all. -Original Message- From: Alan Gauld [mailto:[EMAIL PROTECTED] Sent: Wednesday, October 26, 2005 1:53 AM To: Nick Eberle; bob; tutor@python.org Subject: Re: [Tutor] new user question about while loops As Danny says, try breaking the problem into chunks and solving each bit separately. I'll provide a few comments on your code in the meantime but try the "evolving soluition" approach too. #assigning variables to track the amount of times heads or tails comes up heads=0 tails=1 AG> Why not make both zero, after all there have been no flips so far! flip=100 while flip < 100: AG> flip is never less than 100 because you set it to 100! AG> Thus you never enter the loop... flip -= 1 random.randrange(2) if flip < 100: break AG> And if you did after the first time through you make flip equal 99 AG> so that it will always exit the loop(break) here so it would only run once! AG> Try getting a while loop to run 100 times printing out the loop test value. AG> Or better stuill, since you know how many times you want the lopp to AG> run use a for loop instead: AG> for loop in range(100): AG> # loop code here print "\nThe amount of times tails came up was" , tails , "The amount of times heads came up was" , heads AG> But the only values you assign to head/tails are the initial 1 and 0. AG> Try Danny;'s suggestion of flipping the coin twice... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Global var problem
Hi Folks, messing about with classes I've come across something basic that I don't understand. Take this class class T: def p(self): print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs 1 Now this class T: def p(self): x += 1 print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs UnboundLocalError: local variable 'x' referenced before assignment So I tried this class T: def p(self): x += 1 print x if __name__ == '__main__': global x x = 1 t = T() t.p() but that gives me the same UnboundLocalError exception. This has got me confused. Why does the first example work ok, but not the second ? And in the third example I get the same error even after declaring x to be global. No doubt the answer is staring me in the face ... but I still can't see it. Cheers Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global var problem
Alan Gauld wrote: >> messing about with classes I've come across something basic that I >> don't understand. > > > As you say this has nothing to do with classes its more basic. Its > about namespaces. Try reading the namespaces topic in my tutor for > more info. > > Meanwhile lets simplify by removing the class bit > > > def h(): > global x > x += 1 > print x > > h() # prints 43 Many thanks to Alan, Andrei, Hugo and Welsey for helping me to understand where I was going wrong. I thought I understood namespaces but _obviously_ not . Thanks again, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new topic draft
> -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > Behalf Of Alan Gauld > > > I've just added an incomplete draft copy of my latest tutorial topic > on using the Operating System from Python. The material that's > there discusses the role of the OS and looks at file handling > usng os/os.path/shutil etc. > > http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm > > If anyone would like to take a look and provide feedback on > general direction/depth etc that'd be greatly appreciated. Thanks for that Alan. I always seem to get myself into difficulty with the os.walk routine, but you explained it brilliantly there. Have to admit, I couldn't be bothered to read the "So What is the Operating System" bit tho cos as you say on the page, we don't need to know it. Now if we were C programmers maybe .. :) Thanks again, Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor