From chaostorm at gmail.com Sat Sep 1 00:54:27 2012 From: chaostorm at gmail.com (Lazar) Date: Fri, 31 Aug 2012 15:54:27 -0700 Subject: [Tutor] Power of Two Function Message-ID: Hello, I'm fairly new to Python and still learning. Can someone please explain to me in what way the following function checks if a number is a power of two? Basically, the second line of code is what I can't really grasp: def is_power2(num): return num != 0 and ((num & (num - 1)) == 0) Thank you, Lazar From rdmoores at gmail.com Sat Sep 1 01:16:40 2012 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 31 Aug 2012 16:16:40 -0700 Subject: [Tutor] Problem caused by installing 2.7.3 In-Reply-To: References: Message-ID: On Fri, Aug 31, 2012 at 10:57 AM, eryksun wrote: > On Fri, Aug 31, 2012 at 12:49 PM, Richard D. Moores wrote: > https://bitbucket.org/vinay.sajip/pylauncher > https://bitbucket.org/vinay.sajip/pylauncher/raw/tip/Doc/launcher.rst Thank you! You solved my problem. Dick From visar.zejnullahu at gmail.com Sat Sep 1 01:17:04 2012 From: visar.zejnullahu at gmail.com (Visar Zejnullahu) Date: Sat, 1 Sep 2012 01:17:04 +0200 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: 2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you check if (num & (num - 1)) == 0. Visar Zejnullahu On Sat, Sep 1, 2012 at 12:54 AM, Lazar wrote: > Hello, > > I'm fairly new to Python and still learning. > > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) > > Thank you, > Lazar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From visar.zejnullahu at gmail.com Sat Sep 1 01:22:28 2012 From: visar.zejnullahu at gmail.com (Visar Zejnullahu) Date: Sat, 1 Sep 2012 01:22:28 +0200 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 You have many useful bit hacks here. Visar Zejnullahu On Sat, Sep 1, 2012 at 1:17 AM, Visar Zejnullahu wrote: > 2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So > if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you > check if (num & (num - 1)) == 0. > > Visar Zejnullahu > > > > On Sat, Sep 1, 2012 at 12:54 AM, Lazar wrote: > >> Hello, >> >> I'm fairly new to Python and still learning. >> >> Can someone please explain to me in what way the following function >> checks if a number is a power of two? Basically, the second line of >> code is what I can't really grasp: >> >> def is_power2(num): >> return num != 0 and ((num & (num - 1)) == 0) >> >> Thank you, >> Lazar >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Sep 1 01:30:42 2012 From: bgailer at gmail.com (bob gailer) Date: Fri, 31 Aug 2012 19:30:42 -0400 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: <50414922.3000206@gmail.com> On 8/31/2012 6:54 PM, Lazar wrote: > Hello, > > I'm fairly new to Python and still learning. > > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) A power of 2 in binary is (in general) one followed by zero-or-more zeroes. Thus 2 = 10 4 = 100 8 = 1000 The python manual informs us 5.4.1. Bit-string Operations on Integer Types Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2's complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation). x & y bitwise /and/ of /x/ and /y/ in other words & takes two bit strings, does a boolean and on pairs of bits. Thus 1100 & 1010 = 1000 (you get 1 only where the two bits are 1. for any /integer /n that is a power of 2, n-1 will be a string of all ones length one less than n. Thus given n = 4 (100), n-1 is 11. Attach a leading 0, perform the & and the result will be 0. Thus num & (num - 1)) == 0 will be one only for powers of 2. The function returns 1 or 0 which may be interpreted as True or False by the caller. Why the function does not ensure that its argument is of type int is a problem. HTH. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaostorm at gmail.com Sat Sep 1 01:45:47 2012 From: chaostorm at gmail.com (Lazar) Date: Fri, 31 Aug 2012 16:45:47 -0700 Subject: [Tutor] Power of Two Function In-Reply-To: <50414922.3000206@gmail.com> References: <50414922.3000206@gmail.com> Message-ID: Visar and Bob, Thank you for your detailed explanations, I appreciate your help. Kind regards, Lazar From breamoreboy at yahoo.co.uk Sat Sep 1 01:50:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Sep 2012 00:50:32 +0100 Subject: [Tutor] Problem caused by installing 2.7.3 In-Reply-To: References: Message-ID: On 01/09/2012 00:16, Richard D. Moores wrote: > On Fri, Aug 31, 2012 at 10:57 AM, eryksun wrote: >> On Fri, Aug 31, 2012 at 12:49 PM, Richard D. Moores wrote: > >> https://bitbucket.org/vinay.sajip/pylauncher > >> https://bitbucket.org/vinay.sajip/pylauncher/raw/tip/Doc/launcher.rst > > Thank you! You solved my problem. > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > For the record this is described in PEP 397 and forms part of the Python 3.3 release. -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Sat Sep 1 01:52:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Sep 2012 00:52:15 +0100 Subject: [Tutor] Power of Two Function In-Reply-To: References: Message-ID: On 31/08/12 23:54, Lazar wrote: > Can someone please explain to me in what way the following function > checks if a number is a power of two? Basically, the second line of > code is what I can't really grasp: > > def is_power2(num): > return num != 0 and ((num & (num - 1)) == 0) In binary any positive power of 2 looks like 1 followed by zeros: 10, 100, 1000 etc If you subtract 1 from any of those numbers you get a zero followed by all 1s: 01, 011, 0111 etc So if you bitwise and N and N-1 you get 1....0 & 0....1 ---------- 0....0 ie all zeros which equals the decimal number zero. So your function first checks that the argument is not zero if that is true then it evaluates the second part which as we've seen does equal zero for a power of two. Unfortunately it breaks down for fractions like 1/2, 1/4 etc which are negative powers of 2. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Sep 1 01:58:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Sep 2012 00:58:51 +0100 Subject: [Tutor] Using a calling program to change Python script arguments In-Reply-To: <504131EC.7010907@gmail.com> References: <5040EEE8.3020103@gmail.com> <504131EC.7010907@gmail.com> Message-ID: On 31/08/12 22:51, Ray Jones wrote: > Okay. Now I must figure out how to create the module and have my calling > script look in the right place.... ;) Creating a module is just a matter of creating a standard python file <--------start of myvar.py -----> #! /bin/python # you don't even really need a shebang for modules! myVar = 66 <-------- end of myvar.py ------> import myvar print myvar.myVal And so long as the location of the module is in your sys.path (or in the PYHONPATH environment variable) python will find it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Sep 1 02:20:42 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 01 Sep 2012 10:20:42 +1000 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> Message-ID: <504154DA.1070306@pearwood.info> On 31/08/12 18:31, Mark Lawrence wrote: > On 31/08/2012 04:27, William R. Wing (Bill Wing) wrote: >> >> How about - >> >>>>> for item in iter(list): >>>>> ?.print item > > Overengineering? :) A list is an iterator. Technically, no it isn't, it is an "iterable" or a "sequence" but not an iterator. py> mylist = [1, 2, 3] py> next(mylist) Traceback (most recent call last): File "", line 1, in TypeError: list object is not an iterator You are right to question the call to iter, it is redundant in this case, but your terminology is mixed up. There are three terms normally used to describe things that can be used in for-loops: Sequence The generalisation of lists, tuples and strings. Any object that has a known length where individual items can be retrieved with the __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... Iterator Any object that obeys the "iterator protocol", that is, it must have a method __iter__ which returns itself, and a method __next__ which returns the iterator items one at a time, then raises StopIteration when there are no more items. Examples of iterators include generator expressions, generators, the functions from the itertools module, and in Python 3, built-ins map, filter and zip. Iterable Any object which can be iterated over, that is, a sequence or iterator. The iter() built-in calls the object's __iter__ method. If the object is already an iterator, it returns itself unchanged. Since lists are not iterators, iter(list) returns a new iterator object: py> it = iter(mylist) py> it py> iter(it) is it True -- Steven From crawlzone at gmail.com Sat Sep 1 02:23:55 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 31 Aug 2012 17:23:55 -0700 Subject: [Tutor] Using a calling program to change Python script arguments In-Reply-To: References: <5040EEE8.3020103@gmail.com> <504131EC.7010907@gmail.com> Message-ID: <5041559B.2070804@gmail.com> On 08/31/2012 04:58 PM, Alan Gauld wrote: > > Creating a module is just a matter of creating a standard python file > > <--------start of myvar.py -----> > #! /bin/python # you don't even really need a shebang for modules! > myVar = 66 > <-------- end of myvar.py ------> > > import myvar > print myvar.myVal > > > And so long as the location of the module is in your sys.path > (or in the PYHONPATH environment variable) python will find it. Yep. I got my 'pymodules' directory created, and I will append it to the sys.path list a run time. So far it appears to work in testing mode....next we'll see what happens in real life! Thanks. Ray From etanes.rm at gmail.com Sat Sep 1 03:08:41 2012 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 31 Aug 2012 18:08:41 -0700 Subject: [Tutor] List all possible 10digit number Message-ID: First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like For I in range(1000000000, 9999999999): Print I Without crashing or throwing an exception. I've also tried to do something like I in range (100, 900): Etc And then concatenate the results but also to no avail. Again, any shoves in the right direction would be greatly appreciated. Scott From eryksun at gmail.com Sat Sep 1 03:46:33 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 31 Aug 2012 21:46:33 -0400 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: <504154DA.1070306@pearwood.info> References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> <504154DA.1070306@pearwood.info> Message-ID: On Fri, Aug 31, 2012 at 8:20 PM, Steven D'Aprano wrote: > > Sequence > The generalisation of lists, tuples and strings. Any object that has > a known length where individual items can be retrieved with the > __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... To expand on this, any object that has a __getitem__ method can be iterated over until it raises an IndexError, not just object's that have an __iter__ method, and __len__ is not a factor. For example: class Test(object): def __getitem__(self, n): if n > 4: raise IndexError return 'test' >>> list(Test()) ['test', 'test', 'test', 'test', 'test'] From d at davea.name Sat Sep 1 04:01:01 2012 From: d at davea.name (Dave Angel) Date: Fri, 31 Aug 2012 22:01:01 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: <50416C5D.1080101@davea.name> On 08/31/2012 09:08 PM, Scurvy Scott wrote: > First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. > > My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list > > List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like > > For I in range(1000000000, 9999999999): > Print I > > Without crashing or throwing an exception. > > I've also tried to do something like > > I in range (100, 900): > Etc > And then concatenate the results but also to no avail. > > Again, any shoves in the right direction would be greatly appreciated. > You should have mentioned that you're using Python 2.x. (Things are different in 3.x ) The range() function is the wrong answer, since 9 billion integers aren't going to fit in memory, on most machines. You should at least have tried xrange(). Unfortunately, it's limited to ints, which only go to a couple billion. That's probably why your assignment specifies 10 digits. The easy answer is to do a while loop that's equivalent to the xrange(). Initialize your counter to the smallest value you're interested in, and each time through the loop, print the counter and increment it. The loop should terminate when you pass the highest value of interest. The "right" answer is to write a generator, using yield to yield each value. Interestingly, it's the same loop as previous, but it yields instead of prints. Then, once you have the generator, you write a loop using it, rather than xrange. -- DaveA From eryksun at gmail.com Sat Sep 1 05:42:42 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 31 Aug 2012 23:42:42 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: On Fri, Aug 31, 2012 at 9:08 PM, Scurvy Scott wrote: > > My question is this- I've been trying for a month to generate a list of > all possible 10 digit numbers. I've googled, looked on stackoverflow, > experimented with itertools, In itertools, look at count() and islice(). An alternative to islice in this case is takewhile(). count() works with Python long integers. For example, counter = count(start=10**9L). islice() is limited to sys.maxint (sys.maxsize in Python 3), so you need to chain several together on a 32-bit platform (also 64-bit Windows, I gather, since a C long is always 32-bit on Windows). Use a generator expression with chain.from_iterable: counter = count(start=10**9L) slices = (islice(counter, 10**9) for i in range(10)) nums = chain.from_iterable(slices) Since printing performance is limited by the terminal's speed, you probably don't need the efficiency of islice (with its machine word size limit). Instead, you can use takewhile() with a pure Python predicate. For example: counter = count(start=10**9L) nums = takewhile(lambda x: x < 10**10, counter) From d at davea.name Sat Sep 1 07:00:10 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:00:10 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: <5041965A.60409@davea.name> On 08/31/2012 10:14 PM, Scurvy Scott wrote: > Thanks for the reply. This isn't an assignment per se as I'm just learning python for my own sake- not in classes or school or what have you. As I said I'm pretty new to python picking up whatever I can and generators are something that I haven't grasped. They're functions(kinda) that in some way deal with lists, tuples, or dict,(kinda?). I am probably wrong on this. Some clarification would be excellent. > > Thank you in advance and I apologize for being not so sharp sometimes. > > You seem plenty sharp enough to me. I do have to point out a couple of list etiquette points: 1) You top-posted. That means you put your message BEFORE the part you're quoting. Once a few replies go back and forth, this thoroughly scrambles the order, so you might as well delete all the context. 2) You replied privately to me. I've been participating in public forums like this for over 20 years, and the key word is "public." The only messages to send privately are thank-yous, and ones with personal information in them, such as passwords and such. Instead you should reply-all, and if your email is too broken to offer that, add the cc of tutor at python.org A simple generator could be def bigrange(start, end): i = start while i < end: yield i i += 1 The yield is a little like a return, in that the "caller" gets the value. But the function stack is kept active, and next time the loop needs a value, it resumes the same function. Control gets batted back and forth between the loop code and the generator code, until the generator finally returns. In this case it returns when it reaches the end value. So it'd be used like: for x in bigrange(100, 1000): print x I do hope you've been testing with smaller numbers than 10**10, to make sure the loops you write really do start and end with reasonable results. > I = 1000000000 > While I < 9999999999: > Print I > Is that more like it? -- Did you try running it? You never increment I, so it'll repeat forever on the one value. > I meant; > > I = 1000000000 > While I < 9999999999: > I += 1 > Print I > > > But that doesn't work. Want to explain what about it doesn't work? That phrase could mean that you got an error (post traceback), or it ran forever, or it displayed roman numerals. The only problem I see is it starts one-too-high. Fix that by swapping the last two lines. > Apologies for not mentioning I'm on 2.x.x I've seen so much about > avoiding 3.x I just thought it was assumed. And I've seen so much about avoiding 2.x that i figured 3.x would be assumed. Best to be explicit: python version, operating system, etc. DaveA From d at davea.name Sat Sep 1 07:14:14 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:14:14 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: <504199A6.3050900@davea.name> On 08/31/2012 10:38 PM, Scurvy Scott wrote: > Now I've got > > A = 1000000000 > I = raw_input("file name> ") > TheFile = open(I, 'w') > > TheFile.truncate > def allten(a): > while a < 9999999999: > a = + 1 > TheFile.write(a) > allten(a) > > The result is: > Open file 'file.txt', mode w at 0xb7331ee8 > Traceback line 13 etc.... > Top-posted again. You stop the traceback before showing anything interesting. i don't see 13 lines, so I have to totally guess which line is getting the error, and also what error it's getting. Paste the code and the traceback directly, and if that means you have to get email working on whatever machine you're running Python on, then do so. Retyping on your iphone isn't productive for anyone. There are a pile of typos in that code. Are they just because you retyped, or is that really what you tried? 1) TheFile.truncate doesn't call anything. The line is useless without parentheses. Of course, that doesn't matter much, since the open already truncated it. 2) allien(a) There's no such variable as 'a' defined. you do have one called A 3) write() takes a string. You're passing it an int or long. Convert with the str function, or other method, depending on what you really want. 4) Once you fix #2 and #3, the first value you write will be 10000001 That's off by one. As i said in my last message, you should swap the two lines. And once you do, you'll end one value too low. As I also said there, you should test the loop with smaller numbers. -- DaveA From dwightdhutto at gmail.com Sat Sep 1 07:20:38 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:20:38 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <50416C5D.1080101@davea.name> References: <50416C5D.1080101@davea.name> Message-ID: Dear Scurvy, I don't know if this has been suggested yet, but I just broke the larger list of 10 digit nums into segments, and at the end of the loop, kept the previous last num in the segment as the beginning of the next range() that goes through the same amount of ints in each segmentation of the larger list to iterate through. Except the next list of ints is starting where the last set segmentation of possible length int segments ends, and keeps iterating through all possible nums until it hits a match high_num. The following goes through 10,000 element lists until it hits a target high_num, which in this case is 1,000,000. def iterToHighNum(increment,high_num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: #print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Sep 1 07:20:55 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 1 Sep 2012 01:20:55 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: On Sat, Sep 1, 2012 at 12:29 AM, Scurvy Scott wrote: > > The while loop works for simply printing. Now I'm trying to save to a file > > I = 1000000000 > Boogers = raw_input("file") > Baseball = open(Boogers) As ASCII, that's 11 bytes per number times 9 billion numbers. That's approximately 92 GiB (about 21 DVD-5 discs). Are you sure you want to do that? Minor correction: >> counter = count(start=10**9L) >> slices = (islice(counter, 10**9) for i in range(10)) >> nums = chain.from_iterable(slices) That should have been range(9), not range(10). From dwightdhutto at gmail.com Sat Sep 1 07:24:14 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:24:14 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: You can also watch this happen by uncommenting print on line 8: def iterToHighNum(increment,high_ num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:26:39 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:26:39 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: I mean line 7. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:31:17 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:31:17 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <50416C5D.1080101@davea.name> Message-ID: It might be a little buggy, but I'm in a rush, so it has a flaw in it. But I think you get the point I'm trying to make. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 07:46:24 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 01:46:24 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: Here's the better function fixed with a return statement I forgot, but might not be as quick as the pre-built functions already shown: def iterToHighNum(increment,high_num): end_point = 0 a = [i for i in range(0,increment)] while (end_point != high_num) == True: for integer in a: if integer != high_num: print "no match, integer = %i" % (integer) end_point += 1 if end_point == high_num and integer != (high_num - 1): print 'match, integer = %i, high_num = %i' % (integer,high_num) return previous_increment = increment increment += increment a = [i for i in range(previous_increment,increment)] #instance increment = 10000 high_num = 1000000 iterToHighNum(increment,high_num) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Sep 1 07:55:49 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 01:55:49 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> Message-ID: <5041A365.207@davea.name> On 09/01/2012 01:46 AM, Dwight Hutto wrote: > Here's the better function fixed with a return statement I forgot, but > might not be as quick as the pre-built functions already shown: > > def iterToHighNum(increment,high_num): > end_point = 0 > a = [i for i in range(0,increment)] > while (end_point != high_num) == True: > for integer in a: > if integer != high_num: > print "no match, integer = %i" % (integer) > end_point += 1 > if end_point == high_num and integer != (high_num - 1): > print 'match, integer = %i, high_num = %i' % > (integer,high_num) > return > > previous_increment = increment > increment += increment > a = [i for i in range(previous_increment,increment)] > > #instance > increment = 10000 > high_num = 1000000 > iterToHighNum(increment,high_num) > > I'm not sure what the point of any of that is; you're making a simple problem complex. If you're wanting to accomplish the task without using any of the itertools stuff, why not just: current = 10**9 lim = 10**10 while current < lim: print current #or write to file, or whatever current += 1 -- DaveA From dwightdhutto at gmail.com Sat Sep 1 08:00:00 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 02:00:00 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041A365.207@davea.name> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> <5041A365.207@davea.name> Message-ID: I could comment this better. We have a function, iterToHighNum, that takes two parameters: increment and high_num. increment is how long the list of numbers being added to the old increment list of ints, to create a shorter int list that maintains the sequential count, looking for the high number you're trying to reach. I guess this is a benchmark thing, not sure, so if you comment out(#) the print 'no match' function in line 7, it will run quicker. end_point increments as a boolean, to match the high_num. When that happens, an if occurs, the match is printed, and the function returns to the instance caller. Use the other posters suggestions if they are better suited for you, however, I'd read what those functions do to give a more experienced lesson in how the 'experts' would code it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Sep 1 08:12:36 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sat, 1 Sep 2012 02:12:36 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041A365.207@davea.name> References: <2D406D29-6E6F-472D-B677-0C875ED37417@gmail.com> <5041A365.207@davea.name> Message-ID: I'm not sure what the point of any of that is; you're making a simple > problem complex. If you're wanting to accomplish the task without using > any of the itertools stuff, why not just: > > > current = 10**9 > lim = 10**10 > while current < lim: > print current #or write to file, or whatever > current += 1 > > Rough draft, in a hurry to try and help, and would have gotten a little more zen elegance if it were for a client. Plus the OP stated he needed a list. What's that list of ints for? Unless this is benchmarking, they might be in need of an unordered list of ints in which there are 10**9 different random values that need to have the proverbial needle(or 2, or 3) in a hey stack found. I thought there might be a reason, hopefully, other than trying to find the max range you could count to. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Sep 1 09:18:03 2012 From: d at davea.name (Dave Angel) Date: Sat, 01 Sep 2012 03:18:03 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: References: Message-ID: <5041B6AB.4090108@davea.name> On 08/31/2012 09:08 PM, Scurvy Scott wrote: > First of all thank you guys for all your help. The manual is really no substitute for having things explained in laymans terms as opposed to a technical manual. > > My question is this- I've been trying for a month to generate a list of all possible 10 digit numbers. I've googled, looked on stackoverflow, experimented with itertools, lists, etc to no avail. The closest I've gotten is using itertools to generate every possible arrangement of a list > > List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > I feel like I'm close but can't quite get it. Any suggestions or shoves in the right direction would be helpful. An issue I've encountered is that python won't do something like > > For I in range(1000000000, 9999999999): > Print I > > Without crashing or throwing an exception. > > I've also tried to do something like > > I in range (100, 900): > Etc > And then concatenate the results but also to no avail. > > Again, any shoves in the right direction would be greatly appreciated. > > Scott for i in xrange(start, end): print i Somehow i missed the point that xrange() is NOT necessarily limited to Python int values. So it may be usable on your machine, if your Python is 64bit. All I really know is that it works on mine (2.7 64bit, on Linux). See the following quote from http://docs.python.org/library/functions.html#xrange *CPython implementation detail:*xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (?short? Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using theitertools module:islice(count(start,step),(stop-start+step-1+2*(step<0))//step). Anyway, if you're not sure that xrange() will work for your particular range of values, then use current = 10**9 lim = 10**10 while current < lim: print current #or write to file, or whatever current += 1 or use the combination of islice and count listed above. -- DaveA From breamoreboy at yahoo.co.uk Sat Sep 1 10:52:10 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Sep 2012 09:52:10 +0100 Subject: [Tutor] Tutor Digest, Vol 102, Issue 98 In-Reply-To: <504154DA.1070306@pearwood.info> References: <49870031-CAF9-4D91-9E15-D8ECF11FEFC9@gmail.com> <504154DA.1070306@pearwood.info> Message-ID: On 01/09/2012 01:20, Steven D'Aprano wrote: > On 31/08/12 18:31, Mark Lawrence wrote: >> On 31/08/2012 04:27, William R. Wing (Bill Wing) wrote: >>> >>> How about - >>> >>>>>> for item in iter(list): >>>>>> ?.print item >> >> Overengineering? :) A list is an iterator. > > > Technically, no it isn't, it is an "iterable" or a "sequence" but > not an iterator. > > py> mylist = [1, 2, 3] > py> next(mylist) > Traceback (most recent call last): > File "", line 1, in > TypeError: list object is not an iterator > > > > You are right to question the call to iter, it is redundant in this > case, but your terminology is mixed up. > > There are three terms normally used to describe things that can > be used in for-loops: > > Sequence > The generalisation of lists, tuples and strings. Any object that has > a known length where individual items can be retrieved with the > __getitem__ method called sequentially: obj[0], obj[1], obj[2], ... > > Iterator > Any object that obeys the "iterator protocol", that is, it must have > a method __iter__ which returns itself, and a method __next__ which > returns the iterator items one at a time, then raises StopIteration > when there are no more items. Examples of iterators include generator > expressions, generators, the functions from the itertools module, > and in Python 3, built-ins map, filter and zip. > > Iterable > Any object which can be iterated over, that is, a sequence or > iterator. > > > The iter() built-in calls the object's __iter__ method. If the object > is already an iterator, it returns itself unchanged. Since lists are > not iterators, iter(list) returns a new iterator object: > > py> it = iter(mylist) > py> it > > py> iter(it) is it > True > > > I thought that when I wrote it, but left it on the grounds that I was too lazy to look up the correct terminology and I figured you'd soon correct me :) -- Cheers. Mark Lawrence. From eryksun at gmail.com Sat Sep 1 11:08:50 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 1 Sep 2012 05:08:50 -0400 Subject: [Tutor] List all possible 10digit number In-Reply-To: <5041B6AB.4090108@davea.name> References: <5041B6AB.4090108@davea.name> Message-ID: On Sat, Sep 1, 2012 at 3:18 AM, Dave Angel wrote: > > Somehow i missed the point that xrange() is NOT necessarily limited to > Python int values. So it may be usable on your machine, if your Python > is 64bit. All I really know is that it works on mine (2.7 64bit, on > Linux). See the following quote Since xrange uses a C long type, it's limited to sys.maxint. On a 64-bit Linux system a C long is 64-bit. In Windows, a C long is always 32-bit, so I would suppose sys.maxint is 2**31 - 1 on both 32-bit and 64-bit systems. Someone running 64-bit Windows can confirm that. > islice(count(start,step),(stop-start+step-1+2*(step<0))//step) Or more commonly with step==1: islice(count(start), stop - start) This works so long as the 2nd argument is less than sys.maxsize. On my 32-bit system, that's limited to 2**31 - 1. So instead I decided to slice a billion numbers at a time and use chain.from_iterable() to chain several slices from a generator expression. Previously I thought it had to be less than sys.maxint. The error on my 32-bit Debian system said the value had to be <= maxint, so I assumed islice uses a C long type. But I looked in the itertoolsmodule.c source (2.7.3) and discovered that islice uses a C ssize_t. So the error should have said the size has to be <= maxsize. On a 64-bit platform that's 2**63 - 1, even on 64-bit Windows. Again, someone running 64-bit Windows can confirm that. From wayne at waynewerner.com Sat Sep 1 14:54:56 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 1 Sep 2012 07:54:56 -0500 (CDT) Subject: [Tutor] Why begin a function name with an underscore In-Reply-To: <503E4526.2050408@pearwood.info> References: <503E4526.2050408@pearwood.info> Message-ID: On Thu, 30 Aug 2012, Steven D'Aprano wrote: > On 28/08/12 21:24, Wayne Werner wrote: >> On Mon, 27 Aug 2012, Richard D. Moores wrote: > >>> What the best way to test if something's an integer? >> >> try: >> whatever_you_want(supposed_integer) >> except ValueError: >> print("Oops, that wasn't an integer! Please try again") >> >> That's usually the best way... > > Actually, that's close to the worst way, since you take a nice, useful > exception which prints a traceback showing exactly what went wrong, and > replace it with a pointless, silly message which can't be caught by the > caller. > > Trying again may be impossible, or inappropriate, and certainly isn't > up to the function to make that decision, that's up to the caller to > decide what is the appropriate response to invalid data. I suppose I should've replaced the print() call with # Whatever recovery/handling code you need here My intention was to remove the bit about checking for an integer away from the spot that was checking it, out into an exception handler where it belongs. I was also under the (mistaken?) impression that the use case was an interactive type call, and used something like: supposed_integer = raw_input("Please enter an integer: ") # exception handling here But yes, if you're writing code that is meant to be called by someone else then that code is horrible, and exactly the wrong pattern to follow. -Wayne From wayne at waynewerner.com Sat Sep 1 15:14:53 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 1 Sep 2012 08:14:53 -0500 (CDT) Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Thu, 30 Aug 2012, Abhishek Pratap wrote: > Hi Guys > > I have a with few million lines. I want to process each block of 8 > lines and from my estimate my job is not IO bound. In other words it > takes a lot more time to do the computation than it would take for > simply reading the file. > > I am wondering how can I go about reading data from this at a faster > pace and then farm out the jobs to worker function using > multiprocessing module. > > I can think of two ways. > > 1. split the split and read it in parallel(dint work well for me ) > primarily because I dont know how to read a file in parallel > efficiently. > 2. keep reading the file sequentially into a buffer of some size and > farm out a chunks of the data through multiprocessing. As other folks have mentioned, having at least your general algorithm available would make things a lot better. But here's another way that you could iterate over the file if you know exactly how many you have available (or at least a number that it's divisible by): with open('inputfile') as f: for line1, line2, line3, line4 in zip(f,f,f,f): # do your processing here The caveat to this is that if your lines aren't evenly divisible by 4 then you'll loose the last count % 4 lines. The reason that this can work is because zip() combines several sequences and returns a new iterator. In this case it's combining the file handles f, which are themselves iterators. So each successive call to next() - i.e. pass through the for loop - next() is successively called on f. The problem of course is that when you reach the end of the file - say your last pass through and you've only got one line left. Well, when zip's iterator calls next on the first f, that returns the last line. But since f is now at the end of the file, calling next on it will raise StopIteration, which will end your loop without actually processing anything on the inside! So, this probably isn't the best way to handle your issue, but maybe it is! HTH, Wayne From mjolewis at gmail.com Sun Sep 2 05:29:35 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 1 Sep 2012 20:29:35 -0700 Subject: [Tutor] Running a script in the background Message-ID: Hi everyone, I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. Thanks! -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From dalupus at gmail.com Sun Sep 2 05:38:41 2012 From: dalupus at gmail.com (Michael Crawford) Date: Sat, 1 Sep 2012 23:38:41 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> For windows not sure but for osx just add an & after the command. python myscript.py & On Sep 1, 2012, at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. > > I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. > > Thanks! > > -- > Michael J. Lewis > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mjolewis at gmail.com Sun Sep 2 06:00:07 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sat, 1 Sep 2012 21:00:07 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: > For windows not sure but for osx just add an & after the command. > > python myscript.py & > Thanks, but I know about that. I should have been more clear. What I want to do is have the script run in the background without even seeing the terminal. Adding the & after the command will let do other things, but the terminal still needs to be open. Once the program is running, I don't want either the terminal or the interpreter displayed. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From illusiontechniques at gmail.com Sun Sep 2 06:12:37 2012 From: illusiontechniques at gmail.com (c smith) Date: Sun, 2 Sep 2012 00:12:37 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: You are thinking of && & is what you want -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sun Sep 2 06:28:25 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 2 Sep 2012 00:28:25 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: On Sat, Sep 1, 2012 at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding > the subject, but I've spent the past two days trying to figure this out and > I don't get it. > > I have a script that will run forever > Forever is a very loose term. > . Since it runs forever, I don't want to see the interpreter or command > line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every > x minutes to see if any files have been updated and then moves them to > dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If > need be, I can create two separate scripts to separate out the two OS's. > > I haven't tested this yet. I was about to use this instead of a cron job for autoresponders. In my limited knowledge in this area, I'd think that calling the script in startup/boot like this describes: http://embraceubuntu.com/2005/09/07/adding-a-startup-script-to-be-run-at-bootup/ might help. Or maybe a tkinter/wxpython app, that hides itself continuously, buit there might still be a launched icon on the app bar your OS should have. I haven't used OSX Mountain Lion, yet. I like looking at different OS setups. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sun Sep 2 06:35:52 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Sun, 2 Sep 2012 00:35:52 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: Here's a little more reading for you, found under google search term 'no terminal python script' http://stackoverflow.com/questions/2338951/how-can-i-run-a-py2exe-program-in-windows-without-the-terminal http://ginstrom.com/scribbles/2007/09/12/running-a-python-script-on-windows-without-the-console/ > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Sun Sep 2 07:44:48 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sat, 01 Sep 2012 22:44:48 -0700 Subject: [Tutor] 2.7.3 generator objects Message-ID: <5042F250.4070200@gmail.com> I was playing with os.walk today. I can use os.walk in a for loop (does that make it an iterator or just an irritable? ^_^), but if I assign os.walk to 'test' (test = os.walk()), that variable becomes a generator object that does not work in a for loop. From what I can tell, it's supposed to work in a generator function using 'yield', but I'm at a loss at how that all works. I suppose I should just stick with using the os.walk in the for loop, but I'd like to make sense of the whole thing. Please someone explain this to me? Thanks. Ray From eryksun at gmail.com Sun Sep 2 07:48:31 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 01:48:31 -0400 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Sat, Sep 1, 2012 at 9:14 AM, Wayne Werner wrote: > > with open('inputfile') as f: > for line1, line2, line3, line4 in zip(f,f,f,f): > # do your processing here Use itertools.izip_longest (zip_longest in 3.x) for this. Items in the final batch are set to fillvalue (defaults to None) if the iterator has reached the end of the file. Below I've included a template that uses a multiprocessing.Pool, but only if there are cores available. On a single-core system it falls back to using itertools.imap (use built-in map in 3.x). from multiprocessing import Pool, cpu_count from itertools import izip_longest, imap FILE_IN = '...' FILE_OUT = '...' NLINES = 1000000 # estimate this for a good chunk_size BATCH_SIZE = 8 def func(batch): """ test func """ import os, time time.sleep(0.001) return "%d: %s\n" % (os.getpid(), repr(batch)) if __name__ == '__main__': # <-- required for Windows file_in, file_out = open(FILE_IN), open(FILE_OUT, 'w') nworkers = cpu_count() - 1 with file_in, file_out: batches = izip_longest(* [file_in] * BATCH_SIZE) if nworkers > 0: pool = Pool(nworkers) chunk_size = NLINES // BATCH_SIZE // nworkers result = pool.imap(func, batches, chunk_size) else: result = imap(func, batches) file_out.writelines(result) From alan.gauld at btinternet.com Sun Sep 2 08:34:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:34:05 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: On 02/09/12 04:29, Michael Lewis wrote: > I have a script that will run forever. Since it runs forever, I don't > want to see the interpreter or command line. I want the program to run > in the background so I don't see it at all. That's an OS thing not a Python thing. On Unix it means adding an entry in the startup scripts. For an old BSD type like me that was one of the init scripts in the /etc tree but nowadays there are different mechanisms, and I'm especially unclear on how MacOS/Darwin starts up. You'll need to do some Googling. On windows you can just put it into the Run registry entry under the appropriate key. Again search the Microsoft help system for the answers. > How can I do this? For some background, my script essentially check > every x minutes to see if any files have been updated and then moves > them to dropbox. In that case using a long running Python script is probably the wrong answer. You would be better with a short running, do it once, script that the OS launches regularly. Look at 'cron' on *nix and 'at' on Windows. That will be less resource hungry, there is no point in having running programs that do nothing for most of the time. > ... I can create two separate scripts to separate out the two OS's. One of the beauties of Python is that you rarely need separate scripts. Put the file location(s) in a config file and the same script will work for both. Only the startup mechanism will differ. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 2 08:39:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:39:28 +0100 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5042F250.4070200@gmail.com> References: <5042F250.4070200@gmail.com> Message-ID: On 02/09/12 06:44, Ray Jones wrote: > I was playing with os.walk today. I can use os.walk in a for loop (does > that make it an iterator or just an irritable? ^_^), but if I assign > os.walk to 'test' (test = os.walk()), that variable becomes a > generator object that does not work in a for loop. It does for me.... >>> home = os.walk('/home/alang/src/Python') >>> for root,dirs,files in home: ... print root ... /home/alang/src/Python /home/alang/src/Python/modcopy /home/alang/src/Python/modcopy/src >>> What happened when you tried? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 2 08:41:51 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 07:41:51 +0100 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On 02/09/12 06:48, eryksun wrote: > > from multiprocessing import Pool, cpu_count > from itertools import izip_longest, imap > > FILE_IN = '...' > FILE_OUT = '...' > > NLINES = 1000000 # estimate this for a good chunk_size > BATCH_SIZE = 8 > > def func(batch): > """ test func """ > import os, time > time.sleep(0.001) > return "%d: %s\n" % (os.getpid(), repr(batch)) > > if __name__ == '__main__': # <-- required for Windows Why? What difference does that make in Windows? > file_in, file_out = open(FILE_IN), open(FILE_OUT, 'w') > nworkers = cpu_count() - 1 > > with file_in, file_out: > batches = izip_longest(* [file_in] * BATCH_SIZE) > if nworkers > 0: > pool = Pool(nworkers) > chunk_size = NLINES // BATCH_SIZE // nworkers > result = pool.imap(func, batches, chunk_size) > else: > result = imap(func, batches) > file_out.writelines(result) just curious. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Sun Sep 2 08:55:15 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sat, 01 Sep 2012 23:55:15 -0700 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: References: <5042F250.4070200@gmail.com> Message-ID: <504302D3.6060600@gmail.com> On 09/01/2012 11:39 PM, Alan Gauld wrote: > On 02/09/12 06:44, Ray Jones wrote: >> I was playing with os.walk today. I can use os.walk in a for loop (does >> that make it an iterator or just an irritable? ^_^), but if I assign >> os.walk to 'test' (test = os.walk()), that variable becomes a >> generator object that does not work in a for loop. > > > It does for me.... > > >>> home = os.walk('/home/alang/src/Python') > >>> for root,dirs,files in home: > ... print root > ... > /home/alang/src/Python > /home/alang/src/Python/modcopy > /home/alang/src/Python/modcopy/src > >>> > > What happened when you tried? I'll be dipped. It worked - the first time, anyway. It wouldn't go a second round. Don't I have to reset the object somehow? When I originally tried it, I placed print root print dirs print files within the for loop, and I ended up with nuthin'. Or perhaps it flashed by while I wasn't watching, and it wouldn't do it a second time??? Ray From eryksun at gmail.com Sun Sep 2 08:57:09 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 02:57:09 -0400 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5042F250.4070200@gmail.com> References: <5042F250.4070200@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 1:44 AM, Ray Jones wrote: > > I was playing with os.walk today. I can use os.walk in a for loop (does > that make it an iterator or just an irritable? ^_^), The output from os.walk is a generator, which is an iterator. os.walk actually calls itself recursively, creating a chain of generators. Take a look: print inspect.getsource(os.walk) > os.walk to 'test' (test = os.walk()), that variable becomes a > generator object that does not work in a for loop. You'll have to provide more information. That should work fine if you haven't already exhausted the generator. > it's supposed to work in a generator function using 'yield', but I'm at > a loss at how that all works. > > I suppose I should just stick with using the os.walk in the for loop, > but I'd like to make sense of the whole thing. Please someone explain > this to me? A generator function is a function that uses the keyword "yield" instead of "return" (an empty return statement is allowed). When you call a generator function, the return value is a generator object. Think of the generator function as a factory for generator objects. A return in the generator function (implicit or with a "return" statement) corresponds to the generator object raising StopIteration. A generator object is an iterator. Specifically, it has the methods __iter__ and "next" (in 3.x it's __next__), and "iter(genobject) is genobject". To be an iterable in general, it suffices to have either an __iter__ method or a __getitem__ method. Here are the glossary definitions: http://docs.python.org/glossary.html#term-iterable http://docs.python.org/glossary.html#term-iterator Also, here is the PEP for simple generators: http://www.python.org/dev/peps/pep-0255/ From crawlzone at gmail.com Sun Sep 2 09:09:51 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 00:09:51 -0700 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: References: <5042F250.4070200@gmail.com> Message-ID: <5043063F.7010404@gmail.com> On 09/01/2012 11:57 PM, eryksun wrote: > To be an iterable in general, it suffices to have either an __iter__ > method or a __getitem__ method. Here are the glossary definitions: > http://docs.python.org/glossary.html#term-iterable > http://docs.python.org/glossary.html#term-iterator After a few times re-reading, I'm beginning to get a glimmer.... > Also, here is the PEP for simple generators: > http://www.python.org/dev/peps/pep-0255/ ....but this is complete Greek! ;) But didn't I read somewhere that you can reset an iterator to go through the whole process again? Ray From eryksun at gmail.com Sun Sep 2 09:16:26 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 03:16:26 -0400 Subject: [Tutor] using multiprocessing efficiently to process large data file In-Reply-To: References: Message-ID: On Sun, Sep 2, 2012 at 2:41 AM, Alan Gauld wrote: > >> if __name__ == '__main__': # <-- required for Windows > > Why? > What difference does that make in Windows? It's a hack to get around the fact that Win32 doesn't fork(). Windows calls CreateProcess(), which loads a fresh interpreter. multiprocessing then loads the module under a different name (i.e. not '__main__'). Otherwise another processing Pool would be created, etc, etc. This is also why you can't share global data in Windows. A forked process in Linux uses copy on write, so you can load a large block of data before calling fork() and share it. In Windows the module is executed separately for each process, so each has its own copy. To share data in Windows, I think the fastest option is to use a ctypes shared Array. The example I wrote is just using the default Pool setup that serializes (pickle) over pipes. FYI, the Win32 API imposes the requirement to use CreateProcess(). The native NT kernel has no problem forking (e.g. for the POSIX subsystem). I haven't looked closely enough to know why they didn't implement fork() in Win32. From eryksun at gmail.com Sun Sep 2 09:34:21 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 03:34:21 -0400 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5043063F.7010404@gmail.com> References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 3:09 AM, Ray Jones wrote: > > But didn't I read somewhere that you can reset an iterator to go through > the whole process again? You could implement that ability in your own objects, but it's not part of the protocol. I forgot to mention generator expressions. This is an expression (typically requiring parentheses) that evaluates to a generator object. You can omit the parentheses if it's the only argument in a call. For example: >>> g = (chr(i) for i in range(65, 69)) >>> ", ".join(g) 'A, B, C, D' >>> ", ".join(chr(i) for i in range(65, 69)) 'A, B, C, D' http://docs.python.org/glossary.html#generator%20expression From steve at pearwood.info Sun Sep 2 12:05:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 02 Sep 2012 20:05:40 +1000 Subject: [Tutor] 2.7.3 generator objects In-Reply-To: <5043063F.7010404@gmail.com> References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> Message-ID: <50432F74.3030905@pearwood.info> On 02/09/12 17:09, Ray Jones wrote: > But didn't I read somewhere that you can reset an iterator to go through > the whole process again? In general, no. The usual way to "reset" an iterator is to re-create it. walker = os.walk("/home/steve/start") # ... process files in walker walker = os.walk("/home/steve/start") # ... and process them again -- Steven From fomcl at yahoo.com Sun Sep 2 13:30:45 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 2 Sep 2012 04:30:45 -0700 (PDT) Subject: [Tutor] making len() and __len__ return a non-int Message-ID: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Hi, ? If I implement __len__ in my own class, does it really have to return an int? Is there no way around this (other than modifying the source code of python itself ;-) It would be nice if len(Example(row, col)) would return a dictionary, or a two-tuple (see code below). The strange thing is that calling __len__ directly does work: Example(1, 2).__len__() returns the dictionary. I always thought len() was a convenient "shorthand" for __len__. I've even been reading about metaclasses (interesting, dark, mysterious), thinking the answer might lie there. Note that my question is not whether it's a good idea to do this, I just find it interesting to understand how it could be done. ? Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 >>> class Example(object): ?def __init__(self, row, col): ??self.row = row ??self.col = col ?def __len__(self): ??return {self.row: self.col} ?>>> len(Example(1, 2)) Traceback (most recent call last): ? File "", line 1, in ??? len(Example(1, 2)) TypeError: an integer is required >>> Example(1, 2).__len__() {1: 2} Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Sep 2 13:31:31 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Sep 2012 13:31:31 +0200 Subject: [Tutor] 2.7.3 generator objects References: <5042F250.4070200@gmail.com> <5043063F.7010404@gmail.com> <50432F74.3030905@pearwood.info> Message-ID: Steven D'Aprano wrote: > On 02/09/12 17:09, Ray Jones wrote: > >> But didn't I read somewhere that you can reset an iterator to go through >> the whole process again? > > In general, no. > > The usual way to "reset" an iterator is to re-create it. > > > walker = os.walk("/home/steve/start") > # ... process files in walker > walker = os.walk("/home/steve/start") > # ... and process them again Python doesn't enforce this behaviour for iterators in general, but it is part of the spec: """ - Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators). Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration. """ See http://www.python.org/dev/peps/pep-0234/ For illustration purposes here's a non-compliant iterator: WRONG: >>> class Iterator: ... def __init__(self, max, factor=2): ... self.max = max ... self.factor = factor ... self.value = 1 ... def __iter__(self): ... return self ... def __next__(self): ... result = self.value ... if result >= self.max: ... raise StopIteration ... self.value *= self.factor ... return result ... def reset(self): ... self.value = 1 ... >>> it = Iterator(8) >>> next(it) 1 >>> next(it) 2 >>> next(it) 4 >>> next(it) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration >>> next(it) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration >>> it.reset() >>> next(it) 1 >>> next(it) 2 BETTER (Iterator is the same as above, without* the reset() method): >>> class Iterable: ... def __init__(self, max, factor=2): ... self.max = max ... self.factor = factor ... def __iter__(self): ... return Iterator(self.max, self.factor) ... >>> it = Iterable(8) >>> next(it) Traceback (most recent call last): File "", line 1, in TypeError: 'Iterable' object is not an iterator >>> x = iter(it) >>> next(x) 1 >>> next(x) 2 >>> next(x) 4 >>> next(x) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration Now instead of resetting the iterator ask the iterable for a new iterator: >>> x = iter(it) >>> next(x) 1 >>> next(x) 2 >>> next(x) 4 >>> next(x) Traceback (most recent call last): File "", line 1, in File "", line 11, in __next__ StopIteration (*) Of course I cheated and left it in ;) PS: Since the advent of generators people usually write def g(max, factor=2): value = 1 while value < max: yield value value *= factor They're all lazy bastards... PPS: 'max' should rather be called 'stop' since it indicates the upper bound of a half-open interval. From __peter__ at web.de Sun Sep 2 14:36:49 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Sep 2012 14:36:49 +0200 Subject: [Tutor] making len() and __len__ return a non-int References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > If I implement __len__ in my own class, does it really have to return an > int? Is there no way around this (other than modifying the source code of > python itself ;-) It would be nice if len(Example(row, col)) would return > a dictionary, or a two-tuple (see code below). The strange thing is that > calling __len__ directly does work: Example(1, 2).__len__() returns the > dictionary. I always thought len() was a convenient "shorthand" for > __len__. I've even been reading about metaclasses (interesting, dark, > mysterious), thinking the answer might lie there. Note that my question is > not whether it's a good idea to do this, Ah, you already know it's a bad idea... > I just find it interesting to understand how it could be done. It cannot be done without modifying the source. Here's the implementation of len() in Python 3.3: static PyObject * builtin_len(PyObject *self, PyObject *v) { Py_ssize_t res; res = PyObject_Size(v); if (res < 0 && PyErr_Occurred()) return NULL; return PyLong_FromSsize_t(res); } I did not successfully drill down further, but you can see that it may signal an error or return a Python long (which I think is the same as a Python int in 3.x) and that the underlying code operates on Py_size_t, so you'd have to modify that code, too. Py_ssize_t is implementation dependent -- on my 64-bit Linux valid lengths are in range(0, 2**63): >>> class A: ... def __len__(self): return self._len ... def __init__(self, len): ... self._len = len ... >>> len(A(-1)) Traceback (most recent call last): File "", line 1, in ValueError: __len__() should return >= 0 >>> len(A(2**63)) Traceback (most recent call last): File "", line 1, in OverflowError: cannot fit 'int' into an index-sized integer >>> len(A(2**63-1)) 9223372036854775807 From wprins at gmail.com Sun Sep 2 16:06:41 2012 From: wprins at gmail.com (Walter Prins) Date: Sun, 2 Sep 2012 15:06:41 +0100 Subject: [Tutor] Fwd: Running a script in the background In-Reply-To: References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: forwarding accidental reply to person only ---------- Forwarded message ---------- From: Walter Prins Date: 2 September 2012 15:05 Subject: Re: [Tutor] Running a script in the background To: Michael Lewis On 2 September 2012 05:00, Michael Lewis wrote: > >> For windows not sure but for osx just add an & after the command. >> >> python myscript.py & > > > Thanks, but I know about that. I should have been more clear. What I want to > do is have the script run in the background without even seeing the > terminal. Adding the & after the command will let do other things, but the > terminal still needs to be open. Once the program is running, I don't want > either the terminal or the interpreter displayed. try: nohup python myscript.py & Then you can close the terminal afterwards. "nohup" means"no hangup". It tells the system that the python process launched as a result of this command should not be terminated when its parent shell is terminated. You can also put the above command in a shell script and run the script directly via whatever method suits you best. (Launcher, scheduled job, login script etc.) Walter -- Walter Prins Trendata Solutions Limited 26 Kirfield Drive, Hinckley, Leicestershire, LE10 1SX Tel: 01455 635 994 (fax/landline) 077 8713 1543 (mobile) Email: info at trendatasolutions.ltd.uk Registered Office: 8 Emmanuel Court, 10 Mill Street, Birmingham, B72 1TJ Company registered in England No: 07364060 VAT No: 998 3569 37 From fomcl at yahoo.com Sun Sep 2 21:06:38 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 2 Sep 2012 12:06:38 -0700 (PDT) Subject: [Tutor] making len() and __len__ return a non-int In-Reply-To: References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> Albert-Jan Roskam wrote: > >> If I implement __len__ in my own class, does it really have to return an >> int? Is there no way around this (other than modifying the source code of >> python itself ;-) It would be nice if len(Example(row, col)) would return >> a dictionary, or a two-tuple (see code below). The strange thing is that >> calling __len__ directly does work: Example(1, 2).__len__() returns the >> dictionary. I always thought len() was a convenient "shorthand" for >> __len__. I've even been reading about metaclasses (interesting, dark, >> mysterious), thinking the answer might lie there. Note that my question is >> not whether it's a good idea to do this, > >Ah, you already know it's a bad idea... > >> I just find it interesting to understand how it could be done. > >It cannot be done without modifying the source. > >Here's the implementation of len() in Python 3.3: > >static PyObject * >builtin_len(PyObject *self, PyObject *v) >{ >? ? Py_ssize_t res; > >? ? res = PyObject_Size(v); >? ? if (res < 0 && PyErr_Occurred()) >? ? ? ? return NULL; >? ? return PyLong_FromSsize_t(res); >} > >===> aha. So if I do len(Example(1, 2)) the C function "builtin_len" will be called, whereas if I formulate it like Example(1, 2).__len__(), only the __len__ special method of my own bogus class will be called. Interesting. I was already checking if I could find __builtin__.__len__, but that's not possible, probably because they're all compiled. > >Thanks for your help! > >I did not successfully drill down further, but you can see that it may >signal an error or return a Python long (which I think is the same as a >Python int in 3.x) and that the underlying code operates on Py_size_t, so >you'd have to modify that code, too. Py_ssize_t is implementation dependent >-- on my 64-bit Linux valid lengths are in range(0, 2**63): > >>>> class A: >...? ? def __len__(self): return self._len >...? ? def __init__(self, len): >...? ? ? ? ? ? self._len = len >... >>>> len(A(-1)) >Traceback (most recent call last): >? File "", line 1, in >ValueError: __len__() should return >= 0 >>>> len(A(2**63)) >Traceback (most recent call last): >? File "", line 1, in >OverflowError: cannot fit 'int' into an index-sized integer >>>> len(A(2**63-1)) >9223372036854775807 > > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > ________________________________ From: Peter Otten <__peter__ at web.de> To: tutor at python.org Sent: Sunday, September 2, 2012 2:36 PM Subject: Re: [Tutor] making len() and __len__ return a non-int -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Sep 2 21:30:02 2012 From: d at davea.name (Dave Angel) Date: Sun, 02 Sep 2012 15:30:02 -0400 Subject: [Tutor] making len() and __len__ return a non-int In-Reply-To: <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> References: <1346585445.62145.YahooMailNeo@web110714.mail.gq1.yahoo.com> <1346612798.95412.YahooMailNeo@web110716.mail.gq1.yahoo.com> Message-ID: <5043B3BA.2070507@davea.name> On 09/02/2012 03:06 PM, Albert-Jan Roskam wrote: > Albert-Jan Roskam wrote: > If you're not going to put anything of your own into the reply message, please delete all the context you're not responding to, and then delete the message instead of sending. On the other hand, if the message actually had some content, please observe convention, and let us actually find it. Your reply should follow the parts you're quoting, and those parts should have attribution, and the > indentation at the beginning of the line should be consistent with whichever attribution it matches. New stuff should be at the left margin, without > symbol. In other words, use a decent email program, and use an before and after the stuff you type. -- DaveA From wrw at mac.com Sun Sep 2 22:30:13 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 16:30:13 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: Message-ID: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> On Sep 1, 2012, at 11:29 PM, Michael Lewis wrote: > Hi everyone, > > I am sorry to ask this when there are a lot of resources online regarding the subject, but I've spent the past two days trying to figure this out and I don't get it. > > I have a script that will run forever. Since it runs forever, I don't want to see the interpreter or command line. I want the program to run in the background so I don't see it at all. > > How can I do this? For some background, my script essentially check every x minutes to see if any files have been updated and then moves them to dropbox. > > I want to be able to do this on both OSX Mountain Lion and Windows 7. If need be, I can create two separate scripts to separate out the two OS's. > > Thanks! > > -- > Michael J. Lewis Michael, I see you have several Windows answers, but it doesn't look as though you found quite what you were hoping for on OSX. My suggestion would be to take the script and run it through py2app, which will turn it into a stand-alone application which can then be added to your list of StartUp or LogIn applications. If you never request input or produce output, it will quite happily run in the background with no window and no menu (although by default there will be an icon in the dock). At that point it is so much a background application that the ONLY way you can quit it is via the Force Quit dialog. If you generate status or housekeeping print messages, they will show up in ~/Library/Logfiles. Py2app isn't particularly memory efficient, even a minimal application tends to run close to 9-10 Mbytes, but if it spends most of its time sleeping, it will use very little in the way of system resources. If you want it to run even when you aren't logged in, you will have to go to a bit more trouble. You will have to make up an installer plist file and use launchctl to add it to the list of stuff under control of the launchd daemon. Good luck, Bill From eryksun at gmail.com Sun Sep 2 23:04:38 2012 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Sep 2012 17:04:38 -0400 Subject: [Tutor] Fwd: Running a script in the background In-Reply-To: References: <8B7E35ED-A019-40A3-B95B-0CC053B05CAD@gmail.com> Message-ID: On Sun, Sep 2, 2012 at 10:06 AM, Walter Prins wrote: > > nohup python myscript.py & > > Then you can close the terminal afterwards. "nohup" means"no hangup". > It tells the system that the python process launched as a result of > this command should not be terminated when its parent shell is > terminated. bash starts a background process in a new group. When you close the terminal (SIGHUP), the OS won't forward the HUP to this group, but bash defaults to forwarding it. If you "exit", on the other hand, bash won't be around to forward anything. To skip forwarding HUP in any case, just "disown" the process. If you use nohup, you can avoid creating nohup.out files if you redirect stdout somewhere such as a log file or /dev/null. If instead you just "exit" or use "disown", remember to redirect both stdout and stderr so the program doesn't try to write to a non-existent tty. From mjolewis at gmail.com Sun Sep 2 23:06:03 2012 From: mjolewis at gmail.com (Michael Lewis) Date: Sun, 2 Sep 2012 14:06:03 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> Message-ID: > > > > Michael, I see you have several Windows answers, but it doesn't look as > though you found quite what you were hoping for on OSX. My suggestion > would be to take the script and run it through py2app, which will turn it > into a stand-alone application which can then be added to your list of > StartUp or LogIn applications. If you never request input or produce > output, it will quite happily run in the background with no window and no > menu (although by default there will be an icon in the dock). At that > point it is so much a background application that the ONLY way you can quit > it is via the Force Quit dialog. If you generate status or housekeeping > print messages, they will show up in ~/Library/Logfiles. Py2app isn't > particularly memory efficient, even a minimal application tends to run > close to 9-10 Mbytes, but if it spends most of its time sleeping, it will > use very little in the way of system resources. > > Good luck, > Bill > Thanks, Bill. That is definitely more of what I am looking for and actually found that through some googling. What I am confused about now, is what's really the difference between py2app and the python Build Applet? -- Michael J. Lewis -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Sun Sep 2 23:32:56 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 17:32:56 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> Message-ID: <899AE6F6-8D7B-4F03-9CD7-0C3EAF92FA37@mac.com> On Sep 2, 2012, at 5:06 PM, Michael Lewis wrote: > > > Michael, I see you have several Windows answers, but it doesn't look as though you found quite what you were hoping for on OSX. My suggestion would be to take the script and run it through py2app, which will turn it into a stand-alone application which can then be added to your list of StartUp or LogIn applications. If you never request input or produce output, it will quite happily run in the background with no window and no menu (although by default there will be an icon in the dock). At that point it is so much a background application that the ONLY way you can quit it is via the Force Quit dialog. If you generate status or housekeeping print messages, they will show up in ~/Library/Logfiles. Py2app isn't particularly memory efficient, even a minimal application tends to run close to 9-10 Mbytes, but if it spends most of its time sleeping, it will use very little in the way of system resources. > > Good luck, > Bill > > Thanks, Bill. That is definitely more of what I am looking for and actually found that through some googling. What I am confused about now, is what's really the difference between py2app and the python Build Applet? > -- > Michael J. Lewis I've never played with Build Applet, only py2app, so this may be partially or totally bogus, but py2app uses a fairly elaborate "setup" script that allows you to specify things like a custom icon (if you want one) as well as specific libraries. Build Applet, on the other hand, is a much simpler tool that takes a single source file, pulls in any "includes" it finds and builds a default. It might in fact be sufficient for your needs. If you've downloaded the python from python.org, you will definitely find both the Build Applet and PythonLauncher in a PythonXX folder in your Applications folder. Good luck, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Mon Sep 3 00:14:53 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 15:14:53 -0700 Subject: [Tutor] Running a script in the background Message-ID: <5043DA5D.3010202@gmail.com> This is only tangentially related to the thread. Someone mentioned that so long as a script didn't require user input or output to the user, it could run silently in the background. But is there a way for a Python (2.7.3) script to determine whether it was called by the user or called by something like cron or kalarm? That way user inputs could be used when called by a user, but defaults could be used if run by a bot. Or is this more of a Linux question? Ray From alan.gauld at btinternet.com Mon Sep 3 00:30:57 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Sep 2012 23:30:57 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: <5043DA5D.3010202@gmail.com> References: <5043DA5D.3010202@gmail.com> Message-ID: On 02/09/12 23:14, Ray Jones wrote: > could run silently in the background. But is there a way for a Python > (2.7.3) script to determine whether it was called by the user or called > by something like cron or kalarm? That way user inputs could be used > when called by a user, but defaults could be used if run by a bot. Yes you can query the user via the os module.(getuid or getlogin for example) > Or is this more of a Linux question? The details are likely to be implementation dependant, differing even between local hosts since it depends on how the admin has set up the user for cron etc hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Mon Sep 3 00:36:49 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 15:36:49 -0700 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> Message-ID: <5043DF81.1070405@gmail.com> On 09/02/2012 03:30 PM, Alan Gauld wrote: > On 02/09/12 23:14, Ray Jones wrote: >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > > Yes you can query the user via the os module.(getuid or getlogin for > example) > >> Or is this more of a Linux question? > > The details are likely to be implementation dependant, differing even > between local hosts since it depends on how the admin has set up the > user for cron etc > Thanks. I'll add this to my to-learn list (It's frustrating to come up with questions and answers faster than I can assimilate it all :-p) Ray From steve at pearwood.info Mon Sep 3 03:03:02 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 3 Sep 2012 11:03:02 +1000 Subject: [Tutor] Running a script in the background In-Reply-To: <5043DA5D.3010202@gmail.com> References: <5043DA5D.3010202@gmail.com> Message-ID: <20120903010302.GA20674@ando> On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: > This is only tangentially related to the thread. Someone mentioned that > so long as a script didn't require user input or output to the user, it > could run silently in the background. But is there a way for a Python > (2.7.3) script to determine whether it was called by the user or called > by something like cron or kalarm? That way user inputs could be used > when called by a user, but defaults could be used if run by a bot. The usual way to detect this is by checking whether or not there is a terminal available. os.isatty(sys.stdout.fileno()) If the script is running directly in a console, isatty will return True; if it is running from cron, or via a pipe or similar, then it will return False. -- Steven From wrw at mac.com Mon Sep 3 03:04:41 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Sun, 02 Sep 2012 21:04:41 -0400 Subject: [Tutor] Running a script in the background (this time Cc'd to the list) In-Reply-To: <5043DA74.1040903@btinternet.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> <5043DA74.1040903@btinternet.com> Message-ID: <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> On Sep 2, 2012, at 6:15 PM, Alan Gauld wrote: > On 02/09/12 21:30, William R. Wing (Bill Wing) wrote: > >> My suggestion would be to take the script and run it through py2app, >> which will turn it into a stand-alone application which can then >> be added to your list of StartUp or LogIn applications. > > Why not just create a one line shell script that starts the python program and add that to the Startup? What value does using py2app add in this case? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ Apple's mechanism for launching applications at login is picky about what it will accept as a legitimate application to add to the list. You could get there by creating an "AppleScript" that did the same thing. AppleScripts can be saved as applications and an AppleScript can call a python script (I've actually done that, but it leaves you maintaining two bits of code, not just one). To the best of my knowledge, there is no way you can convince the application-picker to accept a shell script (or a raw python script) as an application. You can add it to the list, but at login, what happens is that the editor you used to create the script gets invoked with the script opened in it. -Bill From eryksun at gmail.com Mon Sep 3 06:34:32 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 3 Sep 2012 00:34:32 -0400 Subject: [Tutor] Running a script in the background (this time Cc'd to the list) In-Reply-To: <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> References: <0E0B7F3E-ADB7-40AB-83AA-CB3409D115F8@mac.com> <5043DA74.1040903@btinternet.com> <64F3166E-2924-4532-8B96-26E426C0D55C@mac.com> Message-ID: On Sun, Sep 2, 2012 at 9:04 PM, William R. Wing (Bill Wing) wrote: > > Apple's mechanism for launching applications at login is picky > about what it will accept as a legitimate application to add to > the list. Here's an Ask Different (Apple Stack Exchange) answer with a template for a launchd plist: http://apple.stackexchange.com/a/822 I don't use OS X, so I can't offer anymore held than that. From crawlzone at gmail.com Mon Sep 3 08:33:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Sun, 02 Sep 2012 23:33:30 -0700 Subject: [Tutor] Running a script in the background (offshoot - sorry, OP) In-Reply-To: <20120903010302.GA20674@ando> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: <50444F3A.90608@gmail.com> On 09/02/2012 06:03 PM, Steven D'Aprano wrote: > On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: >> This is only tangentially related to the thread. Someone mentioned that >> so long as a script didn't require user input or output to the user, it >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > The usual way to detect this is by checking whether or not there is a > terminal available. > > os.isatty(sys.stdout.fileno()) > > If the script is running directly in a console, isatty will return True; > if it is running from cron, or via a pipe or similar, then it will > return False. Okay. Your solution works with cron - it does not work with kalarm (KDE's system alarm). The only reason I'm using kalarm rather than cron to begin with is that kalarm is TZ aware while anacron only looks at the system TZ (i.e. with kalarm I can start each task based on its own individual time zone). I read that fcron is fully TZ aware, but when I tried to install it, it wanted to automatically remove anacron and the entire kubuntu-desktop! Now this definitely gets into the Linux side of things. I'll go hit the Ubuntu forums and see what I can find. Thanks, everyone. Ray From richkappler at gmail.com Mon Sep 3 16:04:39 2012 From: richkappler at gmail.com (richard kappler) Date: Mon, 3 Sep 2012 10:04:39 -0400 Subject: [Tutor] multi processes or threads? Message-ID: I'm not sure which direction to go. I need to be able to run multiple ?processes? ?threads? (not sure which) concurrently. I'm working on AI for a robot and because I'm not sure what direction to go I'll use the term "thread" to illustrate my question, realizing threads may not be what I'm looking for. The bot would have several "threads" running concurrently so as to be aware of it's state, such as a vision thread, an object and face recognition thread, a chat thread, a command and control thread, a nav thread, you get the idea. In order to do this in python, should I be looking at threads, multiprocessing, something else or is this not practicable in python? regards, Richard -- Eat a live toad the first thing in the morning and nothing worse will happen to you the rest of the day. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Mon Sep 3 17:01:28 2012 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 3 Sep 2012 10:01:28 -0500 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: Hi. I started running the program in the terminal rather than IDLE. It works, and I can run several programs at the same time. The problem is that when the program is finished running, it prints: exit status: 0 logout [Process completed] And I can't access the data that the program returned. Do I need the program to be saved to a text file, or is there a way to simply print it out? It's a small amount of data, and I'd rather just print it out. Ben On Aug 29, 2012, at 9:24 AM, Marc Tompkins wrote: > On Tue, Aug 28, 2012 at 7:35 PM, Steven D'Aprano wrote: > > In Windows, that is the DOS prompt -- either cmd.com or command.exe, I never remember which one is which. > > I'm pretty sure that was intentional, but just in case... > > In MS-DOS/PC-DOS, and in 16-bit versions of Windows (up to Windows 98/Me, in other words), the command interpreter is COMMAND.COM > > In 32-bit versions of Windows, you can still use the 16-bit interpreter if you want - although it's deprecated, and has been removed entirely in 64-bit Windows - but the native 32-bit command interpreter is CMD.EXE > > (I used all-caps for emphasis without requiring HTML formatting, but in fact Windows is generally case-insensitive.) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Mon Sep 3 18:26:27 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Mon, 03 Sep 2012 12:26:27 -0400 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> On Sep 3, 2012, at 11:01 AM, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It works, and I can run several programs at the same time. The problem is that when the program is finished running, it prints: > exit status: 0 > logout > > [Process completed] > > And I can't access the data that the program returned. Do I need the program to be saved to a text file, or is there a way to simply print it out? It's a small amount of data, and I'd rather just print it out. > Ben > Ben, You will probably get several answers to this, since there are several ways to solve the issue. The simplest (sort of kludgy) solution is simply to make the last line in your program be: junk = raw_input("Yes Master?") and when your program hits this line, it will print out "Yes Master?" in the terminal window and then sit there waiting for you to type something terminated by a key. For future reference, what you've typed goes into the variable junk. This is a dead easy way to get interactive data into ANY future python script you write. -Bill PS: this assumes you are running python 2.x. In python 3.x, raw_input has been renamed input, but it works the say way. From alan.gauld at btinternet.com Mon Sep 3 19:41:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Sep 2012 18:41:40 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 03/09/12 15:04, richard kappler wrote: > what I'm looking for. The bot would have several "threads" running > concurrently so as to be aware of it's state, such as a vision thread, > an object and face recognition thread, a chat thread, a command and > control thread, a nav thread, you get the idea. In order to do this in > python, should I be looking at threads, multiprocessing, something else > or is this not practicable in python? Threads. Multiple processes would be overkill for this. And yes its fine in Python. Check out the threading module. Several online tutorials on how to use it too. My only caveat is not to have too many, especially conflicting controls. For example anything that causes the bot to move should be in a single thread or you wind up with two threads competing with each other to move the bot in two directions at once. Similarly vision and face recognition could conflict. Hopefully you get my drift. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Sep 3 19:55:43 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Sep 2012 18:55:43 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: On 03/09/12 16:01, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It > works, and I can run several programs at the same time. The problem is > that when the program is finished running, it prints: > exit status: 0 > logout > > [Process completed] That is probably writing to stderr so you can redirect the stderr output to a file (or /dev/null if you're feeling confident!) $python myprog.py myargs 2> myprog.err & runs myprog.opy in the background and redirects stderr to the file myprog.err. You can then open mpyprog.err in any text editor to read it if you wish - hopefully it will be very boring! > And I can't access the data that the program returned. Do I need the > program to be saved to a text file, or is there a way to simply print it > out? It's a small amount of data, and I'd rather just print it out. It should print to stdout so you can see it but in general its probably better to redirect that to a file too... Especially if you have multiple programs in one terminal! So your command lines should probably look like$ python myprog.py myargs 2> myprog.err 1> myprog.out & HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Mon Sep 3 21:50:32 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 03 Sep 2012 20:50:32 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: On Mon, 03 Sep 2012 18:55:43 +0100, Alan Gauld wrote: > On 03/09/12 16:01, Benjamin Fishbein wrote: > > Hi. I started running the program in the terminal rather than IDLE. It > > works, and I can run several programs at the same time. The problem is > > that when the program is finished running, it prints: > > exit status: 0 > > logout > > > > [Process completed] What do you mean when you say you ran the program in the terminal? Do you mean that you opened a terminal window and then typed 'python myprog.py'? Or did you click on the python file and choose 'run in terminal' or similar? That output looks to me like what happens on OSX when a terminal window is open but the shell has been closed. I think the instruction to run in a terminal should look like: 1) open the terminal (how to do this depends on your OS). 2) type 'cd /path/to/my/script/folder' and then hit enter. 3) type 'python script.py' and then hit enter. Is that similar to what you're doing? Oscar From dwightdhutto at gmail.com Mon Sep 3 23:32:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:32:43 -0400 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: Think assembly, or procedural with this, and how the mind of a CPU works. Instructional steps toward an endpoint. Your mind works the fastest when one problems is given, and is being solved, otherwise allocation of certain areas take place in order to find a rewarding solution. Not having used threads in the past, I would suggest that you know there has to be either equal allocation of time, or priority based in order to perform each procedure given in threading, until there is a final result. My first thought on giving computers imagination was monkeys banging on a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's interlocking molecular vectors, and run simulations which is much more difficult, but defined algorithmically, and procedurally, unless you network several cpus and allocate to each a specific thought/theory/hypothesis to process. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 3 23:46:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:46:43 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: <20120903010302.GA20674@ando> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On Sun, Sep 2, 2012 at 9:03 PM, Steven D'Aprano wrote: > On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: > > This is only tangentially related to the thread. Someone mentioned that > > so long as a script didn't require user input or output to the user, it > > could run silently in the background. But is there a way for a Python > > (2.7.3) script to determine whether it was called by the user or called > > by something like cron or kalarm? That way user inputs could be used > > when called by a user, but defaults could be used if run by a bot. > > The usual way to detect this is by checking whether or not there is a > terminal available. > > os.isatty(sys.stdout.fileno()) > > If the script is running directly in a console, isatty will return True; > if it is running from cron, or via a pipe or similar, then it will > return False. But a script is always running in the background of the OS main console of the upfront GUI app users usually see, correct? Cron has to coninually run, or have another process that checks x number per minute(hertz of the process) to see what is going on, so it all goes back to a main script in OS runtime checking for processes to run, even for other processes, for other processes, etc. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Sep 3 23:48:17 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 17:48:17 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: > > Cron or another process that oversees cron has to continually run. > > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com* > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 4 01:57:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 00:57:25 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On 03/09/12 22:46, Dwight Hutto wrote: > But a script is always running in the background of the OS main console > of the upfront GUI app users usually see, correct? Not every OS has a main console behind the GUI, but in the case of *nix its true. On *nix there is a cron daemon that runs in the background. but one job running in the background controlling dozens(?) of others is way more efficient than dozens of programs all running idle in the background and periodically springing into action. > back to a main script in OS runtime checking for processes to run, even > for other processes, for other processes, etc. Ultimately it all goes back to the OS scheduler which constantly swaps processes in and out of run mode... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 4 01:59:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 00:59:28 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 03/09/12 22:32, Dwight Hutto wrote: > Think assembly, or procedural with this, and how the mind of a CPU > works. Instructional steps toward an endpoint. > > Your mind works the fastest when one problems is given, and is being > solved, otherwise allocation of certain areas take place in order to > find a rewarding solution. > > Not having used threads in the past, I would suggest that you know there > has to be either equal allocation of time, or priority based in order to > perform each procedure given in threading, until there is a final result. > > My first thought on giving computers imagination was monkeys banging on > a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's > interlocking molecular vectors, and run simulations which is much more > difficult, but defined algorithmically, and procedurally, unless you > network several cpus and allocate to each a specific > thought/theory/hypothesis to process. > I have no idea what all that means! Nor how it relates to the OPs question. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dwightdhutto at gmail.com Tue Sep 4 02:19:07 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 20:19:07 -0400 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On Mon, Sep 3, 2012 at 7:59 PM, Alan Gauld wrote: > On 03/09/12 22:32, Dwight Hutto wrote: > >> Think assembly, or procedural with this, and how the mind of a CPU >> works. Instructional steps toward an endpoint. >> >> Your mind works the fastest when one problems is given, and is being >> solved, otherwise allocation of certain areas take place in order to >> find a rewarding solution. >> >> Not having used threads in the past, I would suggest that you know there >> has to be either equal allocation of time, or priority based in order to >> perform each procedure given in threading, until there is a final result. >> I'm working on AI for a robot and because I'm not sure what direction >> to go I'll use the term "thread" to illustrate my question, realizing >> threads may not be what I'm looking for. >> My first thought I'm working on AI for a robot and because I'm not sure >> what direction to go I'll use the term "thread" to illustrate my question, >> realizing threads may not be what I'm looking for. on giving computers >> imagination was monkeys banging on >> a keyboard, until Shakespeare shot out(Me thinks it a weasel). Now it's >> interlocking molecular vectors, and run simulations which is much more >> difficult, but defined algorithmically, and procedurally, unless you >> network several cpus and allocate to each a specific >> thought/theory/hypothesis to process. >> >> > I have no idea what all that means! > Nor how it relates to the OPs question. > >From the OP: I'm working on AI for a robot and because I'm not sure what direction to go I'll use the term "thread" to illustrate my question, realizing threads may not be what I'm looking for. Tell me Alan, what is threading within a CPU, coming from a higher level language, that passes through a processor executing one instruction at time from the instruction pointer, unless otherwise designed from multiple instructions through separate cpu's(i.e. real thread commands)? -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Tue Sep 4 02:26:43 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 20:26:43 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On Mon, Sep 3, 2012 at 7:57 PM, Alan Gauld wrote: > On 03/09/12 22:46, Dwight Hutto wrote: > > But a script is always running in the background of the OS main console >> of the upfront GUI app users usually see, correct? >> > > Not every OS has a main console behind the GUI, but in the case of *nix > its true. > > On *nix there is a cron daemon that runs in the background. > but one job running in the background controllingfat boy slim dozens(?) of > others is way more efficient than dozens of programs all running idle in > the background and periodically springing into action. > But each OS(BIOS handler) has a way of providing/accepting instructions to the processor, which is constantly procedural. This has to have a terminal at some point. What is meant by behind a console, and running without a console, just a window system, and a file set that deals with instructions/errors based on BIOS input/output? -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 4 03:47:32 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 04 Sep 2012 11:47:32 +1000 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> Message-ID: <50455DB4.2070808@pearwood.info> On 04/09/12 01:01, Benjamin Fishbein wrote: > Hi. I started running the program in the terminal rather than IDLE. It works, > and I can run several programs at the same time. The problem is that when the >program is finished running, it prints: > exit status: 0 > logout > > [Process completed] Which terminal is that? I've never come across a terminal with that behaviour. > And I can't access the data that the program returned. Programs don't return data. They can output data to a file or pipe, or print to the screen. The execution model of functions within a program and of the program itself are quite different and you need to wrap your brain around the differences. Normally, you would output your program's result to a file-like thing. Two common idioms used by most command-line tools are: 1) the program always writes data to "standard output" (stdout); the caller can re-direct stdout using the usual pipe and redirection operators; 2) the program takes a command-line argument telling it which file to write to; if no file name is given, you can write to a default file, or stdout as above, or print an error message and stop. Variations include "verbose mode", that formats the result in a nice, human- readable format intended for human readers, and "terse mode" intended to be piped to another program. I recommend you study the various conventions of the command-line tools on your operating system. In Python, normally you would divide your program into two separate layers: * a calculation layer that calculates the result you need; * a display layer that is responsible for output. That allows you to easily separate the two parts of the problem: you can isolate "display bugs" from "calculation bugs", test and debug each separately, and even use the calculation functions from other Python code. The display layer might be as simple as the print command: if __name__ == '__main__': result = do_some_calculation() print(result) Last but not least, to be a "well-behaved" command line tool, you should set the return code. The easiest way to do this from Python is with sys.exit: import sys if an_error_occurred: sys.exit(error_code) else: sys.exit(0) There are supposed to be conventions for what the error codes mean, but nobody agrees on them. The easiest is to just return 1 or 2 to mean "an error occurred". -- Steven From steve at pearwood.info Tue Sep 4 03:56:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 04 Sep 2012 11:56:44 +1000 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: <50455FDC.6070900@pearwood.info> On 04/09/12 10:26, Dwight Hutto wrote: >> On *nix there is a cron daemon that runs in the background. >> but one job running in the background controlling dozens(?) of >> others is way more efficient than dozens of programs all running idle in >> the background and periodically springing into action. >> > > But each OS(BIOS handler) has a way of providing/accepting instructions to > the processor, which is constantly procedural. This has to have a terminal > at some point. > > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based on > BIOS input/output? I'm afraid these sentences sound like gobbledygook to me. No offense Dwight, but it sounds like you're randomly inserting "computer terms" into sentences with no meaning. The only part that actually makes sense to me is: "This has to have a terminal at some point." but that is not true. The fact that cron runs without a tty (a terminal) is proof of that. -- Steven From Garry.Willgoose at newcastle.edu.au Tue Sep 4 03:57:48 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 4 Sep 2012 11:57:48 +1000 Subject: [Tutor] making a shortcut in windows Message-ID: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error AttributeError: function 'CreateSymbolicLinkW' not found so does anybody have any suggestions? __CSL = None def create_alias(source, linkname): """ Each operating system has a different way of creating an alias. This is the windows version """ import os try: global __CSL if __CSL is None: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte __CSL = csl flags = 0 if source is not None and os.path.isdir(source): flags = 1 if __CSL(linkname, source, flags) == 0: raise ctypes.WinError() except: print('#### Error creating a file alias from '+str(source)+' to '+str(linkname)) return() From dwightdhutto at gmail.com Tue Sep 4 04:21:36 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Mon, 3 Sep 2012 22:21:36 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: <50455FDC.6070900@pearwood.info> References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> <50455FDC.6070900@pearwood.info> Message-ID: On Mon, Sep 3, 2012 at 9:56 PM, Steven D'Aprano wrote: > On 04/09/12 10:26, Dwight Hutto wrote: > > On *nix there is a cron daemon that runs in the background. >>> but one job running in the background controlling dozens(?) of >>> >>> others is way more efficient than dozens of programs all running idle in >>> the background and periodically springing into action. >>> >>> >> But each OS(BIOS handler) has a way of providing/accepting instructions to >> the processor, which is constantly procedural. This has to have a terminal >> at some point. >> >> What is meant by behind a console, and running without a console, just a >> window system, and a file set that deals with instructions/errors based on >> BIOS input/output? >> > > > On Mon, Sep 3, 2012 at 9:56 PM, Steven D'Apran > > Best regards, > o wrote: > >> On 04/09/12 10:26, Dwight Hutto wrote: >> >> On *nix there is a cron daemon that runs in the background. >>>> but one job running in the background controlling dozens(?) of >>>> >>>> others is way more efficient than dozens of programs all running idle in >>>> the background and periodically springing into action. >>>> >>>> >>> But each OS(BIOS handler) has a way of providing/accepting instructions >>> to >>> the processor, which is constantly procedural. This has to have a >>> terminal >>> at some point. >>> >>> What is meant by behind a console, and running without a console, just a >>> window system, and a file set that deals with instructions/errors based >>> on >>> BIOS input/output? >>> >> >> I'm afraid these sentences sound like gobbledygook to me. No offense >> Dwight, >> but it sounds like you're randomly inserting "computer terms" into >> sentences >> with no meaning. >> >> Which one's. If yuou could, please reply on a line by line, because some of what you listed above isn't mine. What's wrong with: But each OS(BIOS handler) has a way of providing/accepting instructions to the processor, which is constantly procedural. This has to have a terminal at some point. What is meant by behind a console, and running without a console, just a window system, and a file set that deals with instructions/errors based on BIOS input/output? I'll add Intel/AMD to the instructions secton. The gobbledy gook, might be a little smeared on your face...Want a rag?...Steven By the way, you can call me David...buddy. The only part that actually makes sense to me is: >> >> >> "This has to have a terminal at some point." >> >> but that is not true. The fact that cron runs without a tty (a terminal) >> is >> proof of that. >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > I'm afraid these sentences sound like gobbledygook to me. No offense > Dwight, > but it sounds like you're randomly inserting "computer terms" into > sentences > with no meaning. > > The only part that actually makes sense to me is: > > > "This has to have a terminal at some point." > > but that is not true. The fact that cron runs without a tty (a terminal) is > proof of that. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 4 07:56:43 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 4 Sep 2012 15:56:43 +1000 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: <20120904055643.GA28719@ando> On Tue, Sep 04, 2012 at 11:57:48AM +1000, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > Python 2.6 or later. In Unix its easy using os.symlink but I can't > find anything equivalent for windows. My searches on the web led me to > the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found If you expect us to actually debug the error, you need to give the right debugging information. That means you have to show the FULL traceback printed, not just the final error message without any context. Do not retype the error from memory, or summarise it, do a copy and paste of the entire traceback, starting with the line Traceback (most recent call last): all the way to the end. And then make sure that the code you are giving us is the same as the code you are running. I say this because I believe that the code you sent us is not the code you are running. I cannot see any possible way for the code you gave to raise AttributeError. But in this case, I recommend against using ctypes. Here are some better ways to manage Windows shortcuts: http://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts/ http://mail.python.org/pipermail/python-win32/2003-March/000862.html > __CSL = None > > def create_alias(source, linkname): > """ > Each operating system has a different way of creating an alias. > This is the windows version > """ That's technically incorrect. *Alias* (MacOS), *shortcut* (Windows) and *symlink* (Linux, Unix, MacOS, and others) are all slightly different things, although they all solve more-or-less the same problem. In principle you could have a single OS offer all three. MacOS offers both aliases and symlinks. (And even more pedantically: it isn't the *operating system* which matters, but the file system. So Windows with a Linux file system could have symlinks.) > import os > try: [...] > except: > print('#### Error creating a file alias from '+str(source)+' to '+str(linkname)) Please never, ever, ever do that. Every time somebody writes an except block that catches everything like that, god kills a kitten. Catch-all exceptions like that are one of the worst bad-ideas in Python ever. The problems include: * They catch too much -- not only do they catch legitimate errors that should be caught, but they catch non-errors like KeyboardInterrupt which *don't* indicate an error. * They mask programming bugs -- because they catch too much, they hide programming bugs which should be exposed with a traceback so that you can fix them. * They give you no way to access the exception caught. * They tempt beginners into thinking that they have to *hide problems* by catching the exception and just printing a message, instead of *fixing problems* so no exception happens in the first place. There are exceptions (pun not intended) to the rule "never use a bare except", but they're rare. In general, a try...except block should: * always explicitly state the exception(s) you want to catch; * cover only the minimum amount of code necessary. > return() That line is wrong -- it returns an empty tuple (). To return nothing, just say "return" on its own, or better still, don't say anything and the function will return nothing when it is finished. (To be precise: it will return the None object.) -- Steven From alan.gauld at btinternet.com Tue Sep 4 09:51:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 08:51:32 +0100 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> Message-ID: On 04/09/12 01:26, Dwight Hutto wrote: > But each OS(BIOS handler) has a way of providing/accepting instructions > to the processor, which is constantly procedural. This has to have a > terminal at some point. No it doesn't. Most OS do not run in a 'procedural' way (by which I assume you mean sequential?) Most are event driven and that often at the hardware level. The processor has an interrupt mechanism which causes a section of code to run. The section chosen is determined by the interrupt number and results in a jump to a predefined address. The interrupts are driven by hardware events with no software control. Some interrupts are pre-emptive - they will stop any current processing and take control, others will wait for current processing to finish. The processor will also have a software interrupt mechanism which does the same thing but is driven by an INT call in the software. Operating systems from CP/M and DOS onwards are driven by interrupts at the kernel level they do not sit in some kind of giant event loop looking for things to process. > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based > on BIOS input/output? Again no, a terminal is an I/O mechanism. It reads input and displays output. The terminal does not process the commands it passes those to the program running inside it. Even the shell is not part of the Terminal, it just runs inside. And daemon programs do not use a terminal at all. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Sep 4 10:05:49 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Sep 2012 09:05:49 +0100 Subject: [Tutor] multi processes or threads? In-Reply-To: References: Message-ID: On 04/09/12 01:19, Dwight Hutto wrote: > I have no idea what all that means! > Nor how it relates to the OPs question. > From the OP: > > I'm working on AI for a robot and because I'm not sure what direction OK, I see that connection now. > Tell me Alan, what is threading within a CPU, coming from a higher level > language, that passes through a processor executing one instruction at > time from the instruction pointer, unless otherwise designed from > multiple instructions through separate cpu's(i.e. real thread commands)? I'm still not certain what you mean here but I think you are referring to the time-slicing technique used by the OS to run multiple processes/threads on a single CPU? The CPU (or core) doesn't understand the concept of threading that's a higher level concept usually managed by the OS (although with multi-core CPUs increasingly done at hardware too). The point of threading is to avoid programs blocking while still having valid work to do. In effect taking advantage of the multi-processing features of the OS to allow parts of a program to keep running when it would otherwise block while waiting for input or output to complete. As such it will make the application more responsive and for bulk data processing run faster (with fewer wait states). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Tue Sep 4 11:13:37 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Sep 2012 10:13:37 +0100 Subject: [Tutor] running more than one python program at the same time In-Reply-To: References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> <15DDF669-1A6D-448B-8091-B2847ED8D70C@gmail.com> Message-ID: Hi Ben, It's best if you can avoid top-posting and put your responses in between the appropriate parts of the message you are replying to like I have below: On 4 September 2012 02:53, Benjamin Fishbein wrote: > I used Python Launcher and it opened it in the terminal. > Ben > > On Sep 3, 2012, at 2:50 PM, Oscar Benjamin wrote: > > > On Mon, 03 Sep 2012 18:55:43 +0100, Alan Gauld < > alan.gauld at btinternet.com> wrote: > >> On 03/09/12 16:01, Benjamin Fishbein wrote: > >> > Hi. I started running the program in the terminal rather than > > IDLE. It > >> > works, and I can run several programs at the same time. The > > problem is > >> > that when the program is finished running, it prints: > >> > exit status: 0 > >> > logout > >> > > >> > [Process completed] > > > > What do you mean when you say you ran the program in the terminal? Do > you mean that you opened a terminal window and then typed 'python > myprog.py'? Or did you click on the python file and choose 'run in > terminal' or similar? That output looks to me like what happens on OSX when > a terminal window is open but the shell has been closed. > So you were using the python launcher on the dock? I guess you are using OSX, then (it's good to provide this kind of information). The reason you're not seeing any output is probably because you're not printing it. If your program has a variable called 'total' that you would like to see the value of simply put a line like 'print(total)' at the end of your script. Then you should see the output. > > > > I think the instruction to run in a terminal should look like: > > 1) open the terminal (how to do this depends on your OS). > > 2) type 'cd /path/to/my/script/folder' and then hit enter. > > 3) type 'python script.py' and then hit enter. > Have you tried the instructions above. Assuming you're using OSX you can do step 1 by hitting cmd-space to open spotlight. Then you type 'terminal' and hit enter and you will have a terminal window. Oscar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Sep 4 11:14:50 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 4 Sep 2012 05:14:50 -0400 Subject: [Tutor] Running a script in the background In-Reply-To: References: <5043DA5D.3010202@gmail.com> <20120903010302.GA20674@ando> <50455FDC.6070900@pearwood.info> Message-ID: On Mon, Sep 3, 2012 at 10:21 PM, Dwight Hutto wrote: > What's wrong with: > > But each OS(BIOS handler) has a way of providing/accepting instructions to > the processor, which is constantly procedural. This has to have a terminal > at some point. What do you mean by 'terminal' in this context? A terminal is a device (possibly virtual) for entering data and displaying output from a computer. cron isn't scheduling active processes/threads like the kernel does. Every minute, it checks a job table and possibly starts one or more programs. This is an efficient way to schedule a large number of programs to run at various times throughout the day, week, and month. Otherwise all of these programs would need to have at least a stub that runs as a daemon, wasting memory and CPU resources needlessly. Scheduling processes is an entirely different domain. In a preemptive multitasking system, it's up to the kernel to schedule access to the CPU. Each process (or thread on some systems) is assigned a quantum of ticks. The ticks are based on a hardware timer. Periodically (e.g. 10 milliseconds) this timer triggers a hardware interrupt that enables the kernel to preempt the current thread. The kernel schedules the next (possibly the same) process to run, based on a priority scheme, out of the pool of ready processes. Preempting a running process requires a context switch, i.e. the process control block (e.g. PID, priority, execution state such as running/ready/waiting, CPU number/registers/flags, virtual memory, signal handlers, I/O, credentials, accounting, etc) has to be saved on the current stack. Then the PCB of the next process is loaded; the CPU state is restored; and execution resumes seamlessly. Here's the task_struct used by the Linux scheduler (lines 1235-1593): http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=blob;f=include/linux/sched.h#l1235 > What is meant by behind a console, and running without a console, just a > window system, and a file set that deals with instructions/errors based on > BIOS input/output? Windows NT typically boots without a console. It doesn't have virtual terminals, but you can run console programs in a Win32 console managed by the Client/Server Runtime Subsystem (csrss.exe) In contrast, Linux boots in console mode. Typically it maps the "console" (boot parameter) to the current virtual terminal (i.e. /dev/tty0), but it could also be a dumb terminal or modem. It creates several virtual terminals depending on the system configuration. Debian has tty's 1-63 and runs getty on tty 1-6 to allow text-mode logins and an Xorg display manager (e.g. lightdm) on tty7 for logging in to a graphical desktop environment (e.g. xfce4). From eryksun at gmail.com Tue Sep 4 12:31:43 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 4 Sep 2012 06:31:43 -0400 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On Mon, Sep 3, 2012 at 9:57 PM, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > > AttributeError: function 'CreateSymbolicLinkW' not found A simple search for "msdn CreateSymbolicLink" leads to the following page: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363866.aspx Scroll down to the requirements, and you'll see that CreateSymbolicLink was added to Kernel32 (and NTFS) in Windows Vista (NT 6.x). Kernel32 in Windows XP (NT 5.x) doesn't have that function; hence the AttributeError. From oscar.j.benjamin at gmail.com Tue Sep 4 14:06:55 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Sep 2012 13:06:55 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in > Python 2.6 or later. In Unix its easy using os.symlink but I can't find > anything equivalent for windows. My searches on the web led me to the code > below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > > so does anybody have any suggestions? > Are you really trying to create a symbolic link? Note that this is not the same thing as a 'shortcut' in Windows. If you say why you want the shortcut someone may be able to help you find another way of doing what you want. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Sep 4 14:55:27 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Sep 2012 13:55:27 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Hi, On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > so does anybody have any suggestions? IIRC and as implied by other responses so far, "Symbolic Links" are an NTFS feature only relatively recently added to NTFS. Creating a Symbolic Link (whether on Windows or elsewhere) is not the same as creating a "Shortcut" in Windows, even though they can in some contexts (e.g. a GUI desktop environment) be used to fulfil the same role. Anyway, to be backwards compatible with Win XP you should be creating a "Shortcut", more properly known as a "Shell link". See here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776891%28v=vs.85%29.aspx Basically you need to use the IShellLink COM interface to create the link. You can use PythonCOM to do this (not sure if you'll be happy about adding a dependency on COM to your application though), either way, here's a presentation that also mentions IShellLink (note it's a bit old so make allowances for the age): http://starship.python.net/~skippy/conferences/tools99/html/ppframe.htm Walter From Garry.Willgoose at newcastle.edu.au Tue Sep 4 15:10:19 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 4 Sep 2012 23:10:19 +1000 Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Oscar, I actually just want the functionality of a shortcut so that I can put an icon on the desktop. symlink allows that in Unix (and a few other capabilities that I'm not that intersted in) and just want something equivalent to the menu item for making a shortcut in Windows. > On 4 September 2012 02:57, Garry Willgoose wrote: > I want to put a shortcut onto the desktop in windows (XP and later) in Python 2.6 or later. In Unix its easy using os.symlink but I can't find anything equivalent for windows. My searches on the web led me to the code below but the code returns the error > > AttributeError: function 'CreateSymbolicLinkW' not found > > so does anybody have any suggestions? > > Are you really trying to create a symbolic link? Note that this is not the same thing as a 'shortcut' in Windows. If you say why you want the shortcut someone may be able to help you find another way of doing what you want. > > Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Tue Sep 4 16:37:22 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 4 Sep 2012 09:37:22 -0500 (CDT) Subject: [Tutor] running more than one python program at the same time In-Reply-To: <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> References: <97A9CEDD-F0E7-4E09-909C-73E09AE6247C@gmail.com> <503D7FE4.7020702@pearwood.info> <73A51BA1-9D58-486E-870F-301153DE4C14@mac.com> Message-ID: On Mon, 3 Sep 2012, William R. Wing (Bill Wing) wrote: > junk = raw_input("Yes Master?") You don't even need the 'junk' bit: raw_input("Yes Master?") Will run just fine. HTH, -Wayne From wayne at waynewerner.com Tue Sep 4 16:44:01 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Tue, 4 Sep 2012 09:44:01 -0500 (CDT) Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: On Tue, 4 Sep 2012, Garry Willgoose wrote: > Oscar, > > I actually just want the functionality of a shortcut so that I can put an > icon on the desktop. symlink allows that in Unix (and a few other > capabilities that I'm not that intersted in) and just want something > equivalent to the menu item for making a shortcut in Windows.? At least in Windows 7+, you can use the mklink command (as administrator): import subprocess subprocess.check_call(['mklink', '/D', #Use /H for a hard link '\users\yourname\desktop\yourfile.txt', '\path\to\yourfile.txt']) HTH, Wayne From wprins at gmail.com Tue Sep 4 18:10:46 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Sep 2012 17:10:46 +0100 Subject: [Tutor] making a shortcut in windows In-Reply-To: References: <8D47D400-DB3B-4FB5-AE8A-45F954F9E1EA@newcastle.edu.au> Message-ID: Hi, On 4 September 2012 15:44, Wayne Werner wrote: >> I actually just want the functionality of a shortcut so that I can put an >> icon on the desktop. symlink allows that in Unix (and a few other >> capabilities that I'm not that intersted in) and just want something >> equivalent to the menu item for making a shortcut in Windows. > > > At least in Windows 7+, you can use the mklink command (as administrator): > > import subprocess > subprocess.check_call(['mklink', > '/D', #Use /H for a hard link > '\users\yourname\desktop\yourfile.txt', > '\path\to\yourfile.txt']) > > HTH, > Wayne Yes, but as already noted symbolic links are a newish feature that is not available on older OS's, so the original poster probably wants to look at API's to create actual shortcut's given that he's targeting WinXP etc. Regards Walter From chigga101 at gmail.com Tue Sep 4 20:45:12 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 19:45:12 +0100 Subject: [Tutor] help me decide Message-ID: hey guys as i program more, i think of silly questions i would like answers to. if anyone doesnt mind entertaining my question, please do answer:) I have just about finished my beginner tutorial, just a few exercises left. i feel confident using Python now but im still not sure which direction i want to go in. I would at some point like to learn how to use GUIs and a web Framework(Django). But i don't know which of the 2 to start out with. a) IF you happen to have used both, which one fills you with joy and is more fun for you to program with, GUI programming, or web related / Framework programming? b) which was easier and less complex for you to learn? or should i say had a lower learning curve? i ask this because the sooner i get an understanding of one, i can maybe give the other one a go. But if it's too hard i usually give 100% to it and never try learning anything else until it computes. my tutorial had a small section on tkinter. I have now looked for some tutorials and noticed Python tutorials on both tkinter and Tk. As i understand they are not the same thing but tkinter is like the interface of Tk? my question is: c) which tutorial would be better to study, Tkinter or Tk? and what exactly is the difference? why do they have separate tutorials? i looked at some pyQT articles, but its coding looks less organised than Tkinter. d) is this true? is Tkinter a lot more straight forward and Python friendly? e) Does pyQT have grids (rows and columns) to place your widgets on like Tkinter, or do you have to use x and y axis to position widgets etc..? Before i try to learn either, GUIs or a web Framework, i was looking into maybe getting a deeper understanding of OOP. my tutorial only covered it briefly. f) would this be a good idea tackling OOP next before the other 2, or is this a skill you master with more programming experience? ok my last question is not so important:) im just curious as i grow more fond of programming. well i keep reading Python is an all-purpose general programming language(web frameworks, desktop apps, science/maths etc..). I notice Java has similar features so should also be considered an all-purpose general programming language. my question is: g) not a comparison in 1 specific area, but which language is better or more suited to all around all-purpose quality. thanks guys From leamhall at gmail.com Tue Sep 4 21:40:12 2012 From: leamhall at gmail.com (leam hall) Date: Tue, 4 Sep 2012 15:40:12 -0400 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: Matthew, Program what is fun for you. I prefer PHP for web work but I'm learning Python for my day job. Python provides a wider range of abilities but PHP is more "fun" for me. If Python GUIs are fun, then do that. The more you enjoy the topic the more reason you will have to learn more and more. I doubt you will exhaust Python's capabilities any time soon. Python or Java? For me it's Python. The only real Java advantage might be Android programming. Leam -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Tue Sep 4 22:20:31 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 21:20:31 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: sorry wrong i didnt send mail right. hey i didnt explain it properly, i wasn't asking what language to use or learn. I am only going to be using Python. I meant whic area to study on 1st, GUI programing e.g Tkinter or Programming with a web framwork e.g Django. From chigga101 at gmail.com Tue Sep 4 22:31:18 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 4 Sep 2012 21:31:18 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: hey you didnt read my question:( i dont enjoy either because i have no experience with them. so im asking questions about peoples personal experiences with the 2 areas which can give me further information to research on. From crawlzone at gmail.com Wed Sep 5 11:42:31 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 02:42:31 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) Message-ID: <50471E87.60607@gmail.com> I have directory names that contain Russian characters, Romanian characters, French characters, et al. When I search for a file using glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the directory names. I thought simply identifying them as Unicode would clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. These representations of directory names are eventually going to be passed to Dolphin (my file manager). Will they pass to Dolphin properly? Do I need to run a conversion? Can that happen automatically within the script considering that the various types of characters are all mixed together in the same directory (i.e. # coding: Latin-1 at the top of the script is not going to address all the different types of characters). While on the subject, I just read through the Unicode info for Python 2.7.3. The history was interesting, but the implementation portion was beyond me. I was looking for a way for a Russian 'backward R' to look like a Russian 'backward R' - not for a bunch of \xxx and \uxxxxx stuff. Can someone point me to a page that will clarify the concepts, not just try to show me the Python implementation of what I already don't understand? ;) Thanks Ray From wprins at gmail.com Wed Sep 5 11:57:24 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 5 Sep 2012 10:57:24 +0100 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50471E87.60607@gmail.com> References: <50471E87.60607@gmail.com> Message-ID: Hi Ray, On 5 September 2012 10:42, Ray Jones wrote: > Can someone point me to a page that will clarify the concepts, not just > try to show me the Python implementation of what I already don't > understand? ;) Try the following 2 links which should hopefully help: http://www.joelonsoftware.com/articles/Unicode.html http://nedbatchelder.com/text/unipain.html Cheers, Walter From chigga101 at gmail.com Wed Sep 5 12:04:39 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Wed, 5 Sep 2012 11:04:39 +0100 Subject: [Tutor] help me decide In-Reply-To: <5046A014.6030907@btinternet.com> References: <5046A014.6030907@btinternet.com> Message-ID: Hi Alan thanks so much for your helpful answers. > probably wxPython or GTk > But if you want to get serious about GUIs I'd probably suggest wxPython > instead - it ultimately is more powerful and complete and if you are only > just starting will be easy to learn whereas learning Tkinter and converting > is more difficult (IMHO). > PyQt is powerful too but there are several limitations in its licensing > model that leave me slightly wary. Gtk is another option. Both of these were > originally made popular in the Linux community but both are available cross > platform now. (as are Tkinter and wxPython) After your response ive decided GUI programming is defintely better for me at this stage. I read Pyside is a replica of pyqt, same makers qt but it covers all the licensing that PyQt doesnt, and if you learn 1 the other is almost exactly the same. Would this be a good enough reason to give it and pyqt a try? how does it compare to wxPython? also please could you tell me why you suggest wxPython over GTK? what are the factors you looked at, is it better for beginners to start out with a simpler toolkit and decide later on if its enough for them? would you say out of the GUIs we have mentioned, apart from Tkinter, that wxPython is the easiet to pick up yet a lot more complete than Tkinter? > I'm not a big fan of user interface programming in any shape. I started my > career writing embedded software where the UI was a switch and some LEDs. So > i am more interested in the internals of a program than in its outer > appearance, but from necessity I've done a little bit of GUI work and even > less web work. this has interested me. is embedded programming a different field to the type of programming in Python? it sounds like thats more lower level prgroamming better suited to a language like C? is your work today still related to this area? somewhere down the learn, after i have mastered Python i'd definately like to learn about internals of a program, even though the thought of that really scares me:) From crawlzone at gmail.com Wed Sep 5 12:05:23 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 03:05:23 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <504723E3.5070904@gmail.com> On 09/05/2012 02:57 AM, Walter Prins wrote: > Hi Ray, > > On 5 September 2012 10:42, Ray Jones wrote: >> Can someone point me to a page that will clarify the concepts, not just >> try to show me the Python implementation of what I already don't >> understand? ;) > Try the following 2 links which should hopefully help: > > http://www.joelonsoftware.com/articles/Unicode.html > http://nedbatchelder.com/text/unipain.html > "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" Right up my alley! ;) Thank-you. Ray From __peter__ at web.de Wed Sep 5 12:33:46 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 12:33:46 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> Message-ID: Ray Jones wrote: > I have directory names that contain Russian characters, Romanian > characters, French characters, et al. When I search for a file using > glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the > directory names. I thought simply identifying them as Unicode would > clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. That's the representation which is guaranteed to be all-ascii. Python will automatically apply repr() to a unicode string when it is part of a list >>> files = [u"\u0456\u0439\u043e"] # files = glob.glob(unicode_pattern) >>> print files [u'\u0456\u0439\u043e'] To see the actual characters print the unicode strings individually: >>> for file in files: ... print file ... ??? > These representations of directory names are eventually going to be > passed to Dolphin (my file manager). Will they pass to Dolphin properly? How exactly do you "pass" these names? > Do I need to run a conversion? When you write them to a file you need to pick an encoding. > Can that happen automatically within the > script considering that the various types of characters are all mixed > together in the same directory (i.e. # coding: Latin-1 at the top of the > script is not going to address all the different types of characters). the coding cookie tells python how to interpret the bytes in the files, so # -*- coding: utf-8 -*- s = u"???" and # -*- coding: latin1 -*- s = u"???" contain a different byte sequence on disc, but once imported the two strings are equal (and have the same in-memory layout): >>> import codecs >>> for encoding in "latin-1", "utf-8": ... with codecs.open("tmp_%s.py" % encoding.replace("-", ""), "w", encoding=encoding) as f: f.write(u'# -*- coding: %s\ns = u"???"' % encoding)... >>> for encoding in "latin1", "utf8": ... open("tmp_%s.py" % encoding).read() ... '# -*- coding: latin-1\ns = u"\xe4\xf6\xfc"' '# -*- coding: utf-8\ns = u"\xc3\xa4\xc3\xb6\xc3\xbc"' >>> from tmp_latin1 import s >>> from tmp_utf8 import s as t >>> s == t True > While on the subject, I just read through the Unicode info for Python > 2.7.3. The history was interesting, but the implementation portion was > beyond me. I was looking for a way for a Russian 'backward R' to look > like a Russian 'backward R' - not for a bunch of \xxx and \uxxxxx stuff. >>> ya = u"\N{CYRILLIC CAPITAL LETTER YA}" >>> ya u'\u042f' >>> print ya ? This only works because Python correctly guesses the terminal encoding. If you are piping output to another file it will assume ascii and you will see an encoding error: $cat tmp.py # -*- coding: utf-8 -*- print u"?"$ python tmp.py ? $python tmp.py | cat Traceback (most recent call last): File "tmp.py", line 2, in print u"?" UnicodeEncodeError: 'ascii' codec can't encode character u'\u042f' in position 0: ordinal not in range(128) You can work around that by specifying the appropriate encoding explicitly:$ python tmp2.py iso-8859-5 | cat ? $python tmp2.py latin1 | cat Traceback (most recent call last): File "tmp2.py", line 4, in print u"?".encode(encoding) UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in position 0: ordinal not in range(256) From crawlzone at gmail.com Wed Sep 5 13:05:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 04:05:30 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <504731FA.2040903@gmail.com> On 09/05/2012 03:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > >>> files = [u"\u0456\u0439\u043e"] # files = glob.glob(unicode_pattern) >>> print files > [u'\u0456\u0439\u043e'] > > To see the actual characters print the unicode strings individually: > >>>> for file in files: > ... print file > ... > ??? Aha! That works. >> These representations of directory names are eventually going to be >> passed to Dolphin (my file manager). Will they pass to Dolphin properly? > How exactly do you "pass" these names? I will be calling Dolphin with subprocess.call() and passing the directories as command line arguments. >$ cat tmp.py > # -*- coding: utf-8 -*- > print u"?" > $python tmp.py > ? >$ python tmp.py | cat > Traceback (most recent call last): > File "tmp.py", line 2, in > print u"?" > UnicodeEncodeError: 'ascii' codec can't encode character u'\u042f' in > position 0: ordinal not in range(128) > > You can work around that by specifying the appropriate encoding explicitly: > > $python tmp2.py iso-8859-5 | cat > ? >$ python tmp2.py latin1 | cat > Traceback (most recent call last): > File "tmp2.py", line 4, in > print u"?".encode(encoding) > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in > position 0: ordinal not in range(256) > But doesn't that entail knowing in advance which encoding you will be working with? How would you automate the process while reading existing files? Ray From __peter__ at web.de Wed Sep 5 13:52:57 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 13:52:57 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> Message-ID: Ray Jones wrote: >> You can work around that by specifying the appropriate encoding >> explicitly: >> >> $python tmp2.py iso-8859-5 | cat >> ? >>$ python tmp2.py latin1 | cat >> Traceback (most recent call last): >>File "tmp2.py", line 4, in >>print u"?".encode(encoding) >> UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in >> position 0: ordinal not in range(256) >> > But doesn't that entail knowing in advance which encoding you will be > working with? How would you automate the process while reading existing > files? If you don't *know* the encoding you *have* to guess. For instance you could default to UTF-8 and fall back to Latin-1 if you get an error. While decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will always "succeed" as there is one codepoint associated with every possible byte. The result howerver may not make sense. Think for line in codecs.open("lol_cat.jpg", encoding="latin1"): print line.rstrip() From crawlzone at gmail.com Wed Sep 5 16:04:04 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 07:04:04 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> Message-ID: <50475BD4.7020301@gmail.com> On 09/05/2012 04:52 AM, Peter Otten wrote: > Ray Jones wrote: > >> >> But doesn't that entail knowing in advance which encoding you will be >> working with? How would you automate the process while reading existing >> files? > If you don't *know* the encoding you *have* to guess. For instance you could > default to UTF-8 and fall back to Latin-1 if you get an error. While > decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will > always "succeed" as there is one codepoint associated with every possible > byte. The result howerver may not make sense. Think > > for line in codecs.open("lol_cat.jpg", encoding="latin1"): > print line.rstrip() :)) So when glob reads and returns garbley, non-unicode file names....\xb4\xb9....is it making a guess as to which encoding should be used for that filename? Does Linux store that information when it saves the file name? And (most?) importantly, how can I use that fouled up file name as an argument in calling Dolphin? Ray From eryksun at gmail.com Wed Sep 5 16:31:16 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Sep 2012 10:31:16 -0400 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50471E87.60607@gmail.com> References: <50471E87.60607@gmail.com> Message-ID: On Wed, Sep 5, 2012 at 5:42 AM, Ray Jones wrote: > I have directory names that contain Russian characters, Romanian > characters, French characters, et al. When I search for a file using > glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the > directory names. I thought simply identifying them as Unicode would > clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. This is just an FYI in case you were manually decoding. Since glob calls os.listdir(dirname), you can get Unicode output if you call it with a Unicode arg: >>> t = u"\u0456\u0439\u043e" >>> open(t, 'w').close() >>> import glob >>> glob.glob('*') # UTF-8 output ['\xd1\x96\xd0\xb9\xd0\xbe'] >>> glob.glob(u'*') [u'\u0456\u0439\u043e'] Regarding subprocess.Popen, just use Unicode -- at least on a POSIX system. Popen calls an exec function, such as posix.execv, which handles encoding Unicode arguments to the file system encoding. On Windows, the _subprocess C extension in 2.x is limited to calling CreateProcessA with char* 8-bit strings. So Unicode characters beyond ASCII (the default encoding) trigger an encoding error. From crawlzone at gmail.com Wed Sep 5 16:51:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 07:51:52 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> Message-ID: <50476708.4060206@gmail.com> On 09/05/2012 07:31 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 5:42 AM, Ray Jones wrote: >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > This is just an FYI in case you were manually decoding. Since glob > calls os.listdir(dirname), you can get Unicode output if you call it > with a Unicode arg: > > >>> t = u"\u0456\u0439\u043e" > >>> open(t, 'w').close() > > >>> import glob > > >>> glob.glob('*') # UTF-8 output > ['\xd1\x96\xd0\xb9\xd0\xbe'] > > >>> glob.glob(u'*') > [u'\u0456\u0439\u043e'] Yes, I played around with that some....in my lack of misunderstanding, I thought that adding the 'u' would pop the characters out at me the way they should appear. Silly me.... ;) > Regarding subprocess.Popen, just use Unicode -- at least on a POSIX > system. Popen calls an exec function, such as posix.execv, which > handles encoding Unicode arguments to the file system encoding. > > On Windows, the _subprocess C extension in 2.x is limited to calling > CreateProcessA with char* 8-bit strings. So Unicode characters beyond > ASCII (the default encoding) trigger an encoding error. subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) Dolphin's error message: 'The file or folder /my_home/testdir/\u044c\u043e\u0432 does not exist' But if I copy the characters as seen by Bash's shell and paste them into my subprocess.call(), Dolphin recognizes the directory just fine. So is Dolphin unicode-dead, or am I missing something? Ray From crawlzone at gmail.com Wed Sep 5 17:04:50 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 08:04:50 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476A12.1000705@gmail.com> On 09/05/2012 07:51 AM, Ray Jones wrote: > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' > > But if I copy the characters as seen by Bash's shell and paste them into > my subprocess.call(), Dolphin recognizes the directory just fine. > > So is Dolphin unicode-dead, or am I missing something? > > > Ray Answering myself here..... I suspect I'm missing something because once within the folders, Dolphin properly recognizes the characters....even so far as writing Arabic and Hebrew "backward"....I wonder.... Sure enough. If I use the glob.glob() non-unicode characters (\x93\xbe) on the command line, Dolphin understands it just fine. Thanks all. Ray (Still wondering where unicode fits into all this....) From __peter__ at web.de Wed Sep 5 17:09:03 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Sep 2012 17:09:03 +0200 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> <50475BD4.7020301@gmail.com> Message-ID: Ray Jones wrote: > On 09/05/2012 04:52 AM, Peter Otten wrote: >> Ray Jones wrote: >> >>> >>> But doesn't that entail knowing in advance which encoding you will be >>> working with? How would you automate the process while reading existing >>> files? >> If you don't *know* the encoding you *have* to guess. For instance you >> could default to UTF-8 and fall back to Latin-1 if you get an error. >> While decoding non-UTF-8 data with an UTF-8 decoder is likely to fail >> Latin-1 will always "succeed" as there is one codepoint associated with >> every possible byte. The result howerver may not make sense. Think >> >> for line in codecs.open("lol_cat.jpg", encoding="latin1"): >> print line.rstrip() > :)) > > So when glob reads and returns garbley, non-unicode file > names....\xb4\xb9....is it making a guess as to which encoding should be > used for that filename? Does Linux store that information when it saves > the file name? And (most?) importantly, how can I use that fouled up > file name as an argument in calling Dolphin? Linux stores filenames as bytes always. If you pass a unicode path to os.listdir() it tries to decode the byte sequence of the resulting names or returns bytes if that fails: >>> import sys >>> sys.getfilesystemencoding() 'UTF-8' >>> import os >>> os.mkdir(u"alpha") >>> odd_name = "".join(map(chr, range(128, 144))) # a byte string! >>> os.mkdir(odd_name) >>> os.listdir(u".") # unicode arg triggers unicode output (where possible) [u'alpha', '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'] (Python 3 takes a slightly different approach) Dolphin (at least the version I have tried) can only cope with filenames that can be decoded into unicode using the file system encoding. Neither Python nor Linux care for the "meaning" of the file names. They can process arbitrary byte sequences just fine. From eryksun at gmail.com Wed Sep 5 17:18:27 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Sep 2012 11:18:27 -0400 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: > > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' "\u" only codes a BMP character in unicode literals, i.e. u"unicode literal". You forgot the 'u'. From steve at pearwood.info Wed Sep 5 17:16:37 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Sep 2012 01:16:37 +1000 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50475BD4.7020301@gmail.com> References: <50471E87.60607@gmail.com> <504731FA.2040903@gmail.com> <50475BD4.7020301@gmail.com> Message-ID: <50476CD5.5030006@pearwood.info> On 06/09/12 00:04, Ray Jones wrote: > On 09/05/2012 04:52 AM, Peter Otten wrote: >> Ray Jones wrote: >> >>> >>> But doesn't that entail knowing in advance which encoding you will be >>> working with? How would you automate the process while reading existing >>> files? >> If you don't *know* the encoding you *have* to guess. For instance you could >> default to UTF-8 and fall back to Latin-1 if you get an error. While >> decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will >> always "succeed" as there is one codepoint associated with every possible >> byte. The result howerver may not make sense. Think >> >> for line in codecs.open("lol_cat.jpg", encoding="latin1"): >> print line.rstrip() > :)) > > So when glob reads and returns garbley, non-unicode file > names....\xb4\xb9....is it making a guess as to which encoding should be > used for that filename? No. It is returning the actual bytes stored by the file system. At least that's what it does under Linux. Windows is different. The most common Linux file systems (ext2 and ext3) store file names as bytes, not Unicode. Your desktop environment (KDE, Gnome, Unity, etc.) *may* try to enforce Unicode names, probably using UTF-8, but the file system is perfectly happy to let you create file names using different encodings, or no encoding at all. (I believe the only invalid characters in ext2 or ext3 files are ASCII NULL and FORWARD SLASH. Even newline \n is valid.) > Does Linux store that information when it saves the file name? No. The file system doesn't care about encodings, it just knows about bytes. Your desktop environment might try to enforce UTF-8 encoded file names, but nothing stops some other program from creating a file using a different encoding. For example, suppose I want to name a file "A???" (just because I can). Assuming that KDE uses UTF-8, as it should, then Dolphin or Konqueror will tell the file system: name this file "\x41\xcf\x80\xd0\xaf\xe2\x80\xa0" (Note that the first byte, \x41, is just the ASCII code for uppercase A.) When another UTF-8 aware program sees that byte-string, it will decode it back to "A???" and I will be happy that my files have cool names. But then some day I use another program, which knows nothing about UTF-8 but thinks I'm running an Apple Mac in Greece back in 1990 or thereabouts. It sees the same sequence of bytes, and decodes it using the MacGreek encoding, which gives "A???????" instead, and I'll be unhappy because my cool file names look like rubbish. But the actual file names (stored as bytes) are the same. > And (most?) importantly, how can I use that fouled up > file name as an argument in calling Dolphin? Just pass it as the file name and hope for the best :) Seriously, I *expect* (but don't know for sure) that just passing the raw bytes to Dolphin will be fine, it will decode them as it sees fit. Try it and see. -- Steven From crawlzone at gmail.com Wed Sep 5 17:23:51 2012 From: crawlzone at gmail.com (Ray Jones) Date: Wed, 05 Sep 2012 08:23:51 -0700 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476E87.6020400@gmail.com> On 09/05/2012 08:18 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: >> subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) >> >> Dolphin's error message: 'The file or folder >> /my_home/testdir/\u044c\u043e\u0432 does not exist' > "\u" only codes a BMP character in unicode literals, i.e. u"unicode > literal". You forgot the 'u'. What with all the 'u's floating around in the unicode escape characters, I didn't realize I needed to add yet another one! You're right. It worked. Thank-you everyone. Ray From steve at pearwood.info Wed Sep 5 17:25:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Sep 2012 01:25:51 +1000 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: <50476708.4060206@gmail.com> References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: <50476EFF.7060102@pearwood.info> On 06/09/12 00:51, Ray Jones wrote: > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' That's because you're telling Dolphin to look for a file literally called: BACKSLASH u ZERO FOUR FOUR c BACKSLASH ... Either use the actual unicode string, which you can write like either of these: u'/my_home/testdir/???' u'/my_home/testdir/\u044c\u043e\u0432' (note the leading u' delimiter, not just ') or try using the raw bytes instead: '/my_home/testdir/\xd1\x8c\xd0\xbe\xd0\xb2' (assuming Dolphin is using UTF-8) and hope Dolphin can decode them correctly. (It better.) -- Steven From breamoreboy at yahoo.co.uk Wed Sep 5 18:12:43 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Sep 2012 17:12:43 +0100 Subject: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;) In-Reply-To: References: <50471E87.60607@gmail.com> <50476708.4060206@gmail.com> Message-ID: On 05/09/2012 16:18, eryksun wrote: > On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: >> >> subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) >> >> Dolphin's error message: 'The file or folder >> /my_home/testdir/\u044c\u043e\u0432 does not exist' > > "\u" only codes a BMP character in unicode literals, i.e. u"unicode > literal". You forgot the 'u'. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > For the record the u prefix for literals was taken out of Python 3 but has been reinstated in Python 3.3, see http://docs.python.org/dev/whatsnew/3.3.html#pep-414-explicit-unicode-literals -- Cheers. Mark Lawrence. From ramit.prasad at jpmorgan.com Wed Sep 5 19:22:22 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 5 Sep 2012 17:22:22 +0000 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47416646EA0@SCACMX008.exchad.jpmchase.net> From: Matthew Ngaha [snip] > i feel confident using Python now but im still not > sure which direction i want to go in. I would at some point like to > learn how to use GUIs and a web Framework(Django). But i don't know > which of the 2 to start out with. > > a) IF you happen to have used both, which one fills you with joy and > is more fun for you to program with, GUI programming, or web related / > Framework programming? > > b) which was easier and less complex for you to learn? or should i say > had a lower learning curve? i ask this because the sooner i get an > understanding of one, i can maybe give the other one a go. But if it's > too hard i usually give 100% to it and never try learning anything > else until it computes. [snip] > Before i try to learn either, GUIs or a web Framework, i was looking > into maybe getting a deeper understanding of OOP. my tutorial only > covered it briefly. > > f) would this be a good idea tackling OOP next before the other 2, or > is this a skill you master with more programming experience? > > ok my last question is not so important:) im just curious as i grow > more fond of programming. well i keep reading Python is an all-purpose > general programming language(web frameworks, desktop apps, > science/maths etc..). I notice Java has similar features so should > also be considered an all-purpose general programming language. my > question is: > > g) not a comparison in 1 specific area, but which language is better > or more suited to all around all-purpose quality. > > thanks guys I would second the wxPython framework as a popular and fully featured framework; being popular means it will likely be easier to get help on it. I was *not* a fan of GUI in Java using Swing. Stick with Python, but this list is probably biased. :) The real question is what do you want to *do* with it? The purpose or intent probably matters more than which you pick. If you are learning for the sake of learning I would probably point you in the direction of web frameworks. In my personal opinion there is more opportunity there. Not to mention that the basics you learn in web frameworks will help you design web sites in other languages as well. Whereas desktop applications will probably be a lot more specific to the framework/language and project. That is just my personal observations. Others (including you) may disagree. Ramit From alan.gauld at btinternet.com Wed Sep 5 19:40:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Sep 2012 18:40:20 +0100 Subject: [Tutor] help me decide In-Reply-To: References: <5046A014.6030907@btinternet.com> Message-ID: On 05/09/12 11:04, Matthew Ngaha wrote: > also please could you tell me why you suggest wxPython over GTK? Support, there are probably more beginner friendly resources for wxPython than for GTk, although that is changing. > that wxPython is the easiet to pick up yet a lot more complete than > Tkinter? I can't really comment since Tkinter and wxPython are the only two i've really used. I did a PyQt tutorial a long time back and have never used GTk at all so can't really comment on them. > this has interested me. is embedded programming a different field to > the type of programming in Python? Yes, it is usually done using assembler and C or C++. Some embedded work nowadays is done in Java - a reflection of how cheap memory has become! > is your work today still related to this area? Not really, my company (a big telecomms business) got out of making bespoke hardware and now buys in standard commercial kit. My core job these days is as an "Enterprise Architect" and I do almost no programming now. I determine what IT systems are needed, the interfaces between them and review the high level systems designs. I act as a bridge between the business folks and the IT tech heads... I 'own' around 250 systems and oversee the technical work of around 1000 developers, with about 20 projects running at any one time. Python programming has become more of a hobby and personal productivity tool nowadays. It keeps me sane and connected! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Sep 5 19:49:05 2012 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 05 Sep 2012 10:49:05 -0700 Subject: [Tutor] help me decide In-Reply-To: References: <5046A014.6030907@btinternet.com> Message-ID: <50479091.4030101@alchemy.com> On 05-Sep-12 10:40, Alan Gauld wrote: > On 05/09/12 11:04, Matthew Ngaha wrote: > >> also please could you tell me why you suggest wxPython over GTK? > > Support, there are probably more beginner friendly resources for > wxPython than for GTk, although that is changing. Yeah, and wxPython is a large, comprehensive package that should handle all of your GUI needs and then some. I wrote one tool using wxPython and was quite happy with the results, and pleasantly surprised at the performance of widget updates and refreshes it achieved, even for the bits in pure Python. >> that wxPython is the easiet to pick up yet a lot more complete than >> Tkinter? Not sure about that. I started Tk programming back (way back) in my Tcl/Tk phase years ago, so I'm really used to Tk and that may bias me, but I'd say Tkinter is a lot easier to learn than wxPython, partly because it's smaller with fewer moving parts to tweak. And yet, Tkinter is complete enough to be quite satisfactory for a lot of applications. Even after using wx, I've gone back to Tkinter when it sufficed for my applications, since it's a little easier to use and is a lot easier to distribute, coming for free with Python and all that. >> this has interested me. is embedded programming a different field to >> the type of programming in Python? > > Yes, it is usually done using assembler and C or C++. > Some embedded work nowadays is done in Java - a reflection > of how cheap memory has become! Right. Although Java here doesn't necessarily mean the JVM is running on the embedded machine; it could be Java source code compiled down to something a compact runtime can execute. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From dwightdhutto at gmail.com Wed Sep 5 21:45:40 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 5 Sep 2012 15:45:40 -0400 Subject: [Tutor] help me decide In-Reply-To: <50479091.4030101@alchemy.com> References: <5046A014.6030907@btinternet.com> <50479091.4030101@alchemy.com> Message-ID: No matter what the kit used for GUI, make sure it's well documented, and has plenty of tuts/docs. I used tkinter, and wxpython, and like the widget set/cross OS usages in wxpython better. However, with more experience, now I'm moving toward the Blender Game Engine to give more feel, and a 3-d pop to my apps through it's Python API. So, consider that over time your preferences will change in relation to your knowledge, and the wisdom that comes with the application of this knowledge...experience. Also, don't get hung up on just python. Always take a beginner's guide or two with a well referenced language(all the way down to assembly/machine language) for familiarity. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Wed Sep 5 23:15:25 2012 From: wayne at waynewerner.com (Wayne Werner) Date: Wed, 5 Sep 2012 16:15:25 -0500 (CDT) Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: On Tue, 4 Sep 2012, Matthew Ngaha wrote: > a) IF you happen to have used both, which one fills you with joy and > is more fun for you to program with, GUI programming, or web related / > Framework programming? Honestly - both. It's really a highly subjective question and depends what you want to do (although with modern browsers like Google Chrome and Firefox the line is becoming more and more blurry). If you want to provide an application that requires no interaction with the outside world, a GUI is probably a better fit and has the advantage that you'll probably only be using one language - in this case, Python ;) But if you begin doing web programming then you'll start to learn about HTML, JavaScript, and CSS (all valuable technologies and look like they'll be here to stay!) > b) which was easier and less complex for you to learn? or should i say > had a lower learning curve? i ask this because the sooner i get an > understanding of one, i can maybe give the other one a go. But if it's > too hard i usually give 100% to it and never try learning anything > else until it computes. Honestly, I picked up learning HTML before I learned to actually program. That's what got me interested, was being able to make small changes in the text and see large changes happen in my page. I would say as far as complexity goes, learning basic GUI programming has less "pieces". But again, both directions are perfectly valid and valuable things to learn. > > my tutorial had a small section on tkinter. I have now looked for some > tutorials and noticed Python tutorials on both tkinter and Tk. As i > understand they are not the same thing but tkinter is like the > interface of Tk? my question is: I'm sure someone has addressed this already, but Tkinter is the Python bindings for Tk/Tcl. It allows you to write Python code to do Tk things. > c) which tutorial would be better to study, Tkinter or Tk? and what > exactly is the difference? why do they have separate tutorials? You would definitely want to focus on Tkinter - and there are quite a few good tutorials, including the effbot tutorial. That's a reference I turn to almost any time I'm doing Tkinter. > i looked at some pyQT articles, but its coding looks less organised > than Tkinter. I wouldn't say it's less organized, but there's a *lot* more to Qt than Tkinter. > d) is this true? is Tkinter a lot more straight forward and Python friendly? One thing I noticed about Qt is that you'll be using the Q key a lot. So your left pinky (assuming two hands and a Qwerty keyboard) will get a massive workout. It was super awkward for me while I was learning it. > e) Does pyQT have grids (rows and columns) to place your widgets on > like Tkinter, or do you have to use x and y axis to position widgets > etc..? You can do both... In terms of GUI frameworks, I rank them in this order from least- to most-complex: 1. Tkinter 2. wxPython 3. PyGTK+ 4. PyQt Tkinter is kinda the raw materials. You get a few widgets (though that's really grown in the past few years with ttk and tix), and some building blocks. wxPython gives you some tools to interface with the native UI - so if you set it up right, the same Python application will look like a "real" Windows app, a "real" Gnome(GTK) app, or what have you. PyGTK seems to me like it gives you a bit more than wx. Again, this is largely subjective. I used to do quite a bit with PyGTK. The normal GTK documentation maps quite well, though it can be a little difficult to figure out why something is doing what it's doing. PyQt... well that's everything and the kitchen sink. I mean seriously - there's a timer widget built in! It's quite the powerhouse, but ultimately I didn't like using my left pinky to hit the Q key so much. > Before i try to learn either, GUIs or a web Framework, i was looking > into maybe getting a deeper understanding of OOP. my tutorial only > covered it briefly. > > f) would this be a good idea tackling OOP next before the other 2, or > is this a skill you master with more programming experience? I personally would consider OOP fundamentals essential to learning GUI programming with anything besides Tkinter. It's pretty easy to write procedural-ish Tkinter code. > ok my last question is not so important:) im just curious as i grow > more fond of programming. well i keep reading Python is an all-purpose > general programming language(web frameworks, desktop apps, > science/maths etc..). I notice Java has similar features so should > also be considered an all-purpose general programming language. my > question is: > > g) not a comparison in 1 specific area, but which language is better > or more suited to all around all-purpose quality. I'm sure the other folks have mentioned that Java is an extremely verbose language that (at least to me) is entirely too noisy. I did *not* enjoy the two semesters in college that I had to use it. The term Martin Fowler uses to describe it is a "guiding" language. That means that Java has a certain way to do things and you don't really have a choice if you'd like to do it different. Python is an "enabling" language - which in my words means "it's a language that gets out of your way". My experience is that when I write Python code I can express the solution to a problem the way I want to. If it's easier to express the solution in an OOP way, I can do that. If it's easier to express procedurally, or even functionally, I can do that too. Which meant that it's easier to just get stuff done. I don't have to worry about how I can shoehorn the problem into something that the language can solve - I can just solve it. So I find great joy in writing Python code, and encourage everyone to learn it. My recommendation for you would be to learn some OOP basics, and once you feel comfortable around objects start learning Tkinter. Unless you really want to do some web programming, in which case, do that ;) HTH, Wayne From afowler2 at broncos.uncfsu.edu Thu Sep 6 00:10:35 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 5 Sep 2012 22:10:35 +0000 Subject: [Tutor] Student Class Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> I need help creating a student class. I am suppose to create a student class with there first name, last name, credits and gpa. Can anybody help me get started? Below is what needs to be included. For number one, is the variables suppose to be parameters? for instance, class Student: def __init__(self, name, hours, gpa): self.name = name 1. four instance variables: firstName (a string), lastName (a string), numCredits (an integer), gpa (a float); 2. an accessor method for each instance variable; 3. a mutator method for each instance variable; 4. an __init__ method that sets all the instance variables to values provided by the user; 5. a __str__ method that returns a string that contains all the data of the object in the order: firstName, lastName, numCredits, gpa. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Thu Sep 6 00:42:15 2012 From: dwightdhutto at gmail.com (Dwight Hutto) Date: Wed, 5 Sep 2012 18:42:15 -0400 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Wed, Sep 5, 2012 at 6:10 PM, Ashley Fowler wrote: > I need help creating a student class. I am suppose to create a student > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? > > for instance, > class Student: > def __init__(self, name, hours, gpa): > self.name = name > > self.name is bringing a more global variable into the class, so it can > be changed within the class, but remain the same outside of the class > called. > > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); > > Then you need the following in init: def __init__(self, first_name,last_name, numCredits,hours, gpa): self.first_name = first_name self.last_name = last_name self.numCredits = numCredits self.hours = hours self.gpa = gpa def whatever(self.first_name): self.first_name = "Bob" return self.first_name > 2. an accessor method for each instance variable; > > student = Student(first_name,last_name, numCredits,hours, gpa) > student.whatever(): > > > 3. a mutator method for each instance variable; > > Define mutator, is that just to change? > 4. an __init__ method that sets all the instance variables to values > provided by the user; > > look above at the init. > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. > > return : "%s , %s, %i, %i, i%" % (self.first_name, > self.last_name, self.numCredits, > self.hours, self.gpa ) > or something like that. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 01:39:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 00:39:25 +0100 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 05/09/12 23:10, Ashley Fowler wrote: > I need help creating a student class. We don't do your homework for you we will only offer hints. So you need to show us what you are trying and we will try to steer you to something better. > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? Normally yes, you'd make those variables the input parameters to the __init__() method. > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); These would normally be defined inside __init__() > 2. an accessor method for each instance variable; > 3. a mutator method for each instance variable; This is not good Python practice. It smells like Java... In python it's customary to access attributes directly. If you really want to use access methods then you should create a 'property' > 4. an __init__ method that sets all the instance variables to values > provided by the user; > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. These are fairly standard. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From afowler2 at broncos.uncfsu.edu Thu Sep 6 01:43:11 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Wed, 5 Sep 2012 23:43:11 +0000 Subject: [Tutor] Student Class In-Reply-To: References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com>, Message-ID: <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> so far i have: class Student: def __init__(self, first_name, last_name, numCredits, gpa): self.first_name = first_name self.last_name = last_name self.numCredits = numCredits self.gpa = gpa def getFirstname(self): return self.first_name def getLastname(self): return self.last_name def getNumCredits(self): return self.numCredits def getGpa(self): return self.gpa def setFirstname(self, first_name): self.first_name = first def setLastname(self, last_name): self.last_name = last def setNumcredits(self, numCredits): self.NumCredits = credit def setGpa(self, gpa): self.gpa = gpa def __str__(self): return (self.first_name, self.last_name, self.numCredits, self.gpa) ________________________________________ From: Tutor [tutor-bounces+afowler2=broncos.uncfsu.edu at python.org] on behalf of Alan Gauld [alan.gauld at btinternet.com] Sent: Wednesday, September 05, 2012 11:39 PM To: tutor at python.org Subject: Re: [Tutor] Student Class On 05/09/12 23:10, Ashley Fowler wrote: > I need help creating a student class. We don't do your homework for you we will only offer hints. So you need to show us what you are trying and we will try to steer you to something better. > class with there first name, last name, credits > and gpa. Can anybody help me get started? Below is what needs to be > included. For number one, is the variables > suppose to be parameters? Normally yes, you'd make those variables the input parameters to the __init__() method. > 1. four instance variables: firstName (a string), lastName (a string), > numCredits (an integer), gpa (a float); These would normally be defined inside __init__() > 2. an accessor method for each instance variable; > 3. a mutator method for each instance variable; This is not good Python practice. It smells like Java... In python it's customary to access attributes directly. If you really want to use access methods then you should create a 'property' > 4. an __init__ method that sets all the instance variables to values > provided by the user; > 5. a __str__ method that returns a string that contains all the data > of the object in the order: firstName, lastName, numCredits, gpa. These are fairly standard. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From me at staticsafe.ca Thu Sep 6 05:00:15 2012 From: me at staticsafe.ca (staticsafe) Date: Wed, 05 Sep 2012 23:00:15 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() Message-ID: <504811BF.2030506@staticsafe.ca> Hello, I am running Python 2.6.6 on a Debian Squeeze system. I am using two modules in this bit of code - datetime and python-tvrage (available on pypy here: http://pypi.python.org/pypi/python-tvrage/). My goal is to find the time remaining until a certain show airs. Here is some code I have written so far: #!/usr/bin/env python from tvrage import quickinfo from datetime import tzinfo, timedelta, datetime showinfo = quickinfo.fetch("Warehouse 13") nextairdate = showinfo['RFC3369'] now = datetime.now().isoformat() Now for my question/problem. In [68]: showinfo['RFC3339'] Out[68]: '2012-09-10T21:00:00-4:00' In [72]: datetime.now().isoformat() Out[72]: '2012-09-05T22:47:46.061688' isoformat() is in a different format than the value returned by the API. My question is how would one format both values so that I can perform a timedelta on them as is the purpose of my code? I hope I have provided the right amount of detail for my question. Thanks, -- staticsafe http://staticsafe.ca From eryksun at gmail.com Thu Sep 6 08:05:34 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 02:05:34 -0400 Subject: [Tutor] Student Class In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C63561F38E0F9@BL2PRD0710MB363.namprd07.prod.outlook.com> <6962C976AE76AC4298CBF6FD6D0C63561F38E13E@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On Wed, Sep 5, 2012 at 7:43 PM, Ashley Fowler wrote: > > class Student: Are you using Python 3? If not, Student should explicitly inherit from object. > def __init__(self, first_name, last_name, numCredits, gpa): > self.first_name = first_name > self.last_name = last_name > self.numCredits = numCredits > self.gpa = gpa Your requirements specify firstName and lastName, not first_name and last_name. > def getFirstname(self): > return self.first_name All of the function definitions below __init__ need to be dedented one level. You have them defined in __init__. > def setFirstname(self, first_name): > self.first_name = first 'first' isn't defined. You named the parameter "first_name". > def setLastname(self, last_name): > self.last_name = last Neither is 'last' defined. > def setNumcredits(self, numCredits): > self.NumCredits = credit Neither is 'credit' defined. Plus this method creates a new attribute named NumCredits. The name in __init__ is numCredits. > def __str__(self): > return (self.first_name, self.last_name, self.numCredits, self.gpa) The __str__ method absolutely needs to return a string. Use string formatting via 'format' or the old modulo formatting. http://docs.python.org/py3k/library/string.html#format-examples http://docs.python.org/py3k/library/stdtypes.html#old-string-formatting-operations From tokyo.rook at gmail.com Thu Sep 6 09:21:05 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Thu, 6 Sep 2012 03:21:05 -0400 Subject: [Tutor] Hey.need help on time Message-ID: been trying to change this so it wont use my server time. but my actual time here in the us.EST. havent been able to figure it out def sstime(user, body, m): os.environ['TZ'] = 'US/Eastern' tstr1 = time.strftime("%a, %b-%d-%Y", time.tzset()) tstr2 = time.strftime("%I:%M:%S %p", time.tzset()) tstr3 = time.strftime("%Z", time.tzset()) return Html("Today is %s and The current time is %s (%s)" % (tstr1, tstr2, tstr3)) -- ~~Austin From eryksun at gmail.com Thu Sep 6 09:35:54 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 03:35:54 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() In-Reply-To: <504811BF.2030506@staticsafe.ca> References: <504811BF.2030506@staticsafe.ca> Message-ID: On Wed, Sep 5, 2012 at 11:00 PM, staticsafe wrote: > > In [68]: showinfo['RFC3339'] > Out[68]: '2012-09-10T21:00:00-4:00' You can parse the ISO format using the dateutil module: http://labix.org/python-dateutil >>> from dateutil.parser import parse >>> show_time = parse('2012-09-10T21:00:00-4:00') This produces a time-zone aware datetime object. You can pass its tzinfo to datetime.now() to get the current time as an aware datetime object: >>> now = datetime.now(show_time.tzinfo) Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo. It doesn't matter if you're only interested in the timedelta. From __peter__ at web.de Thu Sep 6 09:39:19 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 09:39:19 +0200 Subject: [Tutor] Formatting questions regarding datetime.isoformat() References: <504811BF.2030506@staticsafe.ca> Message-ID: staticsafe wrote: > Hello, > > I am running Python 2.6.6 on a Debian Squeeze system. I am using two > modules in this bit of code - datetime and python-tvrage (available on > pypy here: http://pypi.python.org/pypi/python-tvrage/). > > My goal is to find the time remaining until a certain show airs. Here is > some code I have written so far: > > #!/usr/bin/env python > from tvrage import quickinfo > from datetime import tzinfo, timedelta, datetime > > showinfo = quickinfo.fetch("Warehouse 13") > nextairdate = showinfo['RFC3369'] > now = datetime.now().isoformat() > > Now for my question/problem. > > In [68]: showinfo['RFC3339'] > Out[68]: '2012-09-10T21:00:00-4:00' > > In [72]: datetime.now().isoformat() > Out[72]: '2012-09-05T22:47:46.061688' > > isoformat() is in a different format than the value returned by the API. > My question is how would one format both values so that I can perform a > timedelta on them as is the purpose of my code? > > I hope I have provided the right amount of detail for my question. After some trial and error: import dateutil.parser # python-dateutil import pytz # python-tz import datetime show_start = dateutil.parser.parse("2012-09-10T21:00:00-0400") now = datetime.datetime.now(pytz.timezone("EST")) print "show starts: ", show_start print "current time:", now print "days to go: ", show_start - now (Caveat: I'm using Python 2.7) From eryksun at gmail.com Thu Sep 6 09:51:36 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 03:51:36 -0400 Subject: [Tutor] Hey.need help on time In-Reply-To: References: Message-ID: On Thu, Sep 6, 2012 at 3:21 AM, Keitaro Kaoru wrote: > been trying to change this so it wont use my server time. but my > actual time here in the us.EST. havent been able to figure it out > > def sstime(user, body, m): > os.environ['TZ'] = 'US/Eastern' Now just call time.tzset(), and it should work. > tstr1 = time.strftime("%a, %b-%d-%Y", time.tzset()) I don't know what you're doing here. strftime() uses localtime() if you don't provide a time tuple. time.tzset() just returns None. From ahmetcan196 at gmail.com Thu Sep 6 09:59:37 2012 From: ahmetcan196 at gmail.com (Ahmet Can KEPENEK) Date: Thu, 6 Sep 2012 10:59:37 +0300 Subject: [Tutor] Python Xmpp Received Message Message-ID: I wrote application with xmpp. It sending message from gtalk. I want to print received message. How can i do? My application short code as follows. def process_message(): client = xmpp.Client('gmail.com') client.connect( server=('talk.google.com',5223) ) client.auth(user,passwd, 'botty') to = raw_input("to: "); if client: message = raw_input("message: ") client.send( xmpp.Message( to,message ) ) if __name__ == "__main__": user = raw_input("User: ") passwd = getpass.getpass("Pass: ") process_message() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 10:17:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:17:05 +0100 Subject: [Tutor] Python Xmpp Received Message In-Reply-To: References: Message-ID: On 06/09/12 08:59, Ahmet Can KEPENEK wrote: > I wrote application with xmpp. It sending message from gtalk. I want to > print received message. How can i do? This mailing list is really for people learning Python and its standard library. Your question is mainly about xmpp which I assume is some kind of Google API? Whether you get an answer will depend on how lucky you are as to whether anyone here has used xmpp. You will likely get a better response on an xmpp forum or even on the main Python mailing list/newsgroup: comp.lang.python HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ianodonovan63 at gmail.com Tue Sep 4 21:36:28 2012 From: ianodonovan63 at gmail.com (Ian o donovan) Date: Tue, 4 Sep 2012 20:36:28 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: Hey, I am writing this to you because I want to know could you help. My school is doing enterprise and I want to enter. I really want to make a program that will clean up your desktop E.G put files you haven't used for a while into a folder and delete your trash they are just a few ideas. I am trying to learn programming but I live in Ireland and where I live they is not much access to courses so I have to wait till college to learn programming. I have tried to learn some of python through on-line tutorials but find it hard So what I am asking is could you help me make a program if not I understand as I can imagine ye are very busy people. Thanks for reading this. Ian Lawlor From jacklittlemc at yahoo.com Mon Sep 3 16:39:58 2012 From: jacklittlemc at yahoo.com (Jack Little) Date: Mon, 3 Sep 2012 07:39:58 -0700 (PDT) Subject: [Tutor] Help Message-ID: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> > Ok, I am somewhat new to python, and I am making a text-based RPG. I get a > weird error with this code: > > > #A Python text-RPG > #A Jak Production > #APOC > global ammo > global health > global lives > global exp > global food > ammo=55 > health = 100 > lives=10 > exp = 0 > food = 30 > > def part1(): >? ? print "50 Days After The Outbreak:You are standing outside of the Empire > State Building." >? ? print "Vines, plants, dirt, and grime cover its once-regal surfaces. > Huh." >? ? print "I guess if 80% of the world is dead, more people are concerned > about survival than sightseeing.God." >? ? print "Generally,us survivors tend to band together. Mostly? it is for > good. Not the bandits." >? ? print "? Bandit:'Hey you! What you got in that bag?" >? ? print "I recognized this Bandit as Sam Cabelo. He was the janitor at my > office building. Not the nicest fellow." >? ? answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' > button.") >? ? if answer == "SHOW" or answer == "Show" or answer == "show": >? ? ? ? print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He > says this like a threat, reinforced by that revolver in his hand" >? ? ? ? answer2 = raw_input("Type either Hand it over or flee") >? ? ? ? if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 > == "hand it over": >? ? ? ? ? ? print "Bandit: Good Job.. Go on now" >? ? ? ? ? ? ammo=ammo-15 >? ? ? ? ? ? food=food-10 >? ? ? ? ? ? return answer3 >? ? ? ? if answer2 == "FLEE" or answer2 == "Flee" or answer2 == "flee": >? ? ? ? ? ? print "He shot you" >? ? ? ? ? ? lives=lives-1 >? ? ? ? else: >? ? ? ? ? ? print "TYPE? SOMETHING CORRECTLY" >? ? ? ? ? ? return part1 > >? ? elif answer == "run away" or "Run Away" or "RUN AWAY": >? ? ? ? print "He shot you... hee hee hee" >? ? ? ? print "When the input comes up again, type a differet answer" >? ? else: >? ? ? ? print "You didn't type Show or run away." >? ? ? ? part1() > > part1() > > > Here is my error, if it helps > > Traceback (most recent call last): >? File "C:\Users\Jack\Desktop\game2.py", line 45, in >? ? part1() >? File "C:\Users\Jack\Desktop\game2.py", line 28, in part1 >? ? ammo=ammo-15 > UnboundLocalError: local variable 'ammo' referenced before assignment > > > Thanks, > Jack Little? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Sep 6 10:23:23 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 04:23:23 -0400 Subject: [Tutor] Formatting questions regarding datetime.isoformat() In-Reply-To: <504855DE.4090303@davea.name> References: <504811BF.2030506@staticsafe.ca> <504855DE.4090303@davea.name> Message-ID: On Thu, Sep 6, 2012 at 3:50 AM, Dave Angel wrote: > On 09/06/2012 03:35 AM, eryksun wrote: >> >> Or you could use datetime.now(dateutil.tz.tzutc()) for a UTC tzinfo. >> It doesn't matter if you're only interested in the timedelta. > > Actually, it can matter. Whenever possible, produce all times as UTC > and do your manipulations (eg. difference) in that space. With local > time, there are times that don't exist and times that are ambiguous, one > in the fall and one in the spring, due to setting the clock forward or back. > > i don't know for sure if it matters here, but I've found it's better to > work that way. These are aware datetime objects. See the datetime docs for supported operations, case 3, timedelta = datetime1 - datetime2: http://docs.python.org/library/datetime#datetime.datetime.tzinfo From jason.j.fremouw at gmail.com Tue Sep 4 20:52:04 2012 From: jason.j.fremouw at gmail.com (Jason Fremouw) Date: Tue, 4 Sep 2012 13:52:04 -0500 Subject: [Tutor] Python 2.7.3, Pygame, and LiveWires Message-ID: Hello, My name is Jason Fremouw. I recently began a Structured Programming course using Python as the tool with which we'll learn. The media packages listed above come as add-ons in my text book but are not compatible with 2.7. Are these now built into the latest build of Python or are they listed as different downloads on Python.org? Any help would be greatly appreciated! Thank you. Best, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From sales at myspcworks.com Thu Sep 6 06:43:43 2012 From: sales at myspcworks.com (Sales) Date: Wed, 5 Sep 2012 21:43:43 -0700 Subject: [Tutor] python wifi Message-ID: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Hello, I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: easy_install python_wifi-0.5.0-py2.5.egg I also tried: sudo easy_install python_wifi-0.5.0-py2.5.egg I pasted the output error below. I'm not familiar with easy_install or python wifi. What am I doing wrong here? thanks! Downloading http://pypi.python.org/packages/any/p/python-wifi/python_wifi-0.5.0-py2.5.egg#md5=d7995ad357387d3c2f8b13bcac5c4e20, Processing python_wifi-0.5.0-py2.5.egg Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_wifi-0.5.0-py2.5.egg Moving python_wifi-0.5.0-py2.5.egg to /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages python-wifi 0.5.0 is already the active version in easy-install.pth Installed /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/python_wifi-0.5.0-py2.5.egg Processing dependencies for python-wifi==0.5.0 Searching for python-wifi==0.5.0 Reading http://pypi.python.org/simple/python-wifi/ Reading http://pythonwifi.wikispot.org Reading https://developer.berlios.de/projects/pythonwifi/ Reading http://www.romanofski.de/downloads/pywifi No local packages or download links found for python-wifi==0.5.0 Best match: None Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/bin/easy_install", line 8, in load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1712, in main File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1716, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 211, in run File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 422, in easy_install File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 478, in install_item File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 519, in process_distribution File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 563, in resolve File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 799, in best_match File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 811, in obtain File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 434, in easy_install File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/package_index.py", line 475, in fetch_distribution AttributeError: 'NoneType' object has no attribute 'clone' From crawlzone at gmail.com Thu Sep 6 10:25:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 01:25:52 -0700 Subject: [Tutor] Hey.need help on time In-Reply-To: References: Message-ID: <50485E10.3040605@gmail.com> On 09/06/2012 12:51 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 3:21 AM, Keitaro Kaoru wrote: >> been trying to change this so it wont use my server time. but my >> actual time here in the us.EST. havent been able to figure it out >> >> def sstime(user, body, m): >> os.environ['TZ'] = 'US/Eastern' > Now just call time.tzset(), and it should work. Why the additional step of calling time.tzset()? Once os.environ['TZ'] is set, I've found that time.localtime() responds to the new TZ without anything extra. Is that a difference in versions (2.7.3 here)? Ray From breamoreboy at yahoo.co.uk Thu Sep 6 10:27:30 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Sep 2012 09:27:30 +0100 Subject: [Tutor] math description In-Reply-To: References: Message-ID: On 29/08/2012 21:20, damjan kuzmic wrote: > Hello, > i would like to know how to write a formula that in excell looks like this: > > A / EXP(-LN(2) * t) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Start here http://docs.python.org/tutorial/ -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Thu Sep 6 10:29:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:29:19 +0100 Subject: [Tutor] apologies for any duplicate mails coming through Message-ID: I've just been into the admin interface and flushed a heap of messages in the moderators queue. I hadn't logged in for a while and quite a stack had built up - mostly spam... :-( Some were a few weeks old so apologies if some of them have already been seen and dealt with. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 10:35:37 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 01:35:37 -0700 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: <50486059.5080604@gmail.com> On 09/03/2012 07:39 AM, Jack Little wrote: > > Ok, I am somewhat new to python, and I am making a text-based RPG. I get a > > weird error with this code: > > > > > > #A Python text-RPG > > #A Jak Production > > #APOC > > global ammo > > global health > > global lives > > global exp > > global food > > ammo=55 > > health = 100 > > lives=10 > > exp = 0 > > food = 30 > > > > def part1(): > > print "50 Days After The Outbreak:You are standing outside of the Empire > > State Building." > > print "Vines, plants, dirt, and grime cover its once-regal surfaces. > > Huh." > > print "I guess if 80% of the world is dead, more people are concerned > > about survival than sightseeing.God." > > print "Generally,us survivors tend to band together. Mostly it is for > > good. Not the bandits." > > print " Bandit:'Hey you! What you got in that bag?" > > print "I recognized this Bandit as Sam Cabelo. He was the janitor at my > > office building. Not the nicest fellow." > > answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' > > button.") > > if answer == "SHOW" or answer == "Show" or answer == "show": > > print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He > > says this like a threat, reinforced by that revolver in his hand" > > answer2 = raw_input("Type either Hand it over or flee") > > if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 > > == "hand it over": > > print "Bandit: Good Job.. Go on now" > > ammo=ammo-15 > > I'll take a stab at it. You are using attempting to modify a global variable within a procedure. Procedure variables are separate from global variables. Global variables must be passed into a procedure using something on the order of 'part1(ammo)', and then returned back from the procedure with a 'return ' Ray From alan.gauld at btinternet.com Thu Sep 6 10:35:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 09:35:35 +0100 Subject: [Tutor] math description In-Reply-To: References: Message-ID: On 29/08/12 21:20, damjan kuzmic wrote: > Hello, > i would like to know how to write a formula that in excell looks like this: > > A / EXP(-LN(2) * t) Start by breaking it down from the inside out. LN(2) is log(2) in Python, which is found in the math module so you need import math too. negation ( -LN() ) and multiplication are builtin (* t) EXP() is exp(), also in the math module. division is built in (although I'm not sure if Excel / is integer or 'real' division, given the nature of the values I'll assume its real... So the final expression should look like import math ... value = A/math.exp(-math.log(2) * t) Which isn't too different to Excel. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Thu Sep 6 10:36:59 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 04:36:59 -0400 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On Fri, Aug 17, 2012 at 4:11 PM, Matthew Love wrote: > def inventory(self): > self.inventory = ["torch"] > return self.inventory What is 'self.inventory' before you call inventory(), and what is it afterwards? A quick fix would be to name the list "_inventory" and return self._inventory. From d at davea.name Thu Sep 6 10:51:51 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 04:51:51 -0400 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: <50486427.8020102@davea.name> On 09/03/2012 10:39 AM, Jack Little wrote: >> Ok, I am somewhat new to python, and I am making a text-based RPG. I get a >> weird error with this code: >> >> >> #A Python text-RPG >> #A Jak Production >> #APOC >> global ammo >> global health >> global lives >> global exp >> global food >> ammo=55 >> health = 100 >> lives=10 >> exp = 0 >> food = 30 >> >> def part1(): >> print "50 Days After The Outbreak:You are standing outside of the Empire >> State Building." >> print "Vines, plants, dirt, and grime cover its once-regal surfaces. >> Huh." >> print "I guess if 80% of the world is dead, more people are concerned >> about survival than sightseeing.God." >> print "Generally,us survivors tend to band together. Mostly it is for >> good. Not the bandits." >> print " Bandit:'Hey you! What you got in that bag?" >> print "I recognized this Bandit as Sam Cabelo. He was the janitor at my >> office building. Not the nicest fellow." >> answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' >> button.") >> if answer == "SHOW" or answer == "Show" or answer == "show": >> print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He >> says this like a threat, reinforced by that revolver in his hand" >> answer2 = raw_input("Type either Hand it over or flee") >> if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 >> == "hand it over": >> print "Bandit: Good Job.. Go on now" >> ammo=ammo-15 >> food=food-10 >> return answer3 >> if answer2 == "FLEE" or answer2 == "Flee" or answer2 == "flee": >> print "He shot you" >> lives=lives-1 >> else: >> print "TYPE SOMETHING CORRECTLY" >> return part1 >> >> elif answer == "run away" or "Run Away" or "RUN AWAY": >> print "He shot you... hee hee hee" >> print "When the input comes up again, type a differet answer" >> else: >> print "You didn't type Show or run away." >> part1() >> >> part1() >> >> >> Here is my error, if it helps >> >> Traceback (most recent call last): >> File "C:\Users\Jack\Desktop\game2.py", line 45, in >> part1() >> File "C:\Users\Jack\Desktop\game2.py", line 28, in part1 >> ammo=ammo-15 >> UnboundLocalError: local variable 'ammo' referenced before assignment >> >> >> Thanks, >> Jack Little > > Your global declarations are all at top-level scope, where they are meaningless. All variables defined there are global. What you want for ammo is a global declaration inside the function. By convention, you declare any globals at the top of the function, right after the def and the doc-string. You'll also need global declarations for food and lives, and perhaps others I didn't notice. Other things I notice: You omitted the parentheses in one reference to part1. So it doesn't get called there. You try to use those part1() calls as some form of looping construct. Instead you should use a while loop or similar. That also will avoid the problem you've got now where if a person types nonsense to the second question, he ends up being asked the first question again. Use lower() method on strings to avoid needing multiple comparisons: if answer2.lower() == "flee": -- DaveA From chigga101 at gmail.com Thu Sep 6 10:54:26 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 6 Sep 2012 09:54:26 +0100 Subject: [Tutor] help me decide In-Reply-To: References: Message-ID: hey guys i just like to thank everyone for their input. Its really helped me in deciding a lot of things. also @ Alan i think? as ive started writing this mail it won;t let me look up previous senders but thanks for your input. Also your field of work sounds very interesting indeed. I can't dare to imagine the amount of hard work that got you there.:) i only hope my dedication can take me half as far:) Best wishes to everyone:x From __peter__ at web.de Thu Sep 6 10:56:15 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 10:56:15 +0200 Subject: [Tutor] math description References: Message-ID: damjan kuzmic wrote: > i would like to know how to write a formula that in excell looks like > this: > > A / EXP(-LN(2) * t) >>> import math >>> A = 1.23 >>> t = 4.56 Literally (math.log is the natural logarithm): >>> A / math.exp(-math.log(2) * t) 29.013618196288864 However, exp(-x) == 1 / exp(x) and exp(ln(a)*x) == a ** x so you better spell it >>> A * 2 ** t 29.013618196288864 From d at davea.name Thu Sep 6 10:59:30 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 04:59:30 -0400 Subject: [Tutor] python 2.7.1 In-Reply-To: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: <504865F2.3070102@davea.name> On 08/20/2012 12:47 AM, john wrote: > print "hello world" #this is just something to say > > > > > >>>> /Users/jonathan/Documents/hello.py > File "", line 1 > /Users/jonathan/Documents/hello.py > ^ > SyntaxError: invalid syntax > > what am i doing wrong? > > > it would help if you showed the actual content of hello.py. Looks to me like the first line looks like: /Users/jonathan/Documents/hello.py Comment that out, and see what happens. -- DaveA From alan.gauld at btinternet.com Thu Sep 6 11:00:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:00:20 +0100 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On 17/08/12 21:11, Matthew Love wrote: > class Player(object): > > def inventory(self): > self.inventory = ["torch"] > return self.inventory Notice that you override the name inventory. Initially self.inventory is the inventory() method. But then you change self.inventory to be a list. So the next time you call player.inventory() you are trying to execute the list hence the error. You need to change the name of the inventory attribute to something like theInventory... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Sep 6 11:02:52 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 05:02:52 -0400 Subject: [Tutor] Python In-Reply-To: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> References: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> Message-ID: <504866BC.6060600@davea.name> On 08/19/2012 04:42 PM, Andrew Rosen wrote: > I have a Windows Computer and I'm trying to make a shortcut on my desktop that will run a program, so I don't have to open up a New Window form Python Shell and use that to run the program. I can't figure out how to do it, can you help me? > This is a Windows question, not a Python one. But I'll take a crack at it, since I used to run Windows. Use right-click on the desktop and choose "create shortcut" from the context menu. Fill in the name of your script. Give the shortcut a useful name. This assumes that you have the usual file associations stored in the registry. They are what tells the Windows system how to run a *.py file -- DaveA From eryksun at gmail.com Thu Sep 6 11:08:18 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 6 Sep 2012 05:08:18 -0400 Subject: [Tutor] Hey.need help on time In-Reply-To: <50485E10.3040605@gmail.com> References: <50485E10.3040605@gmail.com> Message-ID: On Thu, Sep 6, 2012 at 4:25 AM, Ray Jones wrote: > > Why the additional step of calling time.tzset()? Once os.environ['TZ'] > is set, I've found that time.localtime() responds to the new TZ without > anything extra. Is that a difference in versions (2.7.3 here)? It shouldn't strictly be necessary using glibc. I checked the source. glibc localtime calls __tz_convert() on each call, which calls tzset_internal() to update the TZ setting. However, I don't think that's guaranteed in all C runtimes. As the Python docs say, "[c]hanging the TZ environment variable without calling tzset *may* change the local timezone used by methods such as localtime, but this behaviour should not be relied on." From __peter__ at web.de Thu Sep 6 11:10:01 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 11:10:01 +0200 Subject: [Tutor] python 2.7.1 References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: john wrote: > print "hello world" #this is just something to say >>>> /Users/jonathan/Documents/hello.py > File "", line 1 > /Users/jonathan/Documents/hello.py > ^ > SyntaxError: invalid syntax > > what am i doing wrong? The >>> prompt indicates that you have already started the interactive interpreter by typing $python This is a great way to test Python statements interactively -- type and explore Python's response. However, to run a script you have to provide the script name on the commandline$ python /Users/jonathan/Documents/hello.py From d at davea.name Thu Sep 6 11:13:40 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 05:13:40 -0400 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> Message-ID: <50486944.8030100@davea.name> On 08/18/2012 09:17 PM, vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input, but the print statement adds a newline. If it were adding to each > individual element, I could solve it easily, but it is adding one at the end > of the array. Is there another way to print an array besides > > print arrayname > > If it were a string, I have a whole host of options, but I need it to be > output as an array. Each element is a url. I call it from a browser, and it > works except for the added newline. > > Here are the relevant lines: > > ================= > /* code that connects to cloudfiles omitted */ > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html\n\n"; > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > try: > del wholelist[int(sys.argv[1]):] > while i < int(sys.argv[1]): > newlist.append("http://example.com/"+wholelist[i].rstrip()) > i = i+1 > except IndexError, e: > del newlist[5] > print newlist > ============== > > The output I am seeing is as follows: > > ['http://example.com/wet-longhaireddachshund.jpg', > 'http://example.com/dachshund2.jpg', > 'http://example.com/dachshundingrass.jpg'] > > Any tips on better coding practices are welcome, but please don't beat me up > > Thanks, > vickistan > > > I don't see any arrays in that code, just lists. i also don't see how that program could produce exactly that ouput, as it also prints "Content-type: text/html\n\n"; But if you literally mean that only the final newline is a problem, then just end the print statement with a comma: print newlist, If you want more flexibility, instead of printing the list as a single entity, you can just loop through it. that way, you can choose which newlines you want, if any. for item in newlist: print repr(item), #or many other variants. But you probably want some delimeter at least. it's not clear what your other program is expecting for stdin, since there is no single standard for "takes an array for input." it's also unclear why a trailing linefeed should hurt you. But I hope this will help some. -- DaveA From alan.gauld at btinternet.com Thu Sep 6 11:15:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:15:19 +0100 Subject: [Tutor] Help In-Reply-To: <50486059.5080604@gmail.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> <50486059.5080604@gmail.com> Message-ID: On 06/09/12 09:35, Ray Jones wrote: >>> #A Python text-RPG >>> #A Jak Production >>> #APOC >>> global ammo You use global inside a function not outside. All variables declared at the module level are global by definition. >>> ammo=55 This sets the global ammo value >>> def part1(): >>> if answer == "SHOW" or answer == "Show" or answer == "show": >>> answer2 = raw_input("Type either Hand it over or flee") >>> if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 >>> == "hand it over": >>> print "Bandit: Good Job.. Go on now" >>> ammo=ammo-15 Here you try to create a local variable in the function butuse that variable in its definition. What you really wanted was to use the global ammo. To do that you need to tell the function that any reference to ammo will use the global value, like this def part1(): global ammo at the top of the function. Ray added: > I'll take a stab at it. You are using attempting to modify a global > variable within a procedure. Procedure variables are separate from > global variables. Global variables must be passed into a procedure using > something on the order of 'part1(ammo)', and then returned back from the > procedure with a 'return ' That's not strictly true, as explained above. However, it is generally considered good programming practice not to rely on globals but to pass values in as parameters as you do in your example here. So good practice says part1() should be defined as: def part1(theAmmo, theFood, theLives): # as is code... Notice I changed the names to distinguish them from the global variables. and you call it using the global variables as: part1(ammo,food,lives) The other thing to note is that at one point you use return part1 That returns the function itself which is almost certainly not what you want. You also return answer3 which doesn't seem to be defined anywhere. Returning lots of different values from the same function will make it very hard to use. You should think about breaking this down into the code that gets the user responses and separate code that returns the required values, one value per function. And finally at the end you call part() from within part(), that's a technique called recursion and can get you into all sorts of problems if you don't know what you are doing with it. What you really want is a loop that repeats the input code until you get valid values. A while loop is probably best in this case. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 6 11:18:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:18:26 +0100 Subject: [Tutor] Python 2.7.3, Pygame, and LiveWires In-Reply-To: References: Message-ID: On 04/09/12 19:52, Jason Fremouw wrote: > packages listed above come as add-ons in my text book but are not > compatible with 2.7. Are these now built into the latest build of Python > or are they listed as different downloads on Python.org? No, the livewires and pygame packages are not part of core python. You will either need to find more recent versions of the packages that are compatible or downgrade python to a version that is compatible with the packages! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 11:23:45 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 02:23:45 -0700 Subject: [Tutor] Hey.need help on time In-Reply-To: References: <50485E10.3040605@gmail.com> Message-ID: <50486BA1.1020904@gmail.com> On 09/06/2012 02:08 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 4:25 AM, Ray Jones wrote: >> Why the additional step of calling time.tzset()? Once os.environ['TZ'] >> is set, I've found that time.localtime() responds to the new TZ without >> anything extra. Is that a difference in versions (2.7.3 here)? > It shouldn't strictly be necessary using glibc. I checked the source. > glibc localtime calls __tz_convert() on each call, which calls > tzset_internal() to update the TZ setting. However, I don't think > that's guaranteed in all C runtimes. As the Python docs say, > "[c]hanging the TZ environment variable without calling tzset *may* > change the local timezone used by methods such as localtime, but this > behaviour should not be relied on." Got ya. I'll remember that. Ray From alan.gauld at btinternet.com Thu Sep 6 11:21:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:21:06 +0100 Subject: [Tutor] Python In-Reply-To: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> References: <1345408977.91331.YahooMailNeo@web65506.mail.ac4.yahoo.com> Message-ID: On 19/08/12 21:42, Andrew Rosen wrote: > I have a Windows Computer and I'm trying to make a shortcut on my > desktop that will run a program, so I don't have to open up a New Window > form Python Shell and use that to run the program. I can't figure out > how to do it, can you help me? Create a shortcut to the python script in Windows explorer and drag that to your desktop. If python is installed properly you should be able to double click it and python will run it. If it's a console program you might need to add a line at the end like raw_input('hit enter to quit') # python v2.x input('hit enter to quit') # python v3.x To prevent the program closing before you can see it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From omar.aboumrad at gmail.com Thu Sep 6 11:28:17 2012 From: omar.aboumrad at gmail.com (Omar Abou Mrad) Date: Thu, 6 Sep 2012 12:28:17 +0300 Subject: [Tutor] Doing the same thing twice. Works first time but not the second. In-Reply-To: References: Message-ID: On Fri, Aug 17, 2012 at 11:11 PM, Matthew Love wrote: > > This is the error: > > Traceback (most recent call last): > File "C:\Users\Matthew\Desktop\test.py", line 16, in > print(player.inventory()) > TypeError: 'list' object is not callable > > The python debugger can also give you a hint of how player.inventory changed: misc $pdb test.py -> class Player(object): (Pdb) n -> player = Player() (Pdb) n Player created. -> player.inventory() (Pdb) whatis player.inventory *Function inventory* (Pdb) n -> player.inventory() (Pdb) whatis player.inventory ** -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 6 11:24:09 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:24:09 +0100 Subject: [Tutor] python 2.7.1 In-Reply-To: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> References: <4C6597F7-E210-4EF8-803A-26F299B25DF4@yahoo.com> Message-ID: On 20/08/12 05:47, john wrote: > print"hello world"#this is just something to say > > > >>> /Users/jonathan/Documents/hello.py You don;t run Python scripts from the python prompt. You only type Python co0mmands there. You could import your file which wiull run it but the effect is slightly different. Its better to run scripts from the OS prompt$ python /Users/jonathan/Documents/hello.py -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 6 11:31:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 10:31:20 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> Message-ID: On 19/08/12 02:17, vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input You are printing a list. You are not passing an 'array' to anything. What exavctly does the other program expect to see. An array object - as defined in what language? or a list of strings? or something else. > the print statement adds a newline. It also prints the string representation of your list. If you want to print the contents of the list use a loop: for item in arrayname: print item That will give you the items each on a separate line but without the [] If you want it on a single line add a comma: for item in arrayname: print item, # python 2, python 3 is different And if you don't want spaces use join(): print ''.join(arrayname) > of the array. Is there another way to print an array besides > > print arrayname See above. but without knowing what your other program expect an 'array' to look like we can't say what is best. > output as an array. Each element is a url. I call it from a browser, and it > works except for the added newline. That suggests that you might actually want to create an html document? If you need a file its best to create a file rather than rely on print statements. IMHO... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Thu Sep 6 11:39:11 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 6 Sep 2012 10:39:11 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: Hi Ian, On 4 September 2012 20:36, Ian o donovan wrote: > Hey, I am writing this to you because I want to know could you help. > My school is doing enterprise and I want to enter. What do you mean your school is "doing enterprise"? Is it some competition or something? > I really want to > make a program that will clean up your desktop E.G put files you > haven't used for a while into a folder and delete your trash they are > just a few ideas. I am trying to learn programming but I live in > Ireland and where I live they is not much access to courses so I have > to wait till college to learn programming. I have tried to learn some > of python through on-line tutorials but find it hard So what I am > asking is > could you help me make a program if not I understand as I can imagine > ye are very busy people. You're at the right place to ask beginner Python questions. Feel free to try stuff and ask questions when you run into problems. Be sure to post complete error messages, what you've tried, what happened and what you expected to happen instead. As for courses, you may want to look into the following free educational offerings where you can learn basic programming in a structured manner: https://www.coursera.org/course/interactivepython http://www.udacity.com/overview/Course/cs101/CourseRev/apr2012 http://www.khanacademy.org/science/computer-science https://www.edx.org/courses/HarvardX/CS50x/2012/about Be sure to browse around the sites, most of the sites have multiple courses available. HTH Walter From oscar.j.benjamin at gmail.com Thu Sep 6 11:44:42 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 06 Sep 2012 10:44:42 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <1345339036049-4985646.post@n6.nabble.com> References: <1345339036049-4985646.post@n6.nabble.com> <1345339036049-4985646.post@n6.nabble.com> Message-ID: On Sat, 18 Aug 2012 18:17:16 -0700 (PDT), vickistan wrote: > Hello: I am trying to output an array to another program that takes an array > as input, but the print statement adds a newline. If it were adding to each > individual element, I could solve it easily, but it is adding one at the end > of the array. Is there another way to print an array besides > print arrayname Yes. You can use: print arrayname, Note the trailing comma ',' character at the end of the print statement. In python 2 this is the normal way to stop print from adding a newline. It's a silly syntax that has been fixed in python 3. If your using python 3 then it looks like print(arrayname, end='') which makes a bit more sense to me. By the way what your calling an array, python calls a list. In python the word array is usually used to refer to a number of other things. As a more general comment: are you the author of both programs? If so then you can choose a different format for outputting your data. My default choice would be to print out each url on a separate line, without the square brackets or commas. You can do that with: for url in arrayname: print url Note that I want print to add the newlines. This is a common way of working with text files and this is the reason that print adds a newline. Oscar From bgailer at gmail.com Thu Sep 6 15:44:46 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Sep 2012 09:44:46 -0400 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: References: Message-ID: <5048A8CE.3040009@gmail.com> On 8/18/2012 10:12 AM, ??? wrote: > > I need to find some way how i can get mac address of windows 7 in python. Windows 7 does not have a MAC address. It is an operating system. Ethernet adapters have MAC addresses. Your computer will have one or more Ethernet adapter. From a command prompt enter ipconfig /all You will see something like (this is from MY computer, Windows 2008 Server, similar to Win 7): Windows IP Configuration Host Name . . . . . . . . . . . . : xxx Primary Dns Suffix . . . . . . . : xxx Node Type . . . . . . . . . . . . : Hybrid IP Routing Enabled. . . . . . . . : Yes WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : xxx Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : Description . . . . . . . . . . . : Intel(R) 82579LM Gigabit Network Connecti on Physical Address. . . . . . . . . : 44-37-E6-63-86-B9 DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::e102:17d6:8b9d:43be%10(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.0.190(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.0.1 DHCPv6 IAID . . . . . . . . . . . : 172242918 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-16-8E-75-AE-44-37-E6-63-86-B9 DNS Servers . . . . . . . . . . . : ::1 127.0.0.1 NetBIOS over Tcpip. . . . . . . . : Enabled Ethernet adapter VMware Network Adapter VMnet1: Connection-specific DNS Suffix . : Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet 1 Physical Address. . . . . . . . . : 00-50-56-C0-00-01 DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::7c33:3774:7709:c50d%15(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.29.1(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : DHCPv6 IAID . . . . . . . . . . . : 419450966 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-16-8E-75-AE-44-37-E6-63-86-B9 DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1 fec0:0:0:ffff::2%1 fec0:0:0:ffff::3%1 NetBIOS over Tcpip. . . . . . . . : Enabled etc. Each Ethernet adapter has a Physical Address (MAC Address). When you run ipconfig /all - if you see only one Physical Address, then that is the one you want. If you see more than one then you must decide which Ethernet adapter you want. Then you use Popen (in subprocess module) to run ipconfig /all, capture the output and parse it for the desired Ethernet adapter, then parse that section for the Physical Address. There may be another (better?, easier?) way but this will work. -- Bob Gailer 919-636-4239 Chapel Hill NC From crawlzone at gmail.com Thu Sep 6 15:56:17 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 06:56:17 -0700 Subject: [Tutor] Making big 'uns into little 'uns Message-ID: <5048AB81.7050905@gmail.com> I have a multiple 'if' expression that I need to drastically reduce in size, both for readability and to keep errors from creeping in. For example, I would like to have the variable 'test' point to the a location 'grid[rcount-1][ccount-1]' so that everywhere I would use 'grid.....', I could replace it with 'test' How would I accomplish that? Thanks. Ray From d at davea.name Thu Sep 6 16:10:13 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:10:13 -0400 Subject: [Tutor] how to print array without adding newline In-Reply-To: <20120906134954.22610.qmail@server308.com> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> <20120906134954.22610.qmail@server308.com> Message-ID: <5048AEC5.8020504@davea.name> On 09/06/2012 09:49 AM, vicki at thepenguin.org wrote: > Thank you for your reply. I understand that it is odd, but my program is being called from a hubot and returning data to it as well. I have figured out how to make the changes to get it to output the correct data in the correct format, but now I am getting a "Premature end of script headers" error. I have the correct #! line and the output from the command line shows no errors that would be interfering. Is there a way to make sure it is showing me all the errors? To increase error logging? > ------ > !/usr/bin/env python You top-posted, so I have to clip both the earlier messages out. On this forum, we put responses immediately AFTER the part we quoted. I don't see how I can possibly help further, without buying a hubot of my own. I don't know what operating system you're running this on, nor what the command lines look like. I have no idea how the stdout of your script migrates over to the hubot's processor. Nor why it only gets some of the stdout. You could give us more environmental data (OS version, command line, any messages, ...), or tell what the hubot's docs say you should use as a format. > import cloudfiles > import random > import sys > import array > > conn = cloudfiles.get_connection('username', 'key') > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html"; Perhaps you need a blank line to be output here. One way is just print by itself. > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > #newlist=wholelist[:] > try: > # print sys.argv[1] > if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") > # print sys.argv[1] > del wholelist[int(sys.argv[1]):] > while i < int(sys.argv[1]): > newlist.append("http://example.com/"+wholelist[i].rstrip()) > i = i+1 > except IndexError, e: Where do you alert the user about this exception? > del newlist[5] > except Exception, err: > print 'Caught an exception' You should probably send this and any other error messages to stderr, as stdout is presumably being consumed by the robot. > print newlist, > ------- -- DaveA From d at davea.name Thu Sep 6 16:15:42 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:15:42 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: <5048B00E.2020301@davea.name> On 09/06/2012 09:56 AM, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? > > Thanks. > > Easiest way: switch to C++ There is no preprocessor in Python, and no addresses. There are some places you could fake such stuff, but not the expression you have. If I HAD to do something like this for Python, I'd write a preprocessor. But one reason I came to Python is its elegance, and a preprocessor isn't elegant. -- DaveA From crawlzone at gmail.com Thu Sep 6 16:15:53 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:15:53 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B00E.2020301@davea.name> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> Message-ID: <5048B019.5010709@gmail.com> On 09/06/2012 07:15 AM, Dave Angel wrote: > On 09/06/2012 09:56 AM, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? >> >> Thanks. >> >> > Easiest way: switch to C++ > > There is no preprocessor in Python, and no addresses. There are some > places you could fake such stuff, but not the expression you have. > > If I HAD to do something like this for Python, I'd write a > preprocessor. But one reason I came to Python is its elegance, and a > preprocessor isn't elegant. Well, of all the..... a REAL programming language..... I mean, even Bash.... ;;)) Anyway, it was a shot. Thanks. Ray > From __peter__ at web.de Thu Sep 6 16:33:53 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Sep 2012 16:33:53 +0200 Subject: [Tutor] Making big 'uns into little 'uns References: <5048AB81.7050905@gmail.com> Message-ID: Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? >>> class Grid(object): ... def __init__(self, rows): ... self.rows = rows ... def __getitem__(self, index): ... return self.rows[index] ... @property ... def test(self): ... return self[-1][-1] ... >>> grid = Grid([[1,2,3], [4,5,6], [7,8,9], [10,11,12]]) >>> grid[1] [4, 5, 6] >>> grid[1][2] 6 >>> grid.test 12 From malaclypse2 at gmail.com Thu Sep 6 16:35:24 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 6 Sep 2012 10:35:24 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B019.5010709@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: On Thu, Sep 6, 2012 at 10:15 AM, Ray Jones wrote: > Well, of all the..... a REAL programming language..... I mean, even > Bash.... ;;)) > > Anyway, it was a shot. Thanks. There's almost certainly a way to accomplish your goal of simplifying your giant nested if statements. It just doesn't involve pointers. Perhaps if you mocked up a representative example for us to look at and play with, someone could come up with a suggestion. For instance, if your set of if statements is emulating what would be done with a case statement in other languages, dictionary based dispatch may be a cleaner way to do the same thing in python. -- Jerry From crawlzone at gmail.com Thu Sep 6 16:34:04 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:34:04 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> Message-ID: <5048B45C.9050105@gmail.com> On 09/06/2012 07:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? >>>> class Grid(object): > ... def __init__(self, rows): > ... self.rows = rows > ... def __getitem__(self, index): > ... return self.rows[index] > ... @property > ... def test(self): > ... return self[-1][-1] > ... Excellent! Now I am going to save this message for the time when I've advanced to classes and objects! Thanks, Peter. Ray From d at davea.name Thu Sep 6 16:48:45 2012 From: d at davea.name (Dave Angel) Date: Thu, 06 Sep 2012 10:48:45 -0400 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B019.5010709@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: <5048B7CD.4090403@davea.name> On 09/06/2012 10:15 AM, Ray Jones wrote: > On 09/06/2012 07:15 AM, Dave Angel wrote: >> On 09/06/2012 09:56 AM, Ray Jones wrote: >>> I have a multiple 'if' expression that I need to drastically reduce in >>> size, both for readability and to keep errors from creeping in. >>> >>> For example, I would like to have the variable 'test' point to the a >>> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >>> 'grid.....', I could replace it with 'test' How would I accomplish that? >>> >>> Thanks. >>> >>> >> Easiest way: switch to C++ >> >> There is no preprocessor in Python, and no addresses. There are some >> places you could fake such stuff, but not the expression you have. >> >> If I HAD to do something like this for Python, I'd write a >> preprocessor. But one reason I came to Python is its elegance, and a >> preprocessor isn't elegant. > Well, of all the..... a REAL programming language..... I mean, even > Bash.... ;;)) > > Anyway, it was a shot. Thanks. > > I don't know your use-case. For that matter, I don't even know what semantics you mean by the grid[xx][yy] expression. For example, are grid, rcount, and ccount globals? Or are you constraining 'test' to only be used in the context where they are all visible? Or are you defining this location as the offset within grid where rcount and ccount happen to point to right now? I can see maybe a dozen "reasonable" meanings, each requiring a different sets of constructs in the language or its preprocessor. One thing you can do in Python, but not in any other language I've used, is to define a class instance property. For example, if you were willing to use q.test instead of test, you could do something like: class Q(object): @property def test(self): return grid[rcount-1][ccount-1] That would give you readonly access to an object defined by 3 variables that have to be visible to the Q code. And you could make the expression more complex if grid is defined elsewhere, for example. Now once you do q = Q(), you can use q.test instead of the larger expression. Lots of other possibilities in Python. But not with exactly your original syntax. Using this one as is would be ugly code, as is your original example. So presumably you have an actual use-case where this makes sense, other than saving typing. -- DaveA From crawlzone at gmail.com Thu Sep 6 16:50:30 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:50:30 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> Message-ID: <5048B836.4030002@gmail.com> On 09/06/2012 07:35 AM, Jerry Hill wrote: > On Thu, Sep 6, 2012 at 10:15 AM, Ray Jones wrote: >> Well, of all the..... a REAL programming language..... I mean, even >> Bash.... ;;)) >> >> Anyway, it was a shot. Thanks. > There's almost certainly a way to accomplish your goal of simplifying > your giant nested if statements. It just doesn't involve pointers. > Perhaps if you mocked up a representative example for us to look at > and play with, someone could come up with a suggestion. > > For instance, if your set of if statements is emulating what would be > done with a case statement in other languages, dictionary based > dispatch may be a cleaner way to do the same thing in python. > Thanks for the reply, Jerry. I actually can do it relatively easily with just a few nested 'if' statements.....I was trying multiple tests within the same 'if' statement. I'm simplifying it by changing into a 0-based loop rather than a 1-based loop (don't have to worry about the '-1' stuff). I'm not certain where I'm going with it yet - it's a udacity assignment that I'm still trying to work out in my head. Ray From crawlzone at gmail.com Thu Sep 6 16:59:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 07:59:52 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048B7CD.4090403@davea.name> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> Message-ID: <5048BA68.5090400@gmail.com> On 09/06/2012 07:48 AM, Dave Angel wrote: >>> On 09/06/2012 09:56 AM, Ray Jones wrote: >>>> I have a multiple 'if' expression that I need to drastically reduce in >>>> size, both for readability and to keep errors from creeping in. >>>> >>>> For example, I would like to have the variable 'test' point to the a >>>> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >>>> 'grid.....', I could replace it with 'test' How would I accomplish that? >>>> >>>> Thanks. >>>> >>>> >>> > I don't know your use-case. For that matter, I don't even know what > semantics you mean by the grid[xx][yy] expression. For example, are > grid, rcount, and ccount globals? Or are you constraining 'test' to > only be used in the context where they are all visible? Or are you > defining this location as the offset within grid where rcount and ccount > happen to point to right now? I can see maybe a dozen "reasonable" > meanings, each requiring a different sets of constructs in the language > or its preprocessor. > > One thing you can do in Python, but not in any other language I've used, > is to define a class instance property. For example, if you were > willing to use q.test instead of test, you could do something like: > > class Q(object): > @property > def test(self): > return grid[rcount-1][ccount-1] > > That would give you readonly access to an object defined by 3 variables > that have to be visible to the Q code. And you could make the > expression more complex if grid is defined elsewhere, for example. > > Now once you do q = Q(), you can use > q.test instead of the larger expression. > > Lots of other possibilities in Python. But not with exactly your > original syntax. Using this one as is would be ugly code, as is your > original example. So presumably you have an actual use-case where this > makes sense, other than saving typing. > Basically it's as simple as ensuring that an array consists of integers, and that those integers fall within a certain range. Rather than using multiple 'if' statements, I was (am, at this point) using multiple tests within a single 'if' statement. Nothing earth-shatteringly difficult, but I was simply looking for a way to shorten the overall test expression with a recursive(? is that the term) variable. No problem though. Thanks. Ray From wprins at gmail.com Thu Sep 6 17:29:08 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 6 Sep 2012 16:29:08 +0100 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048BA68.5090400@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: Hi Ray, On 6 September 2012 15:59, Ray Jones wrote: > Basically it's as simple as ensuring that an array consists of integers, > and that those integers fall within a certain range. Rather than using > multiple 'if' statements, I was (am, at this point) using multiple tests > within a single 'if' statement. Nothing earth-shatteringly difficult, > but I was simply looking for a way to shorten the overall test > expression with a recursive(? is that the term) variable. No problem though. By array I suppose you mean "list of lists of items"? Anyway, if you have such a structure, and you want to "visit" each in turn to check it, you can do this: for sublist in grid: for item in sublist: # code to check if "item" is in range goes here The above obviously doesn't actually track the "row" or "column" you're checking. If you'd like to keep track of what "row"/"column" you're on, you can for example do: for row, sublist in enumerate(grid): for col, item in enumerate(sublist): # code to check if "item" is in range goes here HTH, Walter From oscar.j.benjamin at gmail.com Thu Sep 6 17:34:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 6 Sep 2012 15:34:06 +0000 (UTC) Subject: [Tutor] Making big 'uns into little 'uns References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: On 2012-09-06, Ray Jones wrote: > > Basically it's as simple as ensuring that an array consists of integers, > and that those integers fall within a certain range. Rather than using > multiple 'if' statements, I was (am, at this point) using multiple tests > within a single 'if' statement. Nothing earth-shatteringly difficult, > but I was simply looking for a way to shorten the overall test > expression with a recursive(? is that the term) variable. No problem though. > > Thanks. How about using a generator expression with all()? For example: >>> def isint(n): ... return int(n) == n ... >>> def isinrange(n, a, b): ... return a <= n <= b ... >>> numbers = [11, 12, 14, 15] >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) True >>> numbers[0] = 9 >>> numbers [9, 12, 14, 15] >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) False >>> numbers[0] = 14.5 >>> all(isint(x) and isinrange(x, 10, 20) for x in numbers) False Oscar From crawlzone at gmail.com Thu Sep 6 17:33:57 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 08:33:57 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> Message-ID: <5048C265.7080902@gmail.com> On 09/06/2012 08:29 AM, Walter Prins wrote: > Hi Ray, > > On 6 September 2012 15:59, Ray Jones wrote: >> Basically it's as simple as ensuring that an array consists of integers, >> and that those integers fall within a certain range. Rather than using >> multiple 'if' statements, I was (am, at this point) using multiple tests >> within a single 'if' statement. Nothing earth-shatteringly difficult, >> but I was simply looking for a way to shorten the overall test >> expression with a recursive(? is that the term) variable. No problem though. > By array I suppose you mean "list of lists of items"? Yes. > Anyway, if you have such a structure, and you want to "visit" each in > turn to check it, you can do this: > > for sublist in grid: > for item in sublist: > # code to check if "item" is in range goes here > > The above obviously doesn't actually track the "row" or "column" > you're checking. If you'd like to keep track of what "row"/"column" > you're on, you can for example do: > > for row, sublist in enumerate(grid): > for col, item in enumerate(sublist): > # code to check if "item" is in range goes here Our homework "monitor" complains if we use code that hasn't been discussed in session yet. We haven't even progressed to 'range' in the for loops yet - I don't think 'enumerate' would be appreciated. lol Technically, any variable pointer that I had managed to drum up here would have been frowned upon, but I didn't figure it would have been a serious breach. I've got a pretty good handle on doing it the "hard way". I'm swatting bugs right now... :)) Ray From emile at fenx.com Thu Sep 6 18:36:05 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 06 Sep 2012 09:36:05 -0700 Subject: [Tutor] python wifi In-Reply-To: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> References: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Message-ID: On 9/5/2012 9:43 PM Sales said... > Hello, > I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: > > easy_install python_wifi-0.5.0-py2.5.egg > > I also tried: > > sudo easy_install python_wifi-0.5.0-py2.5.egg Now try the "[sudo ]easy_install python_wifi" variants. IIRC, the py2.5 in the egg name indicated compatibility for python .25 and you've said you've got 2.7 installed so let'd first try to let it pick the compatible version and see what we get. Emile From alan.gauld at btinternet.com Thu Sep 6 19:00:37 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 18:00:37 +0100 Subject: [Tutor] how to print array without adding newline In-Reply-To: <5048AEC5.8020504@davea.name> References: <1345339036049-4985646.post@n6.nabble.com> <50486944.8030100@davea.name> <20120906134954.22610.qmail@server308.com> <5048AEC5.8020504@davea.name> Message-ID: On 06/09/12 15:10, Dave Angel wrote: >> except Exception, err: >> print 'Caught an exception' > > You should probably send this and any other error messages to stderr, as > stdout is presumably being consumed by the robot. And you probably shouldn't use such a bland error message for every possible error. At the very least print the error type but better still store the error data in a log file if you can't just print it out. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From malaclypse2 at gmail.com Thu Sep 6 19:06:17 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 6 Sep 2012 13:06:17 -0400 Subject: [Tutor] python wifi In-Reply-To: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> References: <8B2209DB-806B-4726-96A3-53C7DD29ECBE@myspcworks.com> Message-ID: On Thu, Sep 6, 2012 at 12:43 AM, Sales wrote: > Hello, > I'm trying to install python wifi using easy install. I have python27 and working on mac os. from a shell I'm running: > > easy_install python_wifi-0.5.0-py2.5.egg The "py2.5" in the file name suggests that you're trying to install a version of this code that was compiled for python 2.5. If you're using python 2.7, as you say, that isn't going to work. Also, the project's homepage on the cheeseshop says "Python WiFi is a Python module that provides read and write access to a wireless network card's capabilities using the Linux Wireless Extensions". Does Mac OS X support the Linux Wireless Extensions? If not, I don't think this package is going to be of any help to you at all. -- Jerry From alan.gauld at btinternet.com Thu Sep 6 19:05:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Sep 2012 18:05:25 +0100 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: On 06/09/12 14:56, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? I may have missed some messages but this is context free. What are these multiple if statements? Why would "reducing" them improve readability? It might make them shorter but more cryptic. As to the other question, is test = grid[rcount-1][ccount-1] too obvious? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Thu Sep 6 19:22:23 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 10:22:23 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: References: <5048AB81.7050905@gmail.com> Message-ID: <5048DBCF.8050700@gmail.com> On 09/06/2012 10:05 AM, Alan Gauld wrote: > On 06/09/12 14:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? > > > I may have missed some messages but this is context free. > What are these multiple if statements? > Why would "reducing" them improve readability? It might make them > shorter but more cryptic. > > As to the other question, is > > test = grid[rcount-1][ccount-1] > > too obvious? > I went out to the kitchen for a bit to eat an hour or so ago and suddenly did a face-palm! Duh! I'm going to have to quit dog-sitting for my niece - these all-nighters are killing my thinking ability! Ray From breamoreboy at yahoo.co.uk Thu Sep 6 19:32:54 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Sep 2012 18:32:54 +0100 Subject: [Tutor] Help In-Reply-To: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> References: <1346683198.17619.YahooMailNeo@web125304.mail.ne1.yahoo.com> Message-ID: On 03/09/2012 15:39, Jack Little wrote: >> Ok, I am somewhat new to python, and I am making a text-based RPG. I get a >> weird error with this code: [snip] > >> >> Thanks, >> Jack Little > Further to the sound advice you've already been given a rather more informative subject line would have been helpful :) My apologies if someone has already said this and I've missed it. -- Cheers. Mark Lawrence. From steve at pearwood.info Fri Sep 7 02:31:31 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:31:31 +1000 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048AB81.7050905@gmail.com> References: <5048AB81.7050905@gmail.com> Message-ID: <50494063.5040703@pearwood.info> On 06/09/12 23:56, Ray Jones wrote: > I have a multiple 'if' expression that I need to drastically reduce in > size, both for readability and to keep errors from creeping in. > > For example, I would like to have the variable 'test' point to the a > location 'grid[rcount-1][ccount-1]' so that everywhere I would use > 'grid.....', I could replace it with 'test' How would I accomplish that? Um, am I missing something blindingly obvious here? What about this? test = grid[rcount-1][ccount-1] # I can never think of good names... if test < 1: process(test) elif test == 1: do_something_different(test, 2, 3, 4) elif 1 < test <= 100: do_another_thing(test, "ham", "cheese") # and so on... -- Steven From steve at pearwood.info Fri Sep 7 02:34:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:34:22 +1000 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5048C265.7080902@gmail.com> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> <5048C265.7080902@gmail.com> Message-ID: <5049410E.20607@pearwood.info> On 07/09/12 01:33, Ray Jones wrote: > Our homework "monitor" complains if we use code that hasn't been > discussed in session yet. The good old "teaching by enforced ignorance" method. -- Steven From steve at pearwood.info Fri Sep 7 02:37:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 07 Sep 2012 10:37:22 +1000 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: <5048A8CE.3040009@gmail.com> References: <5048A8CE.3040009@gmail.com> Message-ID: <504941C2.9070907@pearwood.info> On 06/09/12 23:44, bob gailer wrote: > On 8/18/2012 10:12 AM, ??? wrote: >> >> I need to find some way how i can get mac address of windows 7 in python. > Windows 7 does not have a MAC address. It is an operating system. > > Ethernet adapters have MAC addresses. Your computer will have one or more >Ethernet adapter. Just to be pedantic, your computer will have ZERO or more Ethernet adapters. Although if you are receiving email and getting on the Internet on your computer, it must have at least one. -- Steven From crawlzone at gmail.com Fri Sep 7 04:07:27 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 19:07:27 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <50494063.5040703@pearwood.info> References: <5048AB81.7050905@gmail.com> <50494063.5040703@pearwood.info> Message-ID: <504956DF.5010101@gmail.com> On 09/06/2012 05:31 PM, Steven D'Aprano wrote: > On 06/09/12 23:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.....', I could replace it with 'test' How would I accomplish that? > > Um, am I missing something blindingly obvious here? > > What about this? > > test = grid[rcount-1][ccount-1] # I can never think of good names... > if test < 1: > process(test) > elif test == 1: > do_something_different(test, 2, 3, 4) > elif 1 < test <= 100: > do_another_thing(test, "ham", "cheese") > # and so on... > No, you're not missing something blindingly obvious - I was! Ray From crawlzone at gmail.com Fri Sep 7 04:14:32 2012 From: crawlzone at gmail.com (Ray Jones) Date: Thu, 06 Sep 2012 19:14:32 -0700 Subject: [Tutor] Making big 'uns into little 'uns In-Reply-To: <5049410E.20607@pearwood.info> References: <5048AB81.7050905@gmail.com> <5048B00E.2020301@davea.name> <5048B019.5010709@gmail.com> <5048B7CD.4090403@davea.name> <5048BA68.5090400@gmail.com> <5048C265.7080902@gmail.com> <5049410E.20607@pearwood.info> Message-ID: <50495888.2090805@gmail.com> On 09/06/2012 05:34 PM, Steven D'Aprano wrote: > On 07/09/12 01:33, Ray Jones wrote: > >> Our homework "monitor" complains if we use code that hasn't been >> discussed in session yet. > > The good old "teaching by enforced ignorance" method. > Actually I like what they're doing. First of all, this is a CS101 class - not a Python class. I've done some (relatively - from my viewpoint) advanced programming by knowing what I wanted to accomplish and finding a (in the past) Bash tool to accomplish it. In fact, as I've been converting my Bash scripts to Python, I've been doing pretty much the same thing (which is why I subscribed to this list ;) ). But somewhere along the line I will be trying to do something that a specific tool won't accomplish: I'll have to use my brain! I've never known what I could and could not accomplish without another, stronger, tool, so I never really tried. Now I'm learning to apply my mind to problems that I KNOW can be accomplished with basic code and applying my mind to solving the problems. ;) Ray From alan.gauld at btinternet.com Fri Sep 7 09:26:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Sep 2012 08:26:21 +0100 Subject: [Tutor] How to get MAC address using Python at windows 7 In-Reply-To: <504941C2.9070907@pearwood.info> References: <5048A8CE.3040009@gmail.com> <504941C2.9070907@pearwood.info> Message-ID: On 07/09/12 01:37, Steven D'Aprano wrote: > On 06/09/12 23:44, bob gailer wrote: >> On 8/18/2012 10:12 AM, ??? wrote: >>> >>> I need to find some way how i can get mac address of windows 7 >> Ethernet adapters have MAC addresses. Your computer will have one or more >> Ethernet adapter. > > Just to be pedantic, your computer will have ZERO or more Ethernet > adapters. > Although if you are receiving email and getting on the Internet on your > computer, it must have at least one. Unless you are using dial-up... :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From crawlzone at gmail.com Fri Sep 7 17:16:41 2012 From: crawlzone at gmail.com (Ray Jones) Date: Fri, 07 Sep 2012 08:16:41 -0700 Subject: [Tutor] urllib2.urlopen(....., timeout=) Message-ID: <504A0FD9.6010500@gmail.com> 2.7.3 According to the docs, urlopen has a timeout capability. But it says that the timeout = '